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"
15 #include "MCTargetDesc/X86ShuffleDecode.h"
16 #include "X86.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/BlockFrequencyInfo.h"
30 #include "llvm/Analysis/ObjCARCUtil.h"
31 #include "llvm/Analysis/ProfileSummaryInfo.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/IntrinsicLowering.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineModuleInfo.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/TargetLowering.h"
42 #include "llvm/CodeGen/WinEHFuncInfo.h"
43 #include "llvm/IR/CallingConv.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/EHPersonalities.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GlobalAlias.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/IRBuilder.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/PatternMatch.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/CommandLine.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MathExtras.h"
63 #include "llvm/Target/TargetOptions.h"
64 #include <algorithm>
65 #include <bitset>
66 #include <cctype>
67 #include <numeric>
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "x86-isel"
71 
72 static cl::opt<int> ExperimentalPrefInnermostLoopAlignment(
73     "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
74     cl::desc(
75         "Sets the preferable loop alignment for experiments (as log2 bytes) "
76         "for innermost loops only. If specified, this option overrides "
77         "alignment set by x86-experimental-pref-loop-alignment."),
78     cl::Hidden);
79 
80 static cl::opt<bool> MulConstantOptimization(
81     "mul-constant-optimization", cl::init(true),
82     cl::desc("Replace 'mul x, Const' with more effective instructions like "
83              "SHIFT, LEA, etc."),
84     cl::Hidden);
85 
X86TargetLowering(const X86TargetMachine & TM,const X86Subtarget & STI)86 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
87                                      const X86Subtarget &STI)
88     : TargetLowering(TM), Subtarget(STI) {
89   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
90   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
91 
92   // Set up the TargetLowering object.
93 
94   // X86 is weird. It always uses i8 for shift amounts and setcc results.
95   setBooleanContents(ZeroOrOneBooleanContent);
96   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
97   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
98 
99   // For 64-bit, since we have so many registers, use the ILP scheduler.
100   // For 32-bit, use the register pressure specific scheduling.
101   // For Atom, always use ILP scheduling.
102   if (Subtarget.isAtom())
103     setSchedulingPreference(Sched::ILP);
104   else if (Subtarget.is64Bit())
105     setSchedulingPreference(Sched::ILP);
106   else
107     setSchedulingPreference(Sched::RegPressure);
108   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
109   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
110 
111   // Bypass expensive divides and use cheaper ones.
112   if (TM.getOptLevel() >= CodeGenOptLevel::Default) {
113     if (Subtarget.hasSlowDivide32())
114       addBypassSlowDiv(32, 8);
115     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
116       addBypassSlowDiv(64, 32);
117   }
118 
119   // Setup Windows compiler runtime calls.
120   if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
121     static const struct {
122       const RTLIB::Libcall Op;
123       const char * const Name;
124       const CallingConv::ID CC;
125     } LibraryCalls[] = {
126       { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
127       { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
128       { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
129       { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
130       { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
131     };
132 
133     for (const auto &LC : LibraryCalls) {
134       setLibcallName(LC.Op, LC.Name);
135       setLibcallCallingConv(LC.Op, LC.CC);
136     }
137   }
138 
139   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
140     // MSVCRT doesn't have powi; fall back to pow
141     setLibcallName(RTLIB::POWI_F32, nullptr);
142     setLibcallName(RTLIB::POWI_F64, nullptr);
143   }
144 
145   if (Subtarget.canUseCMPXCHG16B())
146     setMaxAtomicSizeInBitsSupported(128);
147   else if (Subtarget.canUseCMPXCHG8B())
148     setMaxAtomicSizeInBitsSupported(64);
149   else
150     setMaxAtomicSizeInBitsSupported(32);
151 
152   setMaxDivRemBitWidthSupported(Subtarget.is64Bit() ? 128 : 64);
153 
154   setMaxLargeFPConvertBitWidthSupported(128);
155 
156   // Set up the register classes.
157   addRegisterClass(MVT::i8, &X86::GR8RegClass);
158   addRegisterClass(MVT::i16, &X86::GR16RegClass);
159   addRegisterClass(MVT::i32, &X86::GR32RegClass);
160   if (Subtarget.is64Bit())
161     addRegisterClass(MVT::i64, &X86::GR64RegClass);
162 
163   for (MVT VT : MVT::integer_valuetypes())
164     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
165 
166   // We don't accept any truncstore of integer registers.
167   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
168   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
169   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
170   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
171   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
172   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
173 
174   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
175 
176   // SETOEQ and SETUNE require checking two conditions.
177   for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
178     setCondCodeAction(ISD::SETOEQ, VT, Expand);
179     setCondCodeAction(ISD::SETUNE, VT, Expand);
180   }
181 
182   // Integer absolute.
183   if (Subtarget.canUseCMOV()) {
184     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
185     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
186     if (Subtarget.is64Bit())
187       setOperationAction(ISD::ABS          , MVT::i64  , Custom);
188   }
189 
190   // Absolute difference.
191   for (auto Op : {ISD::ABDS, ISD::ABDU}) {
192     setOperationAction(Op                  , MVT::i8   , Custom);
193     setOperationAction(Op                  , MVT::i16  , Custom);
194     setOperationAction(Op                  , MVT::i32  , Custom);
195     if (Subtarget.is64Bit())
196      setOperationAction(Op                 , MVT::i64  , Custom);
197   }
198 
199   // Signed saturation subtraction.
200   setOperationAction(ISD::SSUBSAT          , MVT::i8   , Custom);
201   setOperationAction(ISD::SSUBSAT          , MVT::i16  , Custom);
202   setOperationAction(ISD::SSUBSAT          , MVT::i32  , Custom);
203   if (Subtarget.is64Bit())
204     setOperationAction(ISD::SSUBSAT        , MVT::i64  , Custom);
205 
206   // Funnel shifts.
207   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
208     // For slow shld targets we only lower for code size.
209     LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
210 
211     setOperationAction(ShiftOp             , MVT::i8   , Custom);
212     setOperationAction(ShiftOp             , MVT::i16  , Custom);
213     setOperationAction(ShiftOp             , MVT::i32  , ShiftDoubleAction);
214     if (Subtarget.is64Bit())
215       setOperationAction(ShiftOp           , MVT::i64  , ShiftDoubleAction);
216   }
217 
218   if (!Subtarget.useSoftFloat()) {
219     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
220     // operation.
221     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
222     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
223     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
224     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
225     // We have an algorithm for SSE2, and we turn this into a 64-bit
226     // FILD or VCVTUSI2SS/SD for other targets.
227     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
228     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
229     // We have an algorithm for SSE2->double, and we turn this into a
230     // 64-bit FILD followed by conditional FADD for other targets.
231     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
232     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
233 
234     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
235     // this operation.
236     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
237     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
238     // SSE has no i16 to fp conversion, only i32. We promote in the handler
239     // to allow f80 to use i16 and f64 to use i16 with sse1 only
240     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
241     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
242     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
243     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
244     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
245     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
246     // are Legal, f80 is custom lowered.
247     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
248     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
249 
250     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
251     // this operation.
252     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
253     // FIXME: This doesn't generate invalid exception when it should. PR44019.
254     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
255     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
256     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
257     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
258     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
259     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
260     // are Legal, f80 is custom lowered.
261     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
262     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
263 
264     // Handle FP_TO_UINT by promoting the destination to a larger signed
265     // conversion.
266     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
267     // FIXME: This doesn't generate invalid exception when it should. PR44019.
268     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
269     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
270     // FIXME: This doesn't generate invalid exception when it should. PR44019.
271     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
272     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
273     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
274     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
275     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
276 
277     setOperationAction(ISD::LRINT,             MVT::f32, Custom);
278     setOperationAction(ISD::LRINT,             MVT::f64, Custom);
279     setOperationAction(ISD::LLRINT,            MVT::f32, Custom);
280     setOperationAction(ISD::LLRINT,            MVT::f64, Custom);
281 
282     if (!Subtarget.is64Bit()) {
283       setOperationAction(ISD::LRINT,  MVT::i64, Custom);
284       setOperationAction(ISD::LLRINT, MVT::i64, Custom);
285     }
286   }
287 
288   if (Subtarget.hasSSE2()) {
289     // Custom lowering for saturating float to int conversions.
290     // We handle promotion to larger result types manually.
291     for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
292       setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
293       setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
294     }
295     if (Subtarget.is64Bit()) {
296       setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
297       setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
298     }
299   }
300 
301   // Handle address space casts between mixed sized pointers.
302   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
303   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
304 
305   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
306   if (!Subtarget.hasSSE2()) {
307     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
308     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
309     if (Subtarget.is64Bit()) {
310       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
311       // Without SSE, i64->f64 goes through memory.
312       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
313     }
314   } else if (!Subtarget.is64Bit())
315     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
316 
317   // Scalar integer divide and remainder are lowered to use operations that
318   // produce two results, to match the available instructions. This exposes
319   // the two-result form to trivial CSE, which is able to combine x/y and x%y
320   // into a single instruction.
321   //
322   // Scalar integer multiply-high is also lowered to use two-result
323   // operations, to match the available instructions. However, plain multiply
324   // (low) operations are left as Legal, as there are single-result
325   // instructions for this in x86. Using the two-result multiply instructions
326   // when both high and low results are needed must be arranged by dagcombine.
327   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
328     setOperationAction(ISD::MULHS, VT, Expand);
329     setOperationAction(ISD::MULHU, VT, Expand);
330     setOperationAction(ISD::SDIV, VT, Expand);
331     setOperationAction(ISD::UDIV, VT, Expand);
332     setOperationAction(ISD::SREM, VT, Expand);
333     setOperationAction(ISD::UREM, VT, Expand);
334   }
335 
336   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
337   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
338   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
339                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
340     setOperationAction(ISD::BR_CC,     VT, Expand);
341     setOperationAction(ISD::SELECT_CC, VT, Expand);
342   }
343   if (Subtarget.is64Bit())
344     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
345   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
346   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
347   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
348 
349   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
350   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
351   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
352   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
353 
354   if (!Subtarget.useSoftFloat() && Subtarget.hasX87()) {
355     setOperationAction(ISD::GET_ROUNDING   , MVT::i32  , Custom);
356     setOperationAction(ISD::SET_ROUNDING   , MVT::Other, Custom);
357     setOperationAction(ISD::GET_FPENV_MEM  , MVT::Other, Custom);
358     setOperationAction(ISD::SET_FPENV_MEM  , MVT::Other, Custom);
359     setOperationAction(ISD::RESET_FPENV    , MVT::Other, Custom);
360   }
361 
362   // Promote the i8 variants and force them on up to i32 which has a shorter
363   // encoding.
364   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
365   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
366   // Promoted i16. tzcntw has a false dependency on Intel CPUs. For BSF, we emit
367   // a REP prefix to encode it as TZCNT for modern CPUs so it makes sense to
368   // promote that too.
369   setOperationPromotedToType(ISD::CTTZ           , MVT::i16  , MVT::i32);
370   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , MVT::i32);
371 
372   if (!Subtarget.hasBMI()) {
373     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
374     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
375     if (Subtarget.is64Bit()) {
376       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
377       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
378     }
379   }
380 
381   if (Subtarget.hasLZCNT()) {
382     // When promoting the i8 variants, force them to i32 for a shorter
383     // encoding.
384     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
385     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
386   } else {
387     for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
388       if (VT == MVT::i64 && !Subtarget.is64Bit())
389         continue;
390       setOperationAction(ISD::CTLZ           , VT, Custom);
391       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
392     }
393   }
394 
395   for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
396                   ISD::STRICT_FP_TO_FP16}) {
397     // Special handling for half-precision floating point conversions.
398     // If we don't have F16C support, then lower half float conversions
399     // into library calls.
400     setOperationAction(
401         Op, MVT::f32,
402         (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
403     // There's never any support for operations beyond MVT::f32.
404     setOperationAction(Op, MVT::f64, Expand);
405     setOperationAction(Op, MVT::f80, Expand);
406     setOperationAction(Op, MVT::f128, Expand);
407   }
408 
409   for (MVT VT : {MVT::f32, MVT::f64, MVT::f80, MVT::f128}) {
410     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
411     setLoadExtAction(ISD::EXTLOAD, VT, MVT::bf16, Expand);
412     setTruncStoreAction(VT, MVT::f16, Expand);
413     setTruncStoreAction(VT, MVT::bf16, Expand);
414 
415     setOperationAction(ISD::BF16_TO_FP, VT, Expand);
416     setOperationAction(ISD::FP_TO_BF16, VT, Custom);
417   }
418 
419   setOperationAction(ISD::PARITY, MVT::i8, Custom);
420   setOperationAction(ISD::PARITY, MVT::i16, Custom);
421   setOperationAction(ISD::PARITY, MVT::i32, Custom);
422   if (Subtarget.is64Bit())
423     setOperationAction(ISD::PARITY, MVT::i64, Custom);
424   if (Subtarget.hasPOPCNT()) {
425     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
426     // popcntw is longer to encode than popcntl and also has a false dependency
427     // on the dest that popcntl hasn't had since Cannon Lake.
428     setOperationPromotedToType(ISD::CTPOP, MVT::i16, MVT::i32);
429   } else {
430     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433     if (Subtarget.is64Bit())
434       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435     else
436       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
437   }
438 
439   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
440 
441   if (!Subtarget.hasMOVBE())
442     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
443 
444   // X86 wants to expand cmov itself.
445   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
446     setOperationAction(ISD::SELECT, VT, Custom);
447     setOperationAction(ISD::SETCC, VT, Custom);
448     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
449     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
450   }
451   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
452     if (VT == MVT::i64 && !Subtarget.is64Bit())
453       continue;
454     setOperationAction(ISD::SELECT, VT, Custom);
455     setOperationAction(ISD::SETCC,  VT, Custom);
456   }
457 
458   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
459   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
460   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
461 
462   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
463   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
464   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
465   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
467   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
468   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
469     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
470 
471   // Darwin ABI issue.
472   for (auto VT : { MVT::i32, MVT::i64 }) {
473     if (VT == MVT::i64 && !Subtarget.is64Bit())
474       continue;
475     setOperationAction(ISD::ConstantPool    , VT, Custom);
476     setOperationAction(ISD::JumpTable       , VT, Custom);
477     setOperationAction(ISD::GlobalAddress   , VT, Custom);
478     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
479     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
480     setOperationAction(ISD::BlockAddress    , VT, Custom);
481   }
482 
483   // 64-bit shl, sra, srl (iff 32-bit x86)
484   for (auto VT : { MVT::i32, MVT::i64 }) {
485     if (VT == MVT::i64 && !Subtarget.is64Bit())
486       continue;
487     setOperationAction(ISD::SHL_PARTS, VT, Custom);
488     setOperationAction(ISD::SRA_PARTS, VT, Custom);
489     setOperationAction(ISD::SRL_PARTS, VT, Custom);
490   }
491 
492   if (Subtarget.hasSSEPrefetch() || Subtarget.hasThreeDNow())
493     setOperationAction(ISD::PREFETCH      , MVT::Other, Custom);
494 
495   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
496 
497   // Expand certain atomics
498   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
499     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
505     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506   }
507 
508   if (!Subtarget.is64Bit())
509     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510 
511   if (Subtarget.canUseCMPXCHG16B())
512     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
513 
514   // FIXME - use subtarget debug flags
515   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
516       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
517       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
518     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
519   }
520 
521   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
522   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
523 
524   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
525   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
526 
527   setOperationAction(ISD::TRAP, MVT::Other, Legal);
528   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
529   if (Subtarget.isTargetPS())
530     setOperationAction(ISD::UBSANTRAP, MVT::Other, Expand);
531   else
532     setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
533 
534   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
535   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
536   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
537   bool Is64Bit = Subtarget.is64Bit();
538   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
539   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
540 
541   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
542   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
543 
544   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
545 
546   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
547   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
548   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
549 
550   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
551 
552   auto setF16Action = [&] (MVT VT, LegalizeAction Action) {
553     setOperationAction(ISD::FABS, VT, Action);
554     setOperationAction(ISD::FNEG, VT, Action);
555     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
556     setOperationAction(ISD::FREM, VT, Action);
557     setOperationAction(ISD::FMA, VT, Action);
558     setOperationAction(ISD::FMINNUM, VT, Action);
559     setOperationAction(ISD::FMAXNUM, VT, Action);
560     setOperationAction(ISD::FMINIMUM, VT, Action);
561     setOperationAction(ISD::FMAXIMUM, VT, Action);
562     setOperationAction(ISD::FSIN, VT, Action);
563     setOperationAction(ISD::FCOS, VT, Action);
564     setOperationAction(ISD::FSINCOS, VT, Action);
565     setOperationAction(ISD::FSQRT, VT, Action);
566     setOperationAction(ISD::FPOW, VT, Action);
567     setOperationAction(ISD::FLOG, VT, Action);
568     setOperationAction(ISD::FLOG2, VT, Action);
569     setOperationAction(ISD::FLOG10, VT, Action);
570     setOperationAction(ISD::FEXP, VT, Action);
571     setOperationAction(ISD::FEXP2, VT, Action);
572     setOperationAction(ISD::FEXP10, VT, Action);
573     setOperationAction(ISD::FCEIL, VT, Action);
574     setOperationAction(ISD::FFLOOR, VT, Action);
575     setOperationAction(ISD::FNEARBYINT, VT, Action);
576     setOperationAction(ISD::FRINT, VT, Action);
577     setOperationAction(ISD::BR_CC, VT, Action);
578     setOperationAction(ISD::SETCC, VT, Action);
579     setOperationAction(ISD::SELECT, VT, Custom);
580     setOperationAction(ISD::SELECT_CC, VT, Action);
581     setOperationAction(ISD::FROUND, VT, Action);
582     setOperationAction(ISD::FROUNDEVEN, VT, Action);
583     setOperationAction(ISD::FTRUNC, VT, Action);
584     setOperationAction(ISD::FLDEXP, VT, Action);
585   };
586 
587   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
588     // f16, f32 and f64 use SSE.
589     // Set up the FP register classes.
590     addRegisterClass(MVT::f16, Subtarget.hasAVX512() ? &X86::FR16XRegClass
591                                                      : &X86::FR16RegClass);
592     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
593                                                      : &X86::FR32RegClass);
594     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
595                                                      : &X86::FR64RegClass);
596 
597     // Disable f32->f64 extload as we can only generate this in one instruction
598     // under optsize. So its easier to pattern match (fpext (load)) for that
599     // case instead of needing to emit 2 instructions for extload in the
600     // non-optsize case.
601     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
602 
603     for (auto VT : { MVT::f32, MVT::f64 }) {
604       // Use ANDPD to simulate FABS.
605       setOperationAction(ISD::FABS, VT, Custom);
606 
607       // Use XORP to simulate FNEG.
608       setOperationAction(ISD::FNEG, VT, Custom);
609 
610       // Use ANDPD and ORPD to simulate FCOPYSIGN.
611       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
612 
613       // These might be better off as horizontal vector ops.
614       setOperationAction(ISD::FADD, VT, Custom);
615       setOperationAction(ISD::FSUB, VT, Custom);
616 
617       // We don't support sin/cos/fmod
618       setOperationAction(ISD::FSIN   , VT, Expand);
619       setOperationAction(ISD::FCOS   , VT, Expand);
620       setOperationAction(ISD::FSINCOS, VT, Expand);
621     }
622 
623     // Half type will be promoted by default.
624     setF16Action(MVT::f16, Promote);
625     setOperationAction(ISD::FADD, MVT::f16, Promote);
626     setOperationAction(ISD::FSUB, MVT::f16, Promote);
627     setOperationAction(ISD::FMUL, MVT::f16, Promote);
628     setOperationAction(ISD::FDIV, MVT::f16, Promote);
629     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
630     setOperationAction(ISD::FP_EXTEND, MVT::f32, Custom);
631     setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
632 
633     setOperationAction(ISD::STRICT_FADD, MVT::f16, Promote);
634     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Promote);
635     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Promote);
636     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Promote);
637     setOperationAction(ISD::STRICT_FMA, MVT::f16, Promote);
638     setOperationAction(ISD::STRICT_FMINNUM, MVT::f16, Promote);
639     setOperationAction(ISD::STRICT_FMAXNUM, MVT::f16, Promote);
640     setOperationAction(ISD::STRICT_FMINIMUM, MVT::f16, Promote);
641     setOperationAction(ISD::STRICT_FMAXIMUM, MVT::f16, Promote);
642     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Promote);
643     setOperationAction(ISD::STRICT_FPOW, MVT::f16, Promote);
644     setOperationAction(ISD::STRICT_FLDEXP, MVT::f16, Promote);
645     setOperationAction(ISD::STRICT_FLOG, MVT::f16, Promote);
646     setOperationAction(ISD::STRICT_FLOG2, MVT::f16, Promote);
647     setOperationAction(ISD::STRICT_FLOG10, MVT::f16, Promote);
648     setOperationAction(ISD::STRICT_FEXP, MVT::f16, Promote);
649     setOperationAction(ISD::STRICT_FEXP2, MVT::f16, Promote);
650     setOperationAction(ISD::STRICT_FCEIL, MVT::f16, Promote);
651     setOperationAction(ISD::STRICT_FFLOOR, MVT::f16, Promote);
652     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f16, Promote);
653     setOperationAction(ISD::STRICT_FRINT, MVT::f16, Promote);
654     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Promote);
655     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Promote);
656     setOperationAction(ISD::STRICT_FROUND, MVT::f16, Promote);
657     setOperationAction(ISD::STRICT_FROUNDEVEN, MVT::f16, Promote);
658     setOperationAction(ISD::STRICT_FTRUNC, MVT::f16, Promote);
659     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
660     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
661     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
662 
663     setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
664     setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
665 
666     // Lower this to MOVMSK plus an AND.
667     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
669 
670   } else if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1() &&
671              (UseX87 || Is64Bit)) {
672     // Use SSE for f32, x87 for f64.
673     // Set up the FP register classes.
674     addRegisterClass(MVT::f32, &X86::FR32RegClass);
675     if (UseX87)
676       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
677 
678     // Use ANDPS to simulate FABS.
679     setOperationAction(ISD::FABS , MVT::f32, Custom);
680 
681     // Use XORP to simulate FNEG.
682     setOperationAction(ISD::FNEG , MVT::f32, Custom);
683 
684     if (UseX87)
685       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
686 
687     // Use ANDPS and ORPS to simulate FCOPYSIGN.
688     if (UseX87)
689       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
690     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
691 
692     // We don't support sin/cos/fmod
693     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
694     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
695     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
696 
697     if (UseX87) {
698       // Always expand sin/cos functions even though x87 has an instruction.
699       setOperationAction(ISD::FSIN, MVT::f64, Expand);
700       setOperationAction(ISD::FCOS, MVT::f64, Expand);
701       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
702     }
703   } else if (UseX87) {
704     // f32 and f64 in x87.
705     // Set up the FP register classes.
706     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
707     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
708 
709     for (auto VT : { MVT::f32, MVT::f64 }) {
710       setOperationAction(ISD::UNDEF,     VT, Expand);
711       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
712 
713       // Always expand sin/cos functions even though x87 has an instruction.
714       setOperationAction(ISD::FSIN   , VT, Expand);
715       setOperationAction(ISD::FCOS   , VT, Expand);
716       setOperationAction(ISD::FSINCOS, VT, Expand);
717     }
718   }
719 
720   // Expand FP32 immediates into loads from the stack, save special cases.
721   if (isTypeLegal(MVT::f32)) {
722     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
723       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
724       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
725       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
726       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
727     } else // SSE immediates.
728       addLegalFPImmediate(APFloat(+0.0f)); // xorps
729   }
730   // Expand FP64 immediates into loads from the stack, save special cases.
731   if (isTypeLegal(MVT::f64)) {
732     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
733       addLegalFPImmediate(APFloat(+0.0)); // FLD0
734       addLegalFPImmediate(APFloat(+1.0)); // FLD1
735       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
736       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
737     } else // SSE immediates.
738       addLegalFPImmediate(APFloat(+0.0)); // xorpd
739   }
740   // Support fp16 0 immediate.
741   if (isTypeLegal(MVT::f16))
742     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEhalf()));
743 
744   // Handle constrained floating-point operations of scalar.
745   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
746   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
747   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
748   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
749   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
750   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
751   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
752   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
753   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
754   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
755   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
756   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
757 
758   // We don't support FMA.
759   setOperationAction(ISD::FMA, MVT::f64, Expand);
760   setOperationAction(ISD::FMA, MVT::f32, Expand);
761 
762   // f80 always uses X87.
763   if (UseX87) {
764     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
765     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
766     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
767     {
768       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
769       addLegalFPImmediate(TmpFlt);  // FLD0
770       TmpFlt.changeSign();
771       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
772 
773       bool ignored;
774       APFloat TmpFlt2(+1.0);
775       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
776                       &ignored);
777       addLegalFPImmediate(TmpFlt2);  // FLD1
778       TmpFlt2.changeSign();
779       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
780     }
781 
782     // Always expand sin/cos functions even though x87 has an instruction.
783     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
784     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
785     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
786 
787     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
788     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
789     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
790     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
791     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
792     setOperationAction(ISD::FROUNDEVEN, MVT::f80, Expand);
793     setOperationAction(ISD::FMA, MVT::f80, Expand);
794     setOperationAction(ISD::LROUND, MVT::f80, Expand);
795     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
796     setOperationAction(ISD::LRINT, MVT::f80, Custom);
797     setOperationAction(ISD::LLRINT, MVT::f80, Custom);
798 
799     // Handle constrained floating-point operations of scalar.
800     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
801     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
802     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
803     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
804     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
805     if (isTypeLegal(MVT::f16)) {
806       setOperationAction(ISD::FP_EXTEND, MVT::f80, Custom);
807       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Custom);
808     } else {
809       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
810     }
811     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
812     // as Custom.
813     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
814   }
815 
816   // f128 uses xmm registers, but most operations require libcalls.
817   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
818     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
819                                                    : &X86::VR128RegClass);
820 
821     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
822 
823     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
824     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
825     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
826     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
827     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
828     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
829     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
830     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
831     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
832     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
833 
834     setOperationAction(ISD::FABS, MVT::f128, Custom);
835     setOperationAction(ISD::FNEG, MVT::f128, Custom);
836     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
837 
838     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
839     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
840     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
841     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
842     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
843     // No STRICT_FSINCOS
844     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
845     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
846 
847     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
848     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
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)) {
853       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
854       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
855     }
856     if (isTypeLegal(MVT::f64)) {
857       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
858       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
859     }
860     if (isTypeLegal(MVT::f80)) {
861       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
862       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
863     }
864 
865     setOperationAction(ISD::SETCC, MVT::f128, Custom);
866 
867     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
868     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
869     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
870     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
871     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
872     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
873   }
874 
875   // Always use a library call for pow.
876   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
877   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
878   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
879   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
880 
881   setOperationAction(ISD::FLOG, MVT::f80, Expand);
882   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
883   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
884   setOperationAction(ISD::FEXP, MVT::f80, Expand);
885   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
886   setOperationAction(ISD::FEXP10, MVT::f80, Expand);
887   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
888   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
889 
890   // Some FP actions are always expanded for vector types.
891   for (auto VT : { MVT::v8f16, MVT::v16f16, MVT::v32f16,
892                    MVT::v4f32, MVT::v8f32,  MVT::v16f32,
893                    MVT::v2f64, MVT::v4f64,  MVT::v8f64 }) {
894     setOperationAction(ISD::FSIN,      VT, Expand);
895     setOperationAction(ISD::FSINCOS,   VT, Expand);
896     setOperationAction(ISD::FCOS,      VT, Expand);
897     setOperationAction(ISD::FREM,      VT, Expand);
898     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
899     setOperationAction(ISD::FPOW,      VT, Expand);
900     setOperationAction(ISD::FLOG,      VT, Expand);
901     setOperationAction(ISD::FLOG2,     VT, Expand);
902     setOperationAction(ISD::FLOG10,    VT, Expand);
903     setOperationAction(ISD::FEXP,      VT, Expand);
904     setOperationAction(ISD::FEXP2,     VT, Expand);
905     setOperationAction(ISD::FEXP10,    VT, Expand);
906   }
907 
908   // First set operation action for all vector types to either promote
909   // (for widening) or expand (for scalarization). Then we will selectively
910   // turn on ones that can be effectively codegen'd.
911   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
912     setOperationAction(ISD::SDIV, VT, Expand);
913     setOperationAction(ISD::UDIV, VT, Expand);
914     setOperationAction(ISD::SREM, VT, Expand);
915     setOperationAction(ISD::UREM, VT, Expand);
916     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
917     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
918     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
919     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
920     setOperationAction(ISD::FMA,  VT, Expand);
921     setOperationAction(ISD::FFLOOR, VT, Expand);
922     setOperationAction(ISD::FCEIL, VT, Expand);
923     setOperationAction(ISD::FTRUNC, VT, Expand);
924     setOperationAction(ISD::FRINT, VT, Expand);
925     setOperationAction(ISD::FNEARBYINT, VT, Expand);
926     setOperationAction(ISD::FROUNDEVEN, VT, Expand);
927     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
928     setOperationAction(ISD::MULHS, VT, Expand);
929     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
930     setOperationAction(ISD::MULHU, VT, Expand);
931     setOperationAction(ISD::SDIVREM, VT, Expand);
932     setOperationAction(ISD::UDIVREM, VT, Expand);
933     setOperationAction(ISD::CTPOP, VT, Expand);
934     setOperationAction(ISD::CTTZ, VT, Expand);
935     setOperationAction(ISD::CTLZ, VT, Expand);
936     setOperationAction(ISD::ROTL, VT, Expand);
937     setOperationAction(ISD::ROTR, VT, Expand);
938     setOperationAction(ISD::BSWAP, VT, Expand);
939     setOperationAction(ISD::SETCC, VT, Expand);
940     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
941     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
942     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
943     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
944     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
945     setOperationAction(ISD::TRUNCATE, VT, Expand);
946     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
947     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
948     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
949     setOperationAction(ISD::SELECT_CC, VT, Expand);
950     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
951       setTruncStoreAction(InnerVT, VT, Expand);
952 
953       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
954       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
955 
956       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
957       // types, we have to deal with them whether we ask for Expansion or not.
958       // Setting Expand causes its own optimisation problems though, so leave
959       // them legal.
960       if (VT.getVectorElementType() == MVT::i1)
961         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
962 
963       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
964       // split/scalarized right now.
965       if (VT.getVectorElementType() == MVT::f16 ||
966           VT.getVectorElementType() == MVT::bf16)
967         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
968     }
969   }
970 
971   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
972   // with -msoft-float, disable use of MMX as well.
973   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
974     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
975     // No operations on x86mmx supported, everything uses intrinsics.
976   }
977 
978   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
979     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
980                                                     : &X86::VR128RegClass);
981 
982     setOperationAction(ISD::FMAXIMUM,           MVT::f32, Custom);
983     setOperationAction(ISD::FMINIMUM,           MVT::f32, Custom);
984 
985     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
986     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
987     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
988     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
989     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
990     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
991     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
992     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
993 
994     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
995     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
996 
997     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
998     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
999     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
1000     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
1001     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
1002   }
1003 
1004   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
1005     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1006                                                     : &X86::VR128RegClass);
1007 
1008     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
1009     // registers cannot be used even for integer operations.
1010     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
1011                                                     : &X86::VR128RegClass);
1012     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1013                                                     : &X86::VR128RegClass);
1014     addRegisterClass(MVT::v8f16, Subtarget.hasVLX() ? &X86::VR128XRegClass
1015                                                     : &X86::VR128RegClass);
1016     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
1017                                                     : &X86::VR128RegClass);
1018     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
1019                                                     : &X86::VR128RegClass);
1020 
1021     for (auto VT : { MVT::f64, MVT::v4f32, MVT::v2f64 }) {
1022       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1023       setOperationAction(ISD::FMINIMUM, VT, Custom);
1024     }
1025 
1026     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
1027                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
1028       setOperationAction(ISD::SDIV, VT, Custom);
1029       setOperationAction(ISD::SREM, VT, Custom);
1030       setOperationAction(ISD::UDIV, VT, Custom);
1031       setOperationAction(ISD::UREM, VT, Custom);
1032     }
1033 
1034     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
1035     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
1036     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
1037 
1038     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
1039     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
1040     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
1041     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
1042     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
1043     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
1044     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
1045     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
1046     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
1047     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
1048     setOperationAction(ISD::AVGCEILU,           MVT::v16i8, Legal);
1049     setOperationAction(ISD::AVGCEILU,           MVT::v8i16, Legal);
1050 
1051     setOperationAction(ISD::SMULO,              MVT::v16i8, Custom);
1052     setOperationAction(ISD::UMULO,              MVT::v16i8, Custom);
1053     setOperationAction(ISD::UMULO,              MVT::v2i32, Custom);
1054 
1055     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
1056     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
1057     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
1058 
1059     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1060       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
1061       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
1062       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
1063       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
1064     }
1065 
1066     setOperationAction(ISD::ABDU,               MVT::v16i8, Custom);
1067     setOperationAction(ISD::ABDS,               MVT::v16i8, Custom);
1068     setOperationAction(ISD::ABDU,               MVT::v8i16, Custom);
1069     setOperationAction(ISD::ABDS,               MVT::v8i16, Custom);
1070     setOperationAction(ISD::ABDU,               MVT::v4i32, Custom);
1071     setOperationAction(ISD::ABDS,               MVT::v4i32, Custom);
1072 
1073     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
1074     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
1075     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
1076     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
1077     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
1078     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
1079     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
1080     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
1081     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
1082     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
1083 
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1085     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1086     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1087     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1088 
1089     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1090       setOperationAction(ISD::SETCC,              VT, Custom);
1091       setOperationAction(ISD::CTPOP,              VT, Custom);
1092       setOperationAction(ISD::ABS,                VT, Custom);
1093 
1094       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1095       // setcc all the way to isel and prefer SETGT in some isel patterns.
1096       setCondCodeAction(ISD::SETLT, VT, Custom);
1097       setCondCodeAction(ISD::SETLE, VT, Custom);
1098     }
1099 
1100     setOperationAction(ISD::SETCC,          MVT::v2f64, Custom);
1101     setOperationAction(ISD::SETCC,          MVT::v4f32, Custom);
1102     setOperationAction(ISD::STRICT_FSETCC,  MVT::v2f64, Custom);
1103     setOperationAction(ISD::STRICT_FSETCC,  MVT::v4f32, Custom);
1104     setOperationAction(ISD::STRICT_FSETCCS, MVT::v2f64, Custom);
1105     setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f32, Custom);
1106 
1107     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
1108       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1109       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1110       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1111       setOperationAction(ISD::VSELECT,            VT, Custom);
1112       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1113     }
1114 
1115     for (auto VT : { MVT::v8f16, MVT::v2f64, MVT::v2i64 }) {
1116       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1117       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1118       setOperationAction(ISD::VSELECT,            VT, Custom);
1119 
1120       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
1121         continue;
1122 
1123       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1124       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1125     }
1126     setF16Action(MVT::v8f16, Expand);
1127     setOperationAction(ISD::FADD, MVT::v8f16, Expand);
1128     setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
1129     setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
1130     setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
1131     setOperationAction(ISD::FNEG, MVT::v8f16, Custom);
1132     setOperationAction(ISD::FABS, MVT::v8f16, Custom);
1133     setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Custom);
1134 
1135     // Custom lower v2i64 and v2f64 selects.
1136     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1137     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1138     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
1139     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
1140     setOperationAction(ISD::SELECT,             MVT::v8f16, Custom);
1141     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
1142 
1143     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Custom);
1144     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Custom);
1145     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
1146     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1147     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Custom);
1148     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
1149 
1150     // Custom legalize these to avoid over promotion or custom promotion.
1151     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1152       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1153       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1154       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1155       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1156     }
1157 
1158     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Custom);
1159     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Custom);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
1161     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
1162 
1163     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
1164     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
1165 
1166     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
1167     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
1168 
1169     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1170     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
1171     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
1172     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
1173     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
1174 
1175     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1176     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
1177     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1178     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1179 
1180     // We want to legalize this to an f64 load rather than an i64 load on
1181     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1182     // store.
1183     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1184     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1185     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1186     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1187     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1188     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1189 
1190     // Add 32-bit vector stores to help vectorization opportunities.
1191     setOperationAction(ISD::STORE,              MVT::v2i16, Custom);
1192     setOperationAction(ISD::STORE,              MVT::v4i8,  Custom);
1193 
1194     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1195     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1196     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1197     if (!Subtarget.hasAVX512())
1198       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1199 
1200     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1201     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1202     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1203 
1204     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1205 
1206     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1207     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1208     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1209     setOperationAction(ISD::TRUNCATE,    MVT::v2i64, Custom);
1210     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1211     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1212     setOperationAction(ISD::TRUNCATE,    MVT::v4i32, Custom);
1213     setOperationAction(ISD::TRUNCATE,    MVT::v4i64, Custom);
1214     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1215     setOperationAction(ISD::TRUNCATE,    MVT::v8i16, Custom);
1216     setOperationAction(ISD::TRUNCATE,    MVT::v8i32, Custom);
1217     setOperationAction(ISD::TRUNCATE,    MVT::v8i64, Custom);
1218     setOperationAction(ISD::TRUNCATE,    MVT::v16i8, Custom);
1219     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Custom);
1220     setOperationAction(ISD::TRUNCATE,    MVT::v16i32, Custom);
1221     setOperationAction(ISD::TRUNCATE,    MVT::v16i64, Custom);
1222 
1223     // In the customized shift lowering, the legal v4i32/v2i64 cases
1224     // in AVX2 will be recognized.
1225     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1226       setOperationAction(ISD::SRL,              VT, Custom);
1227       setOperationAction(ISD::SHL,              VT, Custom);
1228       setOperationAction(ISD::SRA,              VT, Custom);
1229       if (VT == MVT::v2i64) continue;
1230       setOperationAction(ISD::ROTL,             VT, Custom);
1231       setOperationAction(ISD::ROTR,             VT, Custom);
1232       setOperationAction(ISD::FSHL,             VT, Custom);
1233       setOperationAction(ISD::FSHR,             VT, Custom);
1234     }
1235 
1236     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1237     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1238     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1239     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1240     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1241   }
1242 
1243   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1244     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1245     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1246     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1247     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1248     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1249     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1250     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1251     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1252 
1253     // These might be better off as horizontal vector ops.
1254     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1255     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1256     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1257     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1258   }
1259 
1260   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1261     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1262       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1263       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1264       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1265       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1266       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1267       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1268       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1269       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1270       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1271       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1272       setOperationAction(ISD::FROUNDEVEN,        RoundedTy,  Legal);
1273       setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy,  Legal);
1274 
1275       setOperationAction(ISD::FROUND,            RoundedTy,  Custom);
1276     }
1277 
1278     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1279     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1280     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1281     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1282     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1283     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1284     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1285     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1286 
1287     for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64}) {
1288       setOperationAction(ISD::ABDS,             VT, Custom);
1289       setOperationAction(ISD::ABDU,             VT, Custom);
1290     }
1291 
1292     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
1293     setOperationAction(ISD::SADDSAT,            MVT::v2i64, Custom);
1294     setOperationAction(ISD::SSUBSAT,            MVT::v2i64, Custom);
1295 
1296     // FIXME: Do we need to handle scalar-to-vector here?
1297     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1298     setOperationAction(ISD::SMULO,              MVT::v2i32, Custom);
1299 
1300     // We directly match byte blends in the backend as they match the VSELECT
1301     // condition form.
1302     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1303 
1304     // SSE41 brings specific instructions for doing vector sign extend even in
1305     // cases where we don't have SRA.
1306     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1307       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1308       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1309     }
1310 
1311     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1312     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1313       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1314       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1315       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1316       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1317       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1318       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1319     }
1320 
1321     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1322       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1323       // do the pre and post work in the vector domain.
1324       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1325       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1326       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1327       // so that DAG combine doesn't try to turn it into uint_to_fp.
1328       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1329       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1330     }
1331   }
1332 
1333   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1334     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
1335   }
1336 
1337   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1338     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1339                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1340       setOperationAction(ISD::ROTL, VT, Custom);
1341       setOperationAction(ISD::ROTR, VT, Custom);
1342     }
1343 
1344     // XOP can efficiently perform BITREVERSE with VPPERM.
1345     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1346       setOperationAction(ISD::BITREVERSE, VT, Custom);
1347 
1348     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1349                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1350       setOperationAction(ISD::BITREVERSE, VT, Custom);
1351   }
1352 
1353   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1354     bool HasInt256 = Subtarget.hasInt256();
1355 
1356     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1357                                                      : &X86::VR256RegClass);
1358     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1359                                                      : &X86::VR256RegClass);
1360     addRegisterClass(MVT::v16f16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1361                                                      : &X86::VR256RegClass);
1362     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1363                                                      : &X86::VR256RegClass);
1364     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1365                                                      : &X86::VR256RegClass);
1366     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1367                                                      : &X86::VR256RegClass);
1368     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1369                                                      : &X86::VR256RegClass);
1370 
1371     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1372       setOperationAction(ISD::FFLOOR,            VT, Legal);
1373       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1374       setOperationAction(ISD::FCEIL,             VT, Legal);
1375       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1376       setOperationAction(ISD::FTRUNC,            VT, Legal);
1377       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1378       setOperationAction(ISD::FRINT,             VT, Legal);
1379       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1380       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1381       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1382       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1383       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1384 
1385       setOperationAction(ISD::FROUND,            VT, Custom);
1386 
1387       setOperationAction(ISD::FNEG,              VT, Custom);
1388       setOperationAction(ISD::FABS,              VT, Custom);
1389       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1390 
1391       setOperationAction(ISD::FMAXIMUM,          VT, Custom);
1392       setOperationAction(ISD::FMINIMUM,          VT, Custom);
1393     }
1394 
1395     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1396     // even though v8i16 is a legal type.
1397     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1398     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1399     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1400     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1401     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Custom);
1402     setOperationAction(ISD::FP_TO_UINT,                MVT::v8i32, Custom);
1403     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Custom);
1404 
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Custom);
1406     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Custom);
1407     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Expand);
1408     setOperationAction(ISD::FP_ROUND,           MVT::v8f16, Expand);
1409     setOperationAction(ISD::FP_EXTEND,          MVT::v4f64, Custom);
1410     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Custom);
1411 
1412     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1413     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1414     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1415     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1416     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1417     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1418     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1419     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1420     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1421     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1422     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1423 
1424     if (!Subtarget.hasAVX512())
1425       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1426 
1427     // In the customized shift lowering, the legal v8i32/v4i64 cases
1428     // in AVX2 will be recognized.
1429     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1430       setOperationAction(ISD::SRL,             VT, Custom);
1431       setOperationAction(ISD::SHL,             VT, Custom);
1432       setOperationAction(ISD::SRA,             VT, Custom);
1433       setOperationAction(ISD::ABDS,            VT, Custom);
1434       setOperationAction(ISD::ABDU,            VT, Custom);
1435       if (VT == MVT::v4i64) continue;
1436       setOperationAction(ISD::ROTL,            VT, Custom);
1437       setOperationAction(ISD::ROTR,            VT, Custom);
1438       setOperationAction(ISD::FSHL,            VT, Custom);
1439       setOperationAction(ISD::FSHR,            VT, Custom);
1440     }
1441 
1442     // These types need custom splitting if their input is a 128-bit vector.
1443     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1444     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1445     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1446     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1447 
1448     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1449     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1450     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1451     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1452     setOperationAction(ISD::SELECT,            MVT::v16f16, Custom);
1453     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1454     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1455 
1456     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1457       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1458       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1459       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1460     }
1461 
1462     setOperationAction(ISD::TRUNCATE,          MVT::v32i8, Custom);
1463     setOperationAction(ISD::TRUNCATE,          MVT::v32i16, Custom);
1464     setOperationAction(ISD::TRUNCATE,          MVT::v32i32, Custom);
1465     setOperationAction(ISD::TRUNCATE,          MVT::v32i64, Custom);
1466 
1467     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1468 
1469     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1470       setOperationAction(ISD::SETCC,           VT, Custom);
1471       setOperationAction(ISD::CTPOP,           VT, Custom);
1472       setOperationAction(ISD::CTLZ,            VT, Custom);
1473 
1474       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1475       // setcc all the way to isel and prefer SETGT in some isel patterns.
1476       setCondCodeAction(ISD::SETLT, VT, Custom);
1477       setCondCodeAction(ISD::SETLE, VT, Custom);
1478     }
1479 
1480     setOperationAction(ISD::SETCC,          MVT::v4f64, Custom);
1481     setOperationAction(ISD::SETCC,          MVT::v8f32, Custom);
1482     setOperationAction(ISD::STRICT_FSETCC,  MVT::v4f64, Custom);
1483     setOperationAction(ISD::STRICT_FSETCC,  MVT::v8f32, Custom);
1484     setOperationAction(ISD::STRICT_FSETCCS, MVT::v4f64, Custom);
1485     setOperationAction(ISD::STRICT_FSETCCS, MVT::v8f32, Custom);
1486 
1487     if (Subtarget.hasAnyFMA()) {
1488       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1489                        MVT::v2f64, MVT::v4f64 }) {
1490         setOperationAction(ISD::FMA, VT, Legal);
1491         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1492       }
1493     }
1494 
1495     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1496       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1497       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1498     }
1499 
1500     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1501     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1502     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1503     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1504 
1505     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1506     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1507     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1508     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1509     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1510     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1511     setOperationAction(ISD::AVGCEILU,  MVT::v16i16, HasInt256 ? Legal : Custom);
1512     setOperationAction(ISD::AVGCEILU,  MVT::v32i8,  HasInt256 ? Legal : Custom);
1513 
1514     setOperationAction(ISD::SMULO,     MVT::v32i8, Custom);
1515     setOperationAction(ISD::UMULO,     MVT::v32i8, Custom);
1516 
1517     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1518     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1519     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1520     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1521     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1522 
1523     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1524     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1525     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1526     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1527     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1528     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1529     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1530     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1531     setOperationAction(ISD::UADDSAT,   MVT::v8i32, Custom);
1532     setOperationAction(ISD::USUBSAT,   MVT::v8i32, Custom);
1533     setOperationAction(ISD::UADDSAT,   MVT::v4i64, Custom);
1534     setOperationAction(ISD::USUBSAT,   MVT::v4i64, Custom);
1535 
1536     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1537       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1538       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1539       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1540       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1541       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1542     }
1543 
1544     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1545       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1546       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1547     }
1548 
1549     if (HasInt256) {
1550       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1551       // when we have a 256bit-wide blend with immediate.
1552       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1553       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1554 
1555       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1556       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1557         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1558         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1559         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1560         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1561         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1562         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1563       }
1564     }
1565 
1566     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1567                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1568       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1569       setOperationAction(ISD::MSTORE, VT, Legal);
1570     }
1571 
1572     // Extract subvector is special because the value type
1573     // (result) is 128-bit but the source is 256-bit wide.
1574     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1575                      MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
1576       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1577     }
1578 
1579     // Custom lower several nodes for 256-bit types.
1580     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1581                     MVT::v16f16, MVT::v8f32, MVT::v4f64 }) {
1582       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1583       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1584       setOperationAction(ISD::VSELECT,            VT, Custom);
1585       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1586       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1587       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1588       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1589       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1590       setOperationAction(ISD::STORE,              VT, Custom);
1591     }
1592     setF16Action(MVT::v16f16, Expand);
1593     setOperationAction(ISD::FNEG, MVT::v16f16, Custom);
1594     setOperationAction(ISD::FABS, MVT::v16f16, Custom);
1595     setOperationAction(ISD::FCOPYSIGN, MVT::v16f16, Custom);
1596     setOperationAction(ISD::FADD, MVT::v16f16, Expand);
1597     setOperationAction(ISD::FSUB, MVT::v16f16, Expand);
1598     setOperationAction(ISD::FMUL, MVT::v16f16, Expand);
1599     setOperationAction(ISD::FDIV, MVT::v16f16, Expand);
1600 
1601     if (HasInt256) {
1602       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1603 
1604       // Custom legalize 2x32 to get a little better code.
1605       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1606       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1607 
1608       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1609                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1610         setOperationAction(ISD::MGATHER,  VT, Custom);
1611     }
1612   }
1613 
1614   if (!Subtarget.useSoftFloat() && !Subtarget.hasFP16() &&
1615       Subtarget.hasF16C()) {
1616     for (MVT VT : { MVT::f16, MVT::v2f16, MVT::v4f16, MVT::v8f16 }) {
1617       setOperationAction(ISD::FP_ROUND,           VT, Custom);
1618       setOperationAction(ISD::STRICT_FP_ROUND,    VT, Custom);
1619     }
1620     for (MVT VT : { MVT::f32, MVT::v2f32, MVT::v4f32, MVT::v8f32 }) {
1621       setOperationAction(ISD::FP_EXTEND,          VT, Custom);
1622       setOperationAction(ISD::STRICT_FP_EXTEND,   VT, Custom);
1623     }
1624     for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1625       setOperationPromotedToType(Opc, MVT::v8f16, MVT::v8f32);
1626       setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1627     }
1628   }
1629 
1630   // This block controls legalization of the mask vector sizes that are
1631   // available with AVX512. 512-bit vectors are in a separate block controlled
1632   // by useAVX512Regs.
1633   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1634     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1635     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1636     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1637     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1638     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1639 
1640     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1641     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1642     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1643 
1644     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1645     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1646     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1647     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1648     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1649     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1650     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1651     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1652     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1653     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1654     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1655     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1656 
1657     // There is no byte sized k-register load or store without AVX512DQ.
1658     if (!Subtarget.hasDQI()) {
1659       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1660       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1661       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1662       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1663 
1664       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1665       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1666       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1667       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1668     }
1669 
1670     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1671     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1672       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1673       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1674       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1675     }
1676 
1677     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 })
1678       setOperationAction(ISD::VSELECT,          VT, Expand);
1679 
1680     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1681       setOperationAction(ISD::SETCC,            VT, Custom);
1682       setOperationAction(ISD::SELECT,           VT, Custom);
1683       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1684 
1685       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1686       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1687       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1688       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1689       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1690       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1691     }
1692 
1693     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1694       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1695   }
1696 
1697   // This block controls legalization for 512-bit operations with 8/16/32/64 bit
1698   // elements. 512-bits can be disabled based on prefer-vector-width and
1699   // required-vector-width function attributes.
1700   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1701     bool HasBWI = Subtarget.hasBWI();
1702 
1703     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1704     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1705     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1706     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1707     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1708     addRegisterClass(MVT::v32f16, &X86::VR512RegClass);
1709     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1710 
1711     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1712       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1713       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1714       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1715       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1716       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1717       if (HasBWI)
1718         setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1719     }
1720 
1721     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1722       setOperationAction(ISD::FMAXIMUM, VT, Custom);
1723       setOperationAction(ISD::FMINIMUM, VT, Custom);
1724       setOperationAction(ISD::FNEG,  VT, Custom);
1725       setOperationAction(ISD::FABS,  VT, Custom);
1726       setOperationAction(ISD::FMA,   VT, Legal);
1727       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1728       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1729     }
1730 
1731     for (MVT VT : { MVT::v16i1, MVT::v16i8 }) {
1732       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1733       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1734       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1735       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1736     }
1737 
1738     for (MVT VT : { MVT::v16i16, MVT::v16i32 }) {
1739       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1740       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1741       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1742       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1743     }
1744 
1745     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Custom);
1746     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Custom);
1747     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Custom);
1748     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Custom);
1749     setOperationAction(ISD::FP_EXTEND,         MVT::v8f64,  Custom);
1750     setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v8f64,  Custom);
1751 
1752     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1753     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1754     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1755     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1756     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1757     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1758     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1759     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1760     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1761     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1762     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1763 
1764     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1765     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1766     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1767     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1768     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1769     if (HasBWI)
1770       setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1771 
1772     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1773     // to 512-bit rather than use the AVX2 instructions so that we can use
1774     // k-masks.
1775     if (!Subtarget.hasVLX()) {
1776       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1777            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1778         setOperationAction(ISD::MLOAD,  VT, Custom);
1779         setOperationAction(ISD::MSTORE, VT, Custom);
1780       }
1781     }
1782 
1783     setOperationAction(ISD::TRUNCATE,    MVT::v8i32,  Legal);
1784     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Legal);
1785     setOperationAction(ISD::TRUNCATE,    MVT::v32i8,  HasBWI ? Legal : Custom);
1786     setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1787     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1788     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
1789     setOperationAction(ISD::ANY_EXTEND,  MVT::v32i16, Custom);
1790     setOperationAction(ISD::ANY_EXTEND,  MVT::v16i32, Custom);
1791     setOperationAction(ISD::ANY_EXTEND,  MVT::v8i64,  Custom);
1792     setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1793     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1794     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
1795 
1796     if (HasBWI) {
1797       // Extends from v64i1 masks to 512-bit vectors.
1798       setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1799       setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1800       setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1801     }
1802 
1803     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1804       setOperationAction(ISD::FFLOOR,            VT, Legal);
1805       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1806       setOperationAction(ISD::FCEIL,             VT, Legal);
1807       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1808       setOperationAction(ISD::FTRUNC,            VT, Legal);
1809       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1810       setOperationAction(ISD::FRINT,             VT, Legal);
1811       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1812       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1813       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1814       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1815       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1816 
1817       setOperationAction(ISD::FROUND,            VT, Custom);
1818     }
1819 
1820     for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1821       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1822       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1823     }
1824 
1825     setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1826     setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1827     setOperationAction(ISD::ADD, MVT::v64i8,  HasBWI ? Legal : Custom);
1828     setOperationAction(ISD::SUB, MVT::v64i8,  HasBWI ? Legal : Custom);
1829 
1830     setOperationAction(ISD::MUL, MVT::v8i64,  Custom);
1831     setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1832     setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1833     setOperationAction(ISD::MUL, MVT::v64i8,  Custom);
1834 
1835     setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1836     setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1837     setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1838     setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1839     setOperationAction(ISD::MULHS, MVT::v64i8,  Custom);
1840     setOperationAction(ISD::MULHU, MVT::v64i8,  Custom);
1841     setOperationAction(ISD::AVGCEILU, MVT::v32i16, HasBWI ? Legal : Custom);
1842     setOperationAction(ISD::AVGCEILU, MVT::v64i8,  HasBWI ? Legal : Custom);
1843 
1844     setOperationAction(ISD::SMULO, MVT::v64i8, Custom);
1845     setOperationAction(ISD::UMULO, MVT::v64i8, Custom);
1846 
1847     setOperationAction(ISD::BITREVERSE, MVT::v64i8,  Custom);
1848 
1849     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1850       setOperationAction(ISD::SRL,              VT, Custom);
1851       setOperationAction(ISD::SHL,              VT, Custom);
1852       setOperationAction(ISD::SRA,              VT, Custom);
1853       setOperationAction(ISD::ROTL,             VT, Custom);
1854       setOperationAction(ISD::ROTR,             VT, Custom);
1855       setOperationAction(ISD::SETCC,            VT, Custom);
1856       setOperationAction(ISD::ABDS,             VT, Custom);
1857       setOperationAction(ISD::ABDU,             VT, Custom);
1858 
1859       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1860       // setcc all the way to isel and prefer SETGT in some isel patterns.
1861       setCondCodeAction(ISD::SETLT, VT, Custom);
1862       setCondCodeAction(ISD::SETLE, VT, Custom);
1863     }
1864 
1865     setOperationAction(ISD::SETCC,          MVT::v8f64, Custom);
1866     setOperationAction(ISD::SETCC,          MVT::v16f32, Custom);
1867     setOperationAction(ISD::STRICT_FSETCC,  MVT::v8f64, Custom);
1868     setOperationAction(ISD::STRICT_FSETCC,  MVT::v16f32, Custom);
1869     setOperationAction(ISD::STRICT_FSETCCS, MVT::v8f64, Custom);
1870     setOperationAction(ISD::STRICT_FSETCCS, MVT::v16f32, Custom);
1871 
1872     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1873       setOperationAction(ISD::SMAX,             VT, Legal);
1874       setOperationAction(ISD::UMAX,             VT, Legal);
1875       setOperationAction(ISD::SMIN,             VT, Legal);
1876       setOperationAction(ISD::UMIN,             VT, Legal);
1877       setOperationAction(ISD::ABS,              VT, Legal);
1878       setOperationAction(ISD::CTPOP,            VT, Custom);
1879     }
1880 
1881     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1882       setOperationAction(ISD::ABS,     VT, HasBWI ? Legal : Custom);
1883       setOperationAction(ISD::CTPOP,   VT, Subtarget.hasBITALG() ? Legal : Custom);
1884       setOperationAction(ISD::CTLZ,    VT, Custom);
1885       setOperationAction(ISD::SMAX,    VT, HasBWI ? Legal : Custom);
1886       setOperationAction(ISD::UMAX,    VT, HasBWI ? Legal : Custom);
1887       setOperationAction(ISD::SMIN,    VT, HasBWI ? Legal : Custom);
1888       setOperationAction(ISD::UMIN,    VT, HasBWI ? Legal : Custom);
1889       setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1890       setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1891       setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1892       setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1893     }
1894 
1895     setOperationAction(ISD::FSHL,       MVT::v64i8, Custom);
1896     setOperationAction(ISD::FSHR,       MVT::v64i8, Custom);
1897     setOperationAction(ISD::FSHL,      MVT::v32i16, Custom);
1898     setOperationAction(ISD::FSHR,      MVT::v32i16, Custom);
1899     setOperationAction(ISD::FSHL,      MVT::v16i32, Custom);
1900     setOperationAction(ISD::FSHR,      MVT::v16i32, Custom);
1901 
1902     if (Subtarget.hasDQI()) {
1903       for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
1904                        ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1905                        ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT})
1906         setOperationAction(Opc,           MVT::v8i64, Custom);
1907       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1908     }
1909 
1910     if (Subtarget.hasCDI()) {
1911       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1912       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1913         setOperationAction(ISD::CTLZ,            VT, Legal);
1914       }
1915     } // Subtarget.hasCDI()
1916 
1917     if (Subtarget.hasVPOPCNTDQ()) {
1918       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1919         setOperationAction(ISD::CTPOP, VT, Legal);
1920     }
1921 
1922     // Extract subvector is special because the value type
1923     // (result) is 256-bit but the source is 512-bit wide.
1924     // 128-bit was made Legal under AVX1.
1925     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1926                      MVT::v16f16, MVT::v8f32, MVT::v4f64 })
1927       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1928 
1929     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1930                      MVT::v32f16, MVT::v16f32, MVT::v8f64 }) {
1931       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1932       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1933       setOperationAction(ISD::SELECT,             VT, Custom);
1934       setOperationAction(ISD::VSELECT,            VT, Custom);
1935       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1936       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1937       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1938       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1939       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1940     }
1941     setF16Action(MVT::v32f16, Expand);
1942     setOperationAction(ISD::FP_ROUND, MVT::v16f16, Custom);
1943     setOperationAction(ISD::STRICT_FP_ROUND, MVT::v16f16, Custom);
1944     setOperationAction(ISD::FP_EXTEND, MVT::v16f32, Custom);
1945     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v16f32, Custom);
1946     for (unsigned Opc : {ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV}) {
1947       setOperationPromotedToType(Opc, MVT::v16f16, MVT::v16f32);
1948       setOperationPromotedToType(Opc, MVT::v32f16, MVT::v32f32);
1949     }
1950 
1951     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1952       setOperationAction(ISD::MLOAD,               VT, Legal);
1953       setOperationAction(ISD::MSTORE,              VT, Legal);
1954       setOperationAction(ISD::MGATHER,             VT, Custom);
1955       setOperationAction(ISD::MSCATTER,            VT, Custom);
1956     }
1957     if (HasBWI) {
1958       for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1959         setOperationAction(ISD::MLOAD,        VT, Legal);
1960         setOperationAction(ISD::MSTORE,       VT, Legal);
1961       }
1962     } else {
1963       setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1964       setOperationAction(ISD::STORE, MVT::v64i8,  Custom);
1965     }
1966 
1967     if (Subtarget.hasVBMI2()) {
1968       for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1969         setOperationAction(ISD::FSHL, VT, Custom);
1970         setOperationAction(ISD::FSHR, VT, Custom);
1971       }
1972 
1973       setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
1974       setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
1975     }
1976   }// useAVX512Regs
1977 
1978   if (!Subtarget.useSoftFloat() && Subtarget.hasVBMI2()) {
1979     for (auto VT : {MVT::v8i16, MVT::v4i32, MVT::v2i64, MVT::v16i16, MVT::v8i32,
1980                     MVT::v4i64}) {
1981       setOperationAction(ISD::FSHL, VT, Custom);
1982       setOperationAction(ISD::FSHR, VT, Custom);
1983     }
1984   }
1985 
1986   // This block controls legalization for operations that don't have
1987   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1988   // narrower widths.
1989   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1990     // These operations are handled on non-VLX by artificially widening in
1991     // isel patterns.
1992 
1993     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i32, Custom);
1994     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v4i32, Custom);
1995     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
1996 
1997     if (Subtarget.hasDQI()) {
1998       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1999       // v2f32 UINT_TO_FP is already custom under SSE2.
2000       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
2001              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
2002              "Unexpected operation action!");
2003       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
2004       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
2005       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
2006       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
2007       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
2008     }
2009 
2010     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
2011       setOperationAction(ISD::SMAX, VT, Legal);
2012       setOperationAction(ISD::UMAX, VT, Legal);
2013       setOperationAction(ISD::SMIN, VT, Legal);
2014       setOperationAction(ISD::UMIN, VT, Legal);
2015       setOperationAction(ISD::ABS,  VT, Legal);
2016     }
2017 
2018     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2019       setOperationAction(ISD::ROTL,     VT, Custom);
2020       setOperationAction(ISD::ROTR,     VT, Custom);
2021     }
2022 
2023     // Custom legalize 2x32 to get a little better code.
2024     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
2025     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
2026 
2027     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
2028                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
2029       setOperationAction(ISD::MSCATTER, VT, Custom);
2030 
2031     if (Subtarget.hasDQI()) {
2032       for (auto Opc : {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::STRICT_SINT_TO_FP,
2033                        ISD::STRICT_UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
2034                        ISD::STRICT_FP_TO_SINT, ISD::STRICT_FP_TO_UINT}) {
2035         setOperationAction(Opc, MVT::v2i64, Custom);
2036         setOperationAction(Opc, MVT::v4i64, Custom);
2037       }
2038       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
2039       setOperationAction(ISD::MUL, MVT::v4i64, Legal);
2040     }
2041 
2042     if (Subtarget.hasCDI()) {
2043       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
2044         setOperationAction(ISD::CTLZ,            VT, Legal);
2045       }
2046     } // Subtarget.hasCDI()
2047 
2048     if (Subtarget.hasVPOPCNTDQ()) {
2049       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
2050         setOperationAction(ISD::CTPOP, VT, Legal);
2051     }
2052     setOperationAction(ISD::FNEG, MVT::v32f16, Custom);
2053     setOperationAction(ISD::FABS, MVT::v32f16, Custom);
2054     setOperationAction(ISD::FCOPYSIGN, MVT::v32f16, Custom);
2055   }
2056 
2057   // This block control legalization of v32i1/v64i1 which are available with
2058   // AVX512BW..
2059   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
2060     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
2061     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
2062 
2063     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
2064       setOperationAction(ISD::VSELECT,            VT, Expand);
2065       setOperationAction(ISD::TRUNCATE,           VT, Custom);
2066       setOperationAction(ISD::SETCC,              VT, Custom);
2067       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2068       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
2069       setOperationAction(ISD::SELECT,             VT, Custom);
2070       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
2071       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
2072       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
2073       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
2074     }
2075 
2076     for (auto VT : { MVT::v16i1, MVT::v32i1 })
2077       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
2078 
2079     // Extends from v32i1 masks to 256-bit vectors.
2080     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
2081     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
2082     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
2083 
2084     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
2085       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
2086       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
2087     }
2088 
2089     // These operations are handled on non-VLX by artificially widening in
2090     // isel patterns.
2091     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
2092 
2093     if (Subtarget.hasBITALG()) {
2094       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
2095         setOperationAction(ISD::CTPOP, VT, Legal);
2096     }
2097   }
2098 
2099   if (!Subtarget.useSoftFloat() && Subtarget.hasFP16()) {
2100     auto setGroup = [&] (MVT VT) {
2101       setOperationAction(ISD::FADD,               VT, Legal);
2102       setOperationAction(ISD::STRICT_FADD,        VT, Legal);
2103       setOperationAction(ISD::FSUB,               VT, Legal);
2104       setOperationAction(ISD::STRICT_FSUB,        VT, Legal);
2105       setOperationAction(ISD::FMUL,               VT, Legal);
2106       setOperationAction(ISD::STRICT_FMUL,        VT, Legal);
2107       setOperationAction(ISD::FDIV,               VT, Legal);
2108       setOperationAction(ISD::STRICT_FDIV,        VT, Legal);
2109       setOperationAction(ISD::FSQRT,              VT, Legal);
2110       setOperationAction(ISD::STRICT_FSQRT,       VT, Legal);
2111 
2112       setOperationAction(ISD::FFLOOR,             VT, Legal);
2113       setOperationAction(ISD::STRICT_FFLOOR,      VT, Legal);
2114       setOperationAction(ISD::FCEIL,              VT, Legal);
2115       setOperationAction(ISD::STRICT_FCEIL,       VT, Legal);
2116       setOperationAction(ISD::FTRUNC,             VT, Legal);
2117       setOperationAction(ISD::STRICT_FTRUNC,      VT, Legal);
2118       setOperationAction(ISD::FRINT,              VT, Legal);
2119       setOperationAction(ISD::STRICT_FRINT,       VT, Legal);
2120       setOperationAction(ISD::FNEARBYINT,         VT, Legal);
2121       setOperationAction(ISD::STRICT_FNEARBYINT,  VT, Legal);
2122       setOperationAction(ISD::FROUNDEVEN, VT, Legal);
2123       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
2124 
2125       setOperationAction(ISD::FROUND,             VT, Custom);
2126 
2127       setOperationAction(ISD::LOAD,               VT, Legal);
2128       setOperationAction(ISD::STORE,              VT, Legal);
2129 
2130       setOperationAction(ISD::FMA,                VT, Legal);
2131       setOperationAction(ISD::STRICT_FMA,         VT, Legal);
2132       setOperationAction(ISD::VSELECT,            VT, Legal);
2133       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
2134       setOperationAction(ISD::SELECT,             VT, Custom);
2135 
2136       setOperationAction(ISD::FNEG,               VT, Custom);
2137       setOperationAction(ISD::FABS,               VT, Custom);
2138       setOperationAction(ISD::FCOPYSIGN,          VT, Custom);
2139       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
2140       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
2141 
2142       setOperationAction(ISD::SETCC,              VT, Custom);
2143       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
2144       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
2145     };
2146 
2147     // AVX512_FP16 scalar operations
2148     setGroup(MVT::f16);
2149     setOperationAction(ISD::FREM,                 MVT::f16, Promote);
2150     setOperationAction(ISD::STRICT_FREM,          MVT::f16, Promote);
2151     setOperationAction(ISD::SELECT_CC,            MVT::f16, Expand);
2152     setOperationAction(ISD::BR_CC,                MVT::f16, Expand);
2153     setOperationAction(ISD::STRICT_FROUND,        MVT::f16, Promote);
2154     setOperationAction(ISD::FROUNDEVEN,           MVT::f16, Legal);
2155     setOperationAction(ISD::STRICT_FROUNDEVEN,    MVT::f16, Legal);
2156     setOperationAction(ISD::FP_ROUND,             MVT::f16, Custom);
2157     setOperationAction(ISD::STRICT_FP_ROUND,      MVT::f16, Custom);
2158     setOperationAction(ISD::FMAXIMUM,             MVT::f16, Custom);
2159     setOperationAction(ISD::FMINIMUM,             MVT::f16, Custom);
2160     setOperationAction(ISD::FP_EXTEND,            MVT::f32, Legal);
2161     setOperationAction(ISD::STRICT_FP_EXTEND,     MVT::f32, Legal);
2162 
2163     setCondCodeAction(ISD::SETOEQ, MVT::f16, Expand);
2164     setCondCodeAction(ISD::SETUNE, MVT::f16, Expand);
2165 
2166     if (Subtarget.useAVX512Regs()) {
2167       setGroup(MVT::v32f16);
2168       setOperationAction(ISD::SCALAR_TO_VECTOR,       MVT::v32f16, Custom);
2169       setOperationAction(ISD::SINT_TO_FP,             MVT::v32i16, Legal);
2170       setOperationAction(ISD::STRICT_SINT_TO_FP,      MVT::v32i16, Legal);
2171       setOperationAction(ISD::UINT_TO_FP,             MVT::v32i16, Legal);
2172       setOperationAction(ISD::STRICT_UINT_TO_FP,      MVT::v32i16, Legal);
2173       setOperationAction(ISD::FP_ROUND,               MVT::v16f16, Legal);
2174       setOperationAction(ISD::STRICT_FP_ROUND,        MVT::v16f16, Legal);
2175       setOperationAction(ISD::FP_EXTEND,              MVT::v16f32, Custom);
2176       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v16f32, Legal);
2177       setOperationAction(ISD::FP_EXTEND,              MVT::v8f64,  Custom);
2178       setOperationAction(ISD::STRICT_FP_EXTEND,       MVT::v8f64,  Legal);
2179       setOperationAction(ISD::INSERT_VECTOR_ELT,      MVT::v32f16, Custom);
2180 
2181       setOperationAction(ISD::FP_TO_SINT,             MVT::v32i16, Custom);
2182       setOperationAction(ISD::STRICT_FP_TO_SINT,      MVT::v32i16, Custom);
2183       setOperationAction(ISD::FP_TO_UINT,             MVT::v32i16, Custom);
2184       setOperationAction(ISD::STRICT_FP_TO_UINT,      MVT::v32i16, Custom);
2185       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i8,  MVT::v32i16);
2186       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i8,
2187                                  MVT::v32i16);
2188       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i8,  MVT::v32i16);
2189       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i8,
2190                                  MVT::v32i16);
2191       setOperationPromotedToType(ISD::FP_TO_SINT,     MVT::v32i1,  MVT::v32i16);
2192       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v32i1,
2193                                  MVT::v32i16);
2194       setOperationPromotedToType(ISD::FP_TO_UINT,     MVT::v32i1,  MVT::v32i16);
2195       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v32i1,
2196                                  MVT::v32i16);
2197 
2198       setOperationAction(ISD::EXTRACT_SUBVECTOR,      MVT::v16f16, Legal);
2199       setOperationAction(ISD::INSERT_SUBVECTOR,       MVT::v32f16, Legal);
2200       setOperationAction(ISD::CONCAT_VECTORS,         MVT::v32f16, Custom);
2201 
2202       setLoadExtAction(ISD::EXTLOAD, MVT::v8f64,  MVT::v8f16,  Legal);
2203       setLoadExtAction(ISD::EXTLOAD, MVT::v16f32, MVT::v16f16, Legal);
2204     }
2205 
2206     if (Subtarget.hasVLX()) {
2207       setGroup(MVT::v8f16);
2208       setGroup(MVT::v16f16);
2209 
2210       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8f16,  Legal);
2211       setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16f16, Custom);
2212       setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Legal);
2213       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v16i16, Legal);
2214       setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16,  Legal);
2215       setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i16,  Legal);
2216       setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Legal);
2217       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v16i16, Legal);
2218       setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16,  Legal);
2219       setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v8i16,  Legal);
2220 
2221       setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
2222       setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v8i16, Custom);
2223       setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Custom);
2224       setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v8i16, Custom);
2225       setOperationAction(ISD::FP_ROUND,           MVT::v8f16, Legal);
2226       setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v8f16, Legal);
2227       setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Custom);
2228       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v8f32, Legal);
2229       setOperationAction(ISD::FP_EXTEND,          MVT::v4f64, Custom);
2230       setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
2231 
2232       // INSERT_VECTOR_ELT v8f16 extended to VECTOR_SHUFFLE
2233       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v8f16,  Custom);
2234       setOperationAction(ISD::INSERT_VECTOR_ELT,    MVT::v16f16, Custom);
2235 
2236       setOperationAction(ISD::EXTRACT_SUBVECTOR,    MVT::v8f16, Legal);
2237       setOperationAction(ISD::INSERT_SUBVECTOR,     MVT::v16f16, Legal);
2238       setOperationAction(ISD::CONCAT_VECTORS,       MVT::v16f16, Custom);
2239 
2240       setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f16, Legal);
2241       setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Legal);
2242       setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, MVT::v8f16, Legal);
2243       setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, MVT::v4f16, Legal);
2244 
2245       // Need to custom widen these to prevent scalarization.
2246       setOperationAction(ISD::LOAD,  MVT::v4f16, Custom);
2247       setOperationAction(ISD::STORE, MVT::v4f16, Custom);
2248     }
2249   }
2250 
2251   if (!Subtarget.useSoftFloat() &&
2252       (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16())) {
2253     addRegisterClass(MVT::v8bf16, Subtarget.hasAVX512() ? &X86::VR128XRegClass
2254                                                         : &X86::VR128RegClass);
2255     addRegisterClass(MVT::v16bf16, Subtarget.hasAVX512() ? &X86::VR256XRegClass
2256                                                          : &X86::VR256RegClass);
2257     // We set the type action of bf16 to TypeSoftPromoteHalf, but we don't
2258     // provide the method to promote BUILD_VECTOR and INSERT_VECTOR_ELT.
2259     // Set the operation action Custom to do the customization later.
2260     setOperationAction(ISD::BUILD_VECTOR, MVT::bf16, Custom);
2261     setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::bf16, Custom);
2262     for (auto VT : {MVT::v8bf16, MVT::v16bf16}) {
2263       setF16Action(VT, Expand);
2264       setOperationAction(ISD::FADD, VT, Expand);
2265       setOperationAction(ISD::FSUB, VT, Expand);
2266       setOperationAction(ISD::FMUL, VT, Expand);
2267       setOperationAction(ISD::FDIV, VT, Expand);
2268       setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
2269       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
2270       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
2271       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
2272     }
2273     setOperationAction(ISD::FP_ROUND, MVT::v8bf16, Custom);
2274     addLegalFPImmediate(APFloat::getZero(APFloat::BFloat()));
2275   }
2276 
2277   if (!Subtarget.useSoftFloat() && Subtarget.hasBF16()) {
2278     addRegisterClass(MVT::v32bf16, &X86::VR512RegClass);
2279     setF16Action(MVT::v32bf16, Expand);
2280     setOperationAction(ISD::FADD, MVT::v32bf16, Expand);
2281     setOperationAction(ISD::FSUB, MVT::v32bf16, Expand);
2282     setOperationAction(ISD::FMUL, MVT::v32bf16, Expand);
2283     setOperationAction(ISD::FDIV, MVT::v32bf16, Expand);
2284     setOperationAction(ISD::BUILD_VECTOR, MVT::v32bf16, Custom);
2285     setOperationAction(ISD::FP_ROUND, MVT::v16bf16, Custom);
2286     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32bf16, Custom);
2287     setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32bf16, Legal);
2288     setOperationAction(ISD::CONCAT_VECTORS, MVT::v32bf16, Custom);
2289   }
2290 
2291   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
2292     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
2293     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
2294     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
2295     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
2296     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
2297 
2298     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
2299     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
2300     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
2301     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
2302     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
2303 
2304     if (Subtarget.hasBWI()) {
2305       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
2306       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
2307     }
2308 
2309     if (Subtarget.hasFP16()) {
2310       // vcvttph2[u]dq v4f16 -> v4i32/64, v2f16 -> v2i32/64
2311       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f16, Custom);
2312       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f16, Custom);
2313       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f16, Custom);
2314       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f16, Custom);
2315       setOperationAction(ISD::FP_TO_SINT,        MVT::v4f16, Custom);
2316       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f16, Custom);
2317       setOperationAction(ISD::FP_TO_UINT,        MVT::v4f16, Custom);
2318       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f16, Custom);
2319       // vcvt[u]dq2ph v4i32/64 -> v4f16, v2i32/64 -> v2f16
2320       setOperationAction(ISD::SINT_TO_FP,        MVT::v2f16, Custom);
2321       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f16, Custom);
2322       setOperationAction(ISD::UINT_TO_FP,        MVT::v2f16, Custom);
2323       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f16, Custom);
2324       setOperationAction(ISD::SINT_TO_FP,        MVT::v4f16, Custom);
2325       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f16, Custom);
2326       setOperationAction(ISD::UINT_TO_FP,        MVT::v4f16, Custom);
2327       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f16, Custom);
2328       // vcvtps2phx v4f32 -> v4f16, v2f32 -> v2f16
2329       setOperationAction(ISD::FP_ROUND,          MVT::v2f16, Custom);
2330       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v2f16, Custom);
2331       setOperationAction(ISD::FP_ROUND,          MVT::v4f16, Custom);
2332       setOperationAction(ISD::STRICT_FP_ROUND,   MVT::v4f16, Custom);
2333       // vcvtph2psx v4f16 -> v4f32, v2f16 -> v2f32
2334       setOperationAction(ISD::FP_EXTEND,         MVT::v2f16, Custom);
2335       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v2f16, Custom);
2336       setOperationAction(ISD::FP_EXTEND,         MVT::v4f16, Custom);
2337       setOperationAction(ISD::STRICT_FP_EXTEND,  MVT::v4f16, Custom);
2338     }
2339   }
2340 
2341   if (!Subtarget.useSoftFloat() && Subtarget.hasAMXTILE()) {
2342     addRegisterClass(MVT::x86amx, &X86::TILERegClass);
2343   }
2344 
2345   // We want to custom lower some of our intrinsics.
2346   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
2347   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
2348   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
2349   if (!Subtarget.is64Bit()) {
2350     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
2351   }
2352 
2353   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
2354   // handle type legalization for these operations here.
2355   //
2356   // FIXME: We really should do custom legalization for addition and
2357   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
2358   // than generic legalization for 64-bit multiplication-with-overflow, though.
2359   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
2360     if (VT == MVT::i64 && !Subtarget.is64Bit())
2361       continue;
2362     // Add/Sub/Mul with overflow operations are custom lowered.
2363     setOperationAction(ISD::SADDO, VT, Custom);
2364     setOperationAction(ISD::UADDO, VT, Custom);
2365     setOperationAction(ISD::SSUBO, VT, Custom);
2366     setOperationAction(ISD::USUBO, VT, Custom);
2367     setOperationAction(ISD::SMULO, VT, Custom);
2368     setOperationAction(ISD::UMULO, VT, Custom);
2369 
2370     // Support carry in as value rather than glue.
2371     setOperationAction(ISD::UADDO_CARRY, VT, Custom);
2372     setOperationAction(ISD::USUBO_CARRY, VT, Custom);
2373     setOperationAction(ISD::SETCCCARRY, VT, Custom);
2374     setOperationAction(ISD::SADDO_CARRY, VT, Custom);
2375     setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
2376   }
2377 
2378   if (!Subtarget.is64Bit()) {
2379     // These libcalls are not available in 32-bit.
2380     setLibcallName(RTLIB::SHL_I128, nullptr);
2381     setLibcallName(RTLIB::SRL_I128, nullptr);
2382     setLibcallName(RTLIB::SRA_I128, nullptr);
2383     setLibcallName(RTLIB::MUL_I128, nullptr);
2384     // The MULO libcall is not part of libgcc, only compiler-rt.
2385     setLibcallName(RTLIB::MULO_I64, nullptr);
2386   }
2387   // The MULO libcall is not part of libgcc, only compiler-rt.
2388   setLibcallName(RTLIB::MULO_I128, nullptr);
2389 
2390   // Combine sin / cos into _sincos_stret if it is available.
2391   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
2392       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
2393     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
2394     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
2395   }
2396 
2397   if (Subtarget.isTargetWin64()) {
2398     setOperationAction(ISD::SDIV, MVT::i128, Custom);
2399     setOperationAction(ISD::UDIV, MVT::i128, Custom);
2400     setOperationAction(ISD::SREM, MVT::i128, Custom);
2401     setOperationAction(ISD::UREM, MVT::i128, Custom);
2402     setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
2403     setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
2404     setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
2405     setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
2406     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
2407     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
2408     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
2409     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
2410   }
2411 
2412   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
2413   // is. We should promote the value to 64-bits to solve this.
2414   // This is what the CRT headers do - `fmodf` is an inline header
2415   // function casting to f64 and calling `fmod`.
2416   if (Subtarget.is32Bit() &&
2417       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
2418     for (ISD::NodeType Op :
2419          {ISD::FCEIL,  ISD::STRICT_FCEIL,
2420           ISD::FCOS,   ISD::STRICT_FCOS,
2421           ISD::FEXP,   ISD::STRICT_FEXP,
2422           ISD::FFLOOR, ISD::STRICT_FFLOOR,
2423           ISD::FREM,   ISD::STRICT_FREM,
2424           ISD::FLOG,   ISD::STRICT_FLOG,
2425           ISD::FLOG10, ISD::STRICT_FLOG10,
2426           ISD::FPOW,   ISD::STRICT_FPOW,
2427           ISD::FSIN,   ISD::STRICT_FSIN})
2428       if (isOperationExpand(Op, MVT::f32))
2429         setOperationAction(Op, MVT::f32, Promote);
2430 
2431   // We have target-specific dag combine patterns for the following nodes:
2432   setTargetDAGCombine({ISD::VECTOR_SHUFFLE,
2433                        ISD::SCALAR_TO_VECTOR,
2434                        ISD::INSERT_VECTOR_ELT,
2435                        ISD::EXTRACT_VECTOR_ELT,
2436                        ISD::CONCAT_VECTORS,
2437                        ISD::INSERT_SUBVECTOR,
2438                        ISD::EXTRACT_SUBVECTOR,
2439                        ISD::BITCAST,
2440                        ISD::VSELECT,
2441                        ISD::SELECT,
2442                        ISD::SHL,
2443                        ISD::SRA,
2444                        ISD::SRL,
2445                        ISD::OR,
2446                        ISD::AND,
2447                        ISD::BITREVERSE,
2448                        ISD::ADD,
2449                        ISD::FADD,
2450                        ISD::FSUB,
2451                        ISD::FNEG,
2452                        ISD::FMA,
2453                        ISD::STRICT_FMA,
2454                        ISD::FMINNUM,
2455                        ISD::FMAXNUM,
2456                        ISD::SUB,
2457                        ISD::LOAD,
2458                        ISD::MLOAD,
2459                        ISD::STORE,
2460                        ISD::MSTORE,
2461                        ISD::TRUNCATE,
2462                        ISD::ZERO_EXTEND,
2463                        ISD::ANY_EXTEND,
2464                        ISD::SIGN_EXTEND,
2465                        ISD::SIGN_EXTEND_INREG,
2466                        ISD::ANY_EXTEND_VECTOR_INREG,
2467                        ISD::SIGN_EXTEND_VECTOR_INREG,
2468                        ISD::ZERO_EXTEND_VECTOR_INREG,
2469                        ISD::SINT_TO_FP,
2470                        ISD::UINT_TO_FP,
2471                        ISD::STRICT_SINT_TO_FP,
2472                        ISD::STRICT_UINT_TO_FP,
2473                        ISD::SETCC,
2474                        ISD::MUL,
2475                        ISD::XOR,
2476                        ISD::MSCATTER,
2477                        ISD::MGATHER,
2478                        ISD::FP16_TO_FP,
2479                        ISD::FP_EXTEND,
2480                        ISD::STRICT_FP_EXTEND,
2481                        ISD::FP_ROUND,
2482                        ISD::STRICT_FP_ROUND});
2483 
2484   computeRegisterProperties(Subtarget.getRegisterInfo());
2485 
2486   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2487   MaxStoresPerMemsetOptSize = 8;
2488   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2489   MaxStoresPerMemcpyOptSize = 4;
2490   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2491   MaxStoresPerMemmoveOptSize = 4;
2492 
2493   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2494   // that needs to benchmarked and balanced with the potential use of vector
2495   // load/store types (PR33329, PR33914).
2496   MaxLoadsPerMemcmp = 2;
2497   MaxLoadsPerMemcmpOptSize = 2;
2498 
2499   // Default loop alignment, which can be overridden by -align-loops.
2500   setPrefLoopAlignment(Align(16));
2501 
2502   // An out-of-order CPU can speculatively execute past a predictable branch,
2503   // but a conditional move could be stalled by an expensive earlier operation.
2504   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2505   EnableExtLdPromotion = true;
2506   setPrefFunctionAlignment(Align(16));
2507 
2508   verifyIntrinsicTables();
2509 
2510   // Default to having -disable-strictnode-mutation on
2511   IsStrictFPEnabled = true;
2512 }
2513 
2514 // This has so far only been implemented for 64-bit MachO.
useLoadStackGuardNode() const2515 bool X86TargetLowering::useLoadStackGuardNode() const {
2516   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2517 }
2518 
useStackGuardXorFP() const2519 bool X86TargetLowering::useStackGuardXorFP() const {
2520   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2521   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2522 }
2523 
emitStackGuardXorFP(SelectionDAG & DAG,SDValue Val,const SDLoc & DL) const2524 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2525                                                const SDLoc &DL) const {
2526   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2527   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2528   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2529   return SDValue(Node, 0);
2530 }
2531 
2532 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const2533 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2534   if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2535       !Subtarget.hasBWI())
2536     return TypeSplitVector;
2537 
2538   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2539       !Subtarget.hasF16C() && VT.getVectorElementType() == MVT::f16)
2540     return TypeSplitVector;
2541 
2542   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
2543       VT.getVectorElementType() != MVT::i1)
2544     return TypeWidenVector;
2545 
2546   return TargetLoweringBase::getPreferredVectorAction(VT);
2547 }
2548 
2549 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const2550 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2551                                   const TargetLibraryInfo *libInfo) const {
2552   return X86::createFastISel(funcInfo, libInfo);
2553 }
2554 
2555 //===----------------------------------------------------------------------===//
2556 //                           Other Lowering Hooks
2557 //===----------------------------------------------------------------------===//
2558 
mayFoldLoad(SDValue Op,const X86Subtarget & Subtarget,bool AssumeSingleUse)2559 bool X86::mayFoldLoad(SDValue Op, const X86Subtarget &Subtarget,
2560                       bool AssumeSingleUse) {
2561   if (!AssumeSingleUse && !Op.hasOneUse())
2562     return false;
2563   if (!ISD::isNormalLoad(Op.getNode()))
2564     return false;
2565 
2566   // If this is an unaligned vector, make sure the target supports folding it.
2567   auto *Ld = cast<LoadSDNode>(Op.getNode());
2568   if (!Subtarget.hasAVX() && !Subtarget.hasSSEUnalignedMem() &&
2569       Ld->getValueSizeInBits(0) == 128 && Ld->getAlign() < Align(16))
2570     return false;
2571 
2572   // TODO: If this is a non-temporal load and the target has an instruction
2573   //       for it, it should not be folded. See "useNonTemporalLoad()".
2574 
2575   return true;
2576 }
2577 
mayFoldLoadIntoBroadcastFromMem(SDValue Op,MVT EltVT,const X86Subtarget & Subtarget,bool AssumeSingleUse)2578 bool X86::mayFoldLoadIntoBroadcastFromMem(SDValue Op, MVT EltVT,
2579                                           const X86Subtarget &Subtarget,
2580                                           bool AssumeSingleUse) {
2581   assert(Subtarget.hasAVX() && "Expected AVX for broadcast from memory");
2582   if (!X86::mayFoldLoad(Op, Subtarget, AssumeSingleUse))
2583     return false;
2584 
2585   // We can not replace a wide volatile load with a broadcast-from-memory,
2586   // because that would narrow the load, which isn't legal for volatiles.
2587   auto *Ld = cast<LoadSDNode>(Op.getNode());
2588   return !Ld->isVolatile() ||
2589          Ld->getValueSizeInBits(0) == EltVT.getScalarSizeInBits();
2590 }
2591 
mayFoldIntoStore(SDValue Op)2592 bool X86::mayFoldIntoStore(SDValue Op) {
2593   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2594 }
2595 
mayFoldIntoZeroExtend(SDValue Op)2596 bool X86::mayFoldIntoZeroExtend(SDValue Op) {
2597   if (Op.hasOneUse()) {
2598     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
2599     return (ISD::ZERO_EXTEND == Opcode);
2600   }
2601   return false;
2602 }
2603 
isTargetShuffle(unsigned Opcode)2604 static bool isTargetShuffle(unsigned Opcode) {
2605   switch(Opcode) {
2606   default: return false;
2607   case X86ISD::BLENDI:
2608   case X86ISD::PSHUFB:
2609   case X86ISD::PSHUFD:
2610   case X86ISD::PSHUFHW:
2611   case X86ISD::PSHUFLW:
2612   case X86ISD::SHUFP:
2613   case X86ISD::INSERTPS:
2614   case X86ISD::EXTRQI:
2615   case X86ISD::INSERTQI:
2616   case X86ISD::VALIGN:
2617   case X86ISD::PALIGNR:
2618   case X86ISD::VSHLDQ:
2619   case X86ISD::VSRLDQ:
2620   case X86ISD::MOVLHPS:
2621   case X86ISD::MOVHLPS:
2622   case X86ISD::MOVSHDUP:
2623   case X86ISD::MOVSLDUP:
2624   case X86ISD::MOVDDUP:
2625   case X86ISD::MOVSS:
2626   case X86ISD::MOVSD:
2627   case X86ISD::MOVSH:
2628   case X86ISD::UNPCKL:
2629   case X86ISD::UNPCKH:
2630   case X86ISD::VBROADCAST:
2631   case X86ISD::VPERMILPI:
2632   case X86ISD::VPERMILPV:
2633   case X86ISD::VPERM2X128:
2634   case X86ISD::SHUF128:
2635   case X86ISD::VPERMIL2:
2636   case X86ISD::VPERMI:
2637   case X86ISD::VPPERM:
2638   case X86ISD::VPERMV:
2639   case X86ISD::VPERMV3:
2640   case X86ISD::VZEXT_MOVL:
2641     return true;
2642   }
2643 }
2644 
isTargetShuffleVariableMask(unsigned Opcode)2645 static bool isTargetShuffleVariableMask(unsigned Opcode) {
2646   switch (Opcode) {
2647   default: return false;
2648   // Target Shuffles.
2649   case X86ISD::PSHUFB:
2650   case X86ISD::VPERMILPV:
2651   case X86ISD::VPERMIL2:
2652   case X86ISD::VPPERM:
2653   case X86ISD::VPERMV:
2654   case X86ISD::VPERMV3:
2655     return true;
2656   // 'Faux' Target Shuffles.
2657   case ISD::OR:
2658   case ISD::AND:
2659   case X86ISD::ANDNP:
2660     return true;
2661   }
2662 }
2663 
getReturnAddressFrameIndex(SelectionDAG & DAG) const2664 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2665   MachineFunction &MF = DAG.getMachineFunction();
2666   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
2667   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2668   int ReturnAddrIndex = FuncInfo->getRAIndex();
2669 
2670   if (ReturnAddrIndex == 0) {
2671     // Set up a frame object for the return address.
2672     unsigned SlotSize = RegInfo->getSlotSize();
2673     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
2674                                                           -(int64_t)SlotSize,
2675                                                           false);
2676     FuncInfo->setRAIndex(ReturnAddrIndex);
2677   }
2678 
2679   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
2680 }
2681 
isOffsetSuitableForCodeModel(int64_t Offset,CodeModel::Model CM,bool HasSymbolicDisplacement)2682 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model CM,
2683                                        bool HasSymbolicDisplacement) {
2684   // Offset should fit into 32 bit immediate field.
2685   if (!isInt<32>(Offset))
2686     return false;
2687 
2688   // If we don't have a symbolic displacement - we don't have any extra
2689   // restrictions.
2690   if (!HasSymbolicDisplacement)
2691     return true;
2692 
2693   // We can fold large offsets in the large code model because we always use
2694   // 64-bit offsets.
2695   if (CM == CodeModel::Large)
2696     return true;
2697 
2698   // For kernel code model we know that all object resist in the negative half
2699   // of 32bits address space. We may not accept negative offsets, since they may
2700   // be just off and we may accept pretty large positive ones.
2701   if (CM == CodeModel::Kernel)
2702     return Offset >= 0;
2703 
2704   // For other non-large code models we assume that latest small object is 16MB
2705   // before end of 31 bits boundary. We may also accept pretty large negative
2706   // constants knowing that all objects are in the positive half of address
2707   // space.
2708   return Offset < 16 * 1024 * 1024;
2709 }
2710 
2711 /// Return true if the condition is an signed comparison operation.
isX86CCSigned(unsigned X86CC)2712 static bool isX86CCSigned(unsigned X86CC) {
2713   switch (X86CC) {
2714   default:
2715     llvm_unreachable("Invalid integer condition!");
2716   case X86::COND_E:
2717   case X86::COND_NE:
2718   case X86::COND_B:
2719   case X86::COND_A:
2720   case X86::COND_BE:
2721   case X86::COND_AE:
2722     return false;
2723   case X86::COND_G:
2724   case X86::COND_GE:
2725   case X86::COND_L:
2726   case X86::COND_LE:
2727     return true;
2728   }
2729 }
2730 
TranslateIntegerX86CC(ISD::CondCode SetCCOpcode)2731 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
2732   switch (SetCCOpcode) {
2733   default: llvm_unreachable("Invalid integer condition!");
2734   case ISD::SETEQ:  return X86::COND_E;
2735   case ISD::SETGT:  return X86::COND_G;
2736   case ISD::SETGE:  return X86::COND_GE;
2737   case ISD::SETLT:  return X86::COND_L;
2738   case ISD::SETLE:  return X86::COND_LE;
2739   case ISD::SETNE:  return X86::COND_NE;
2740   case ISD::SETULT: return X86::COND_B;
2741   case ISD::SETUGT: return X86::COND_A;
2742   case ISD::SETULE: return X86::COND_BE;
2743   case ISD::SETUGE: return X86::COND_AE;
2744   }
2745 }
2746 
2747 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
2748 /// condition code, returning the condition code and the LHS/RHS of the
2749 /// comparison to make.
TranslateX86CC(ISD::CondCode SetCCOpcode,const SDLoc & DL,bool isFP,SDValue & LHS,SDValue & RHS,SelectionDAG & DAG)2750 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
2751                                     bool isFP, SDValue &LHS, SDValue &RHS,
2752                                     SelectionDAG &DAG) {
2753   if (!isFP) {
2754     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2755       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnes()) {
2756         // X > -1   -> X == 0, jump !sign.
2757         RHS = DAG.getConstant(0, DL, RHS.getValueType());
2758         return X86::COND_NS;
2759       }
2760       if (SetCCOpcode == ISD::SETLT && RHSC->isZero()) {
2761         // X < 0   -> X == 0, jump on sign.
2762         return X86::COND_S;
2763       }
2764       if (SetCCOpcode == ISD::SETGE && RHSC->isZero()) {
2765         // X >= 0   -> X == 0, jump on !sign.
2766         return X86::COND_NS;
2767       }
2768       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
2769         // X < 1   -> X <= 0
2770         RHS = DAG.getConstant(0, DL, RHS.getValueType());
2771         return X86::COND_LE;
2772       }
2773     }
2774 
2775     return TranslateIntegerX86CC(SetCCOpcode);
2776   }
2777 
2778   // First determine if it is required or is profitable to flip the operands.
2779 
2780   // If LHS is a foldable load, but RHS is not, flip the condition.
2781   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
2782       !ISD::isNON_EXTLoad(RHS.getNode())) {
2783     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2784     std::swap(LHS, RHS);
2785   }
2786 
2787   switch (SetCCOpcode) {
2788   default: break;
2789   case ISD::SETOLT:
2790   case ISD::SETOLE:
2791   case ISD::SETUGT:
2792   case ISD::SETUGE:
2793     std::swap(LHS, RHS);
2794     break;
2795   }
2796 
2797   // On a floating point condition, the flags are set as follows:
2798   // ZF  PF  CF   op
2799   //  0 | 0 | 0 | X > Y
2800   //  0 | 0 | 1 | X < Y
2801   //  1 | 0 | 0 | X == Y
2802   //  1 | 1 | 1 | unordered
2803   switch (SetCCOpcode) {
2804   default: llvm_unreachable("Condcode should be pre-legalized away");
2805   case ISD::SETUEQ:
2806   case ISD::SETEQ:   return X86::COND_E;
2807   case ISD::SETOLT:              // flipped
2808   case ISD::SETOGT:
2809   case ISD::SETGT:   return X86::COND_A;
2810   case ISD::SETOLE:              // flipped
2811   case ISD::SETOGE:
2812   case ISD::SETGE:   return X86::COND_AE;
2813   case ISD::SETUGT:              // flipped
2814   case ISD::SETULT:
2815   case ISD::SETLT:   return X86::COND_B;
2816   case ISD::SETUGE:              // flipped
2817   case ISD::SETULE:
2818   case ISD::SETLE:   return X86::COND_BE;
2819   case ISD::SETONE:
2820   case ISD::SETNE:   return X86::COND_NE;
2821   case ISD::SETUO:   return X86::COND_P;
2822   case ISD::SETO:    return X86::COND_NP;
2823   case ISD::SETOEQ:
2824   case ISD::SETUNE:  return X86::COND_INVALID;
2825   }
2826 }
2827 
2828 /// Is there a floating point cmov for the specific X86 condition code?
2829 /// Current x86 isa includes the following FP cmov instructions:
2830 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
hasFPCMov(unsigned X86CC)2831 static bool hasFPCMov(unsigned X86CC) {
2832   switch (X86CC) {
2833   default:
2834     return false;
2835   case X86::COND_B:
2836   case X86::COND_BE:
2837   case X86::COND_E:
2838   case X86::COND_P:
2839   case X86::COND_A:
2840   case X86::COND_AE:
2841   case X86::COND_NE:
2842   case X86::COND_NP:
2843     return true;
2844   }
2845 }
2846 
useVPTERNLOG(const X86Subtarget & Subtarget,MVT VT)2847 static bool useVPTERNLOG(const X86Subtarget &Subtarget, MVT VT) {
2848   return Subtarget.hasVLX() || Subtarget.canExtendTo512DQ() ||
2849          VT.is512BitVector();
2850 }
2851 
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const2852 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
2853                                            const CallInst &I,
2854                                            MachineFunction &MF,
2855                                            unsigned Intrinsic) const {
2856   Info.flags = MachineMemOperand::MONone;
2857   Info.offset = 0;
2858 
2859   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
2860   if (!IntrData) {
2861     switch (Intrinsic) {
2862     case Intrinsic::x86_aesenc128kl:
2863     case Intrinsic::x86_aesdec128kl:
2864       Info.opc = ISD::INTRINSIC_W_CHAIN;
2865       Info.ptrVal = I.getArgOperand(1);
2866       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
2867       Info.align = Align(1);
2868       Info.flags |= MachineMemOperand::MOLoad;
2869       return true;
2870     case Intrinsic::x86_aesenc256kl:
2871     case Intrinsic::x86_aesdec256kl:
2872       Info.opc = ISD::INTRINSIC_W_CHAIN;
2873       Info.ptrVal = I.getArgOperand(1);
2874       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
2875       Info.align = Align(1);
2876       Info.flags |= MachineMemOperand::MOLoad;
2877       return true;
2878     case Intrinsic::x86_aesencwide128kl:
2879     case Intrinsic::x86_aesdecwide128kl:
2880       Info.opc = ISD::INTRINSIC_W_CHAIN;
2881       Info.ptrVal = I.getArgOperand(0);
2882       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
2883       Info.align = Align(1);
2884       Info.flags |= MachineMemOperand::MOLoad;
2885       return true;
2886     case Intrinsic::x86_aesencwide256kl:
2887     case Intrinsic::x86_aesdecwide256kl:
2888       Info.opc = ISD::INTRINSIC_W_CHAIN;
2889       Info.ptrVal = I.getArgOperand(0);
2890       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
2891       Info.align = Align(1);
2892       Info.flags |= MachineMemOperand::MOLoad;
2893       return true;
2894     case Intrinsic::x86_cmpccxadd32:
2895     case Intrinsic::x86_cmpccxadd64:
2896     case Intrinsic::x86_atomic_bts:
2897     case Intrinsic::x86_atomic_btc:
2898     case Intrinsic::x86_atomic_btr: {
2899       Info.opc = ISD::INTRINSIC_W_CHAIN;
2900       Info.ptrVal = I.getArgOperand(0);
2901       unsigned Size = I.getType()->getScalarSizeInBits();
2902       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
2903       Info.align = Align(Size);
2904       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
2905                     MachineMemOperand::MOVolatile;
2906       return true;
2907     }
2908     case Intrinsic::x86_atomic_bts_rm:
2909     case Intrinsic::x86_atomic_btc_rm:
2910     case Intrinsic::x86_atomic_btr_rm: {
2911       Info.opc = ISD::INTRINSIC_W_CHAIN;
2912       Info.ptrVal = I.getArgOperand(0);
2913       unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
2914       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
2915       Info.align = Align(Size);
2916       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
2917                     MachineMemOperand::MOVolatile;
2918       return true;
2919     }
2920     case Intrinsic::x86_aadd32:
2921     case Intrinsic::x86_aadd64:
2922     case Intrinsic::x86_aand32:
2923     case Intrinsic::x86_aand64:
2924     case Intrinsic::x86_aor32:
2925     case Intrinsic::x86_aor64:
2926     case Intrinsic::x86_axor32:
2927     case Intrinsic::x86_axor64:
2928     case Intrinsic::x86_atomic_add_cc:
2929     case Intrinsic::x86_atomic_sub_cc:
2930     case Intrinsic::x86_atomic_or_cc:
2931     case Intrinsic::x86_atomic_and_cc:
2932     case Intrinsic::x86_atomic_xor_cc: {
2933       Info.opc = ISD::INTRINSIC_W_CHAIN;
2934       Info.ptrVal = I.getArgOperand(0);
2935       unsigned Size = I.getArgOperand(1)->getType()->getScalarSizeInBits();
2936       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), Size);
2937       Info.align = Align(Size);
2938       Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
2939                     MachineMemOperand::MOVolatile;
2940       return true;
2941     }
2942     }
2943     return false;
2944   }
2945 
2946   switch (IntrData->Type) {
2947   case TRUNCATE_TO_MEM_VI8:
2948   case TRUNCATE_TO_MEM_VI16:
2949   case TRUNCATE_TO_MEM_VI32: {
2950     Info.opc = ISD::INTRINSIC_VOID;
2951     Info.ptrVal = I.getArgOperand(0);
2952     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
2953     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
2954     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
2955       ScalarVT = MVT::i8;
2956     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
2957       ScalarVT = MVT::i16;
2958     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
2959       ScalarVT = MVT::i32;
2960 
2961     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
2962     Info.align = Align(1);
2963     Info.flags |= MachineMemOperand::MOStore;
2964     break;
2965   }
2966   case GATHER:
2967   case GATHER_AVX2: {
2968     Info.opc = ISD::INTRINSIC_W_CHAIN;
2969     Info.ptrVal = nullptr;
2970     MVT DataVT = MVT::getVT(I.getType());
2971     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
2972     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
2973                                 IndexVT.getVectorNumElements());
2974     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
2975     Info.align = Align(1);
2976     Info.flags |= MachineMemOperand::MOLoad;
2977     break;
2978   }
2979   case SCATTER: {
2980     Info.opc = ISD::INTRINSIC_VOID;
2981     Info.ptrVal = nullptr;
2982     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
2983     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
2984     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
2985                                 IndexVT.getVectorNumElements());
2986     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
2987     Info.align = Align(1);
2988     Info.flags |= MachineMemOperand::MOStore;
2989     break;
2990   }
2991   default:
2992     return false;
2993   }
2994 
2995   return true;
2996 }
2997 
2998 /// Returns true if the target can instruction select the
2999 /// specified FP immediate natively. If false, the legalizer will
3000 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT,bool ForCodeSize) const3001 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
3002                                      bool ForCodeSize) const {
3003   for (const APFloat &FPImm : LegalFPImmediates)
3004     if (Imm.bitwiseIsEqual(FPImm))
3005       return true;
3006   return false;
3007 }
3008 
shouldReduceLoadWidth(SDNode * Load,ISD::LoadExtType ExtTy,EVT NewVT) const3009 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3010                                               ISD::LoadExtType ExtTy,
3011                                               EVT NewVT) const {
3012   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
3013 
3014   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3015   // relocation target a movq or addq instruction: don't let the load shrink.
3016   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3017   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3018     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3019       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3020 
3021   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
3022   // those uses are extracted directly into a store, then the extract + store
3023   // can be store-folded. Therefore, it's probably not worth splitting the load.
3024   EVT VT = Load->getValueType(0);
3025   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
3026     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
3027       // Skip uses of the chain value. Result 0 of the node is the load value.
3028       if (UI.getUse().getResNo() != 0)
3029         continue;
3030 
3031       // If this use is not an extract + store, it's probably worth splitting.
3032       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
3033           UI->use_begin()->getOpcode() != ISD::STORE)
3034         return true;
3035     }
3036     // All non-chain uses are extract + store.
3037     return false;
3038   }
3039 
3040   return true;
3041 }
3042 
3043 /// Returns true if it is beneficial to convert a load of a constant
3044 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const3045 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3046                                                           Type *Ty) const {
3047   assert(Ty->isIntegerTy());
3048 
3049   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3050   if (BitSize == 0 || BitSize > 64)
3051     return false;
3052   return true;
3053 }
3054 
reduceSelectOfFPConstantLoads(EVT CmpOpVT) const3055 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
3056   // If we are using XMM registers in the ABI and the condition of the select is
3057   // a floating-point compare and we have blendv or conditional move, then it is
3058   // cheaper to select instead of doing a cross-register move and creating a
3059   // load that depends on the compare result.
3060   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
3061   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
3062 }
3063 
convertSelectOfConstantsToMath(EVT VT) const3064 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
3065   // TODO: It might be a win to ease or lift this restriction, but the generic
3066   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
3067   if (VT.isVector() && Subtarget.hasAVX512())
3068     return false;
3069 
3070   return true;
3071 }
3072 
decomposeMulByConstant(LLVMContext & Context,EVT VT,SDValue C) const3073 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
3074                                                SDValue C) const {
3075   // TODO: We handle scalars using custom code, but generic combining could make
3076   // that unnecessary.
3077   APInt MulC;
3078   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
3079     return false;
3080 
3081   // Find the type this will be legalized too. Otherwise we might prematurely
3082   // convert this to shl+add/sub and then still have to type legalize those ops.
3083   // Another choice would be to defer the decision for illegal types until
3084   // after type legalization. But constant splat vectors of i64 can't make it
3085   // through type legalization on 32-bit targets so we would need to special
3086   // case vXi64.
3087   while (getTypeAction(Context, VT) != TypeLegal)
3088     VT = getTypeToTransformTo(Context, VT);
3089 
3090   // If vector multiply is legal, assume that's faster than shl + add/sub.
3091   // Multiply is a complex op with higher latency and lower throughput in
3092   // most implementations, sub-vXi32 vector multiplies are always fast,
3093   // vXi32 mustn't have a SlowMULLD implementation, and anything larger (vXi64)
3094   // is always going to be slow.
3095   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3096   if (isOperationLegal(ISD::MUL, VT) && EltSizeInBits <= 32 &&
3097       (EltSizeInBits != 32 || !Subtarget.isPMULLDSlow()))
3098     return false;
3099 
3100   // shl+add, shl+sub, shl+add+neg
3101   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
3102          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
3103 }
3104 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const3105 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
3106                                                 unsigned Index) const {
3107   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3108     return false;
3109 
3110   // Mask vectors support all subregister combinations and operations that
3111   // extract half of vector.
3112   if (ResVT.getVectorElementType() == MVT::i1)
3113     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
3114                           (Index == ResVT.getVectorNumElements()));
3115 
3116   return (Index % ResVT.getVectorNumElements()) == 0;
3117 }
3118 
shouldScalarizeBinop(SDValue VecOp) const3119 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
3120   unsigned Opc = VecOp.getOpcode();
3121 
3122   // Assume target opcodes can't be scalarized.
3123   // TODO - do we have any exceptions?
3124   if (Opc >= ISD::BUILTIN_OP_END)
3125     return false;
3126 
3127   // If the vector op is not supported, try to convert to scalar.
3128   EVT VecVT = VecOp.getValueType();
3129   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
3130     return true;
3131 
3132   // If the vector op is supported, but the scalar op is not, the transform may
3133   // not be worthwhile.
3134   EVT ScalarVT = VecVT.getScalarType();
3135   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
3136 }
3137 
shouldFormOverflowOp(unsigned Opcode,EVT VT,bool) const3138 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
3139                                              bool) const {
3140   // TODO: Allow vectors?
3141   if (VT.isVector())
3142     return false;
3143   return VT.isSimple() || !isOperationExpand(Opcode, VT);
3144 }
3145 
isCheapToSpeculateCttz(Type * Ty) const3146 bool X86TargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
3147   // Speculate cttz only if we can directly use TZCNT or can promote to i32.
3148   return Subtarget.hasBMI() ||
3149          (!Ty->isVectorTy() && Ty->getScalarSizeInBits() < 32);
3150 }
3151 
isCheapToSpeculateCtlz(Type * Ty) const3152 bool X86TargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
3153   // Speculate ctlz only if we can directly use LZCNT.
3154   return Subtarget.hasLZCNT();
3155 }
3156 
ShouldShrinkFPConstant(EVT VT) const3157 bool X86TargetLowering::ShouldShrinkFPConstant(EVT VT) const {
3158   // Don't shrink FP constpool if SSE2 is available since cvtss2sd is more
3159   // expensive than a straight movsd. On the other hand, it's important to
3160   // shrink long double fp constant since fldt is very slow.
3161   return !Subtarget.hasSSE2() || VT == MVT::f80;
3162 }
3163 
isScalarFPTypeInSSEReg(EVT VT) const3164 bool X86TargetLowering::isScalarFPTypeInSSEReg(EVT VT) const {
3165   return (VT == MVT::f64 && Subtarget.hasSSE2()) ||
3166          (VT == MVT::f32 && Subtarget.hasSSE1()) || VT == MVT::f16;
3167 }
3168 
isLoadBitCastBeneficial(EVT LoadVT,EVT BitcastVT,const SelectionDAG & DAG,const MachineMemOperand & MMO) const3169 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
3170                                                 const SelectionDAG &DAG,
3171                                                 const MachineMemOperand &MMO) const {
3172   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
3173       BitcastVT.getVectorElementType() == MVT::i1)
3174     return false;
3175 
3176   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
3177     return false;
3178 
3179   // If both types are legal vectors, it's always ok to convert them.
3180   if (LoadVT.isVector() && BitcastVT.isVector() &&
3181       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
3182     return true;
3183 
3184   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
3185 }
3186 
canMergeStoresTo(unsigned AddressSpace,EVT MemVT,const MachineFunction & MF) const3187 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
3188                                          const MachineFunction &MF) const {
3189   // Do not merge to float value size (128 bytes) if no implicit
3190   // float attribute is set.
3191   bool NoFloat = MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat);
3192 
3193   if (NoFloat) {
3194     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
3195     return (MemVT.getSizeInBits() <= MaxIntSize);
3196   }
3197   // Make sure we don't merge greater than our preferred vector
3198   // width.
3199   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
3200     return false;
3201 
3202   return true;
3203 }
3204 
isCtlzFast() const3205 bool X86TargetLowering::isCtlzFast() const {
3206   return Subtarget.hasFastLZCNT();
3207 }
3208 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const3209 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
3210     const Instruction &AndI) const {
3211   return true;
3212 }
3213 
hasAndNotCompare(SDValue Y) const3214 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
3215   EVT VT = Y.getValueType();
3216 
3217   if (VT.isVector())
3218     return false;
3219 
3220   if (!Subtarget.hasBMI())
3221     return false;
3222 
3223   // There are only 32-bit and 64-bit forms for 'andn'.
3224   if (VT != MVT::i32 && VT != MVT::i64)
3225     return false;
3226 
3227   return !isa<ConstantSDNode>(Y);
3228 }
3229 
hasAndNot(SDValue Y) const3230 bool X86TargetLowering::hasAndNot(SDValue Y) const {
3231   EVT VT = Y.getValueType();
3232 
3233   if (!VT.isVector())
3234     return hasAndNotCompare(Y);
3235 
3236   // Vector.
3237 
3238   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
3239     return false;
3240 
3241   if (VT == MVT::v4i32)
3242     return true;
3243 
3244   return Subtarget.hasSSE2();
3245 }
3246 
hasBitTest(SDValue X,SDValue Y) const3247 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
3248   return X.getValueType().isScalarInteger(); // 'bt'
3249 }
3250 
3251 bool X86TargetLowering::
shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X,ConstantSDNode * XC,ConstantSDNode * CC,SDValue Y,unsigned OldShiftOpcode,unsigned NewShiftOpcode,SelectionDAG & DAG) const3252     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3253         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
3254         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
3255         SelectionDAG &DAG) const {
3256   // Does baseline recommend not to perform the fold by default?
3257   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3258           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
3259     return false;
3260   // For scalars this transform is always beneficial.
3261   if (X.getValueType().isScalarInteger())
3262     return true;
3263   // If all the shift amounts are identical, then transform is beneficial even
3264   // with rudimentary SSE2 shifts.
3265   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
3266     return true;
3267   // If we have AVX2 with it's powerful shift operations, then it's also good.
3268   if (Subtarget.hasAVX2())
3269     return true;
3270   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
3271   return NewShiftOpcode == ISD::SHL;
3272 }
3273 
preferedOpcodeForCmpEqPiecesOfOperand(EVT VT,unsigned ShiftOpc,bool MayTransformRotate,const APInt & ShiftOrRotateAmt,const std::optional<APInt> & AndMask) const3274 unsigned X86TargetLowering::preferedOpcodeForCmpEqPiecesOfOperand(
3275     EVT VT, unsigned ShiftOpc, bool MayTransformRotate,
3276     const APInt &ShiftOrRotateAmt, const std::optional<APInt> &AndMask) const {
3277   if (!VT.isInteger())
3278     return ShiftOpc;
3279 
3280   bool PreferRotate = false;
3281   if (VT.isVector()) {
3282     // For vectors, if we have rotate instruction support, then its definetly
3283     // best. Otherwise its not clear what the best so just don't make changed.
3284     PreferRotate = Subtarget.hasAVX512() && (VT.getScalarType() == MVT::i32 ||
3285                                              VT.getScalarType() == MVT::i64);
3286   } else {
3287     // For scalar, if we have bmi prefer rotate for rorx. Otherwise prefer
3288     // rotate unless we have a zext mask+shr.
3289     PreferRotate = Subtarget.hasBMI2();
3290     if (!PreferRotate) {
3291       unsigned MaskBits =
3292           VT.getScalarSizeInBits() - ShiftOrRotateAmt.getZExtValue();
3293       PreferRotate = (MaskBits != 8) && (MaskBits != 16) && (MaskBits != 32);
3294     }
3295   }
3296 
3297   if (ShiftOpc == ISD::SHL || ShiftOpc == ISD::SRL) {
3298     assert(AndMask.has_value() && "Null andmask when querying about shift+and");
3299 
3300     if (PreferRotate && MayTransformRotate)
3301       return ISD::ROTL;
3302 
3303     // If vector we don't really get much benefit swapping around constants.
3304     // Maybe we could check if the DAG has the flipped node already in the
3305     // future.
3306     if (VT.isVector())
3307       return ShiftOpc;
3308 
3309     // See if the beneficial to swap shift type.
3310     if (ShiftOpc == ISD::SHL) {
3311       // If the current setup has imm64 mask, then inverse will have
3312       // at least imm32 mask (or be zext i32 -> i64).
3313       if (VT == MVT::i64)
3314         return AndMask->getSignificantBits() > 32 ? (unsigned)ISD::SRL
3315                                                   : ShiftOpc;
3316 
3317       // We can only benefit if req at least 7-bit for the mask. We
3318       // don't want to replace shl of 1,2,3 as they can be implemented
3319       // with lea/add.
3320       return ShiftOrRotateAmt.uge(7) ? (unsigned)ISD::SRL : ShiftOpc;
3321     }
3322 
3323     if (VT == MVT::i64)
3324       // Keep exactly 32-bit imm64, this is zext i32 -> i64 which is
3325       // extremely efficient.
3326       return AndMask->getSignificantBits() > 33 ? (unsigned)ISD::SHL : ShiftOpc;
3327 
3328     // Keep small shifts as shl so we can generate add/lea.
3329     return ShiftOrRotateAmt.ult(7) ? (unsigned)ISD::SHL : ShiftOpc;
3330   }
3331 
3332   // We prefer rotate for vectors of if we won't get a zext mask with SRL
3333   // (PreferRotate will be set in the latter case).
3334   if (PreferRotate || VT.isVector())
3335     return ShiftOpc;
3336 
3337   // Non-vector type and we have a zext mask with SRL.
3338   return ISD::SRL;
3339 }
3340 
preferScalarizeSplat(SDNode * N) const3341 bool X86TargetLowering::preferScalarizeSplat(SDNode *N) const {
3342   return N->getOpcode() != ISD::FP_EXTEND;
3343 }
3344 
shouldFoldConstantShiftPairToMask(const SDNode * N,CombineLevel Level) const3345 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
3346     const SDNode *N, CombineLevel Level) const {
3347   assert(((N->getOpcode() == ISD::SHL &&
3348            N->getOperand(0).getOpcode() == ISD::SRL) ||
3349           (N->getOpcode() == ISD::SRL &&
3350            N->getOperand(0).getOpcode() == ISD::SHL)) &&
3351          "Expected shift-shift mask");
3352   // TODO: Should we always create i64 masks? Or only folded immediates?
3353   EVT VT = N->getValueType(0);
3354   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
3355       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
3356     // Only fold if the shift values are equal - so it folds to AND.
3357     // TODO - we should fold if either is a non-uniform vector but we don't do
3358     // the fold for non-splats yet.
3359     return N->getOperand(1) == N->getOperand(0).getOperand(1);
3360   }
3361   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
3362 }
3363 
shouldFoldMaskToVariableShiftPair(SDValue Y) const3364 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
3365   EVT VT = Y.getValueType();
3366 
3367   // For vectors, we don't have a preference, but we probably want a mask.
3368   if (VT.isVector())
3369     return false;
3370 
3371   // 64-bit shifts on 32-bit targets produce really bad bloated code.
3372   if (VT == MVT::i64 && !Subtarget.is64Bit())
3373     return false;
3374 
3375   return true;
3376 }
3377 
3378 TargetLowering::ShiftLegalizationStrategy
preferredShiftLegalizationStrategy(SelectionDAG & DAG,SDNode * N,unsigned ExpansionFactor) const3379 X86TargetLowering::preferredShiftLegalizationStrategy(
3380     SelectionDAG &DAG, SDNode *N, unsigned ExpansionFactor) const {
3381   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
3382       !Subtarget.isOSWindows())
3383     return ShiftLegalizationStrategy::LowerToLibcall;
3384   return TargetLowering::preferredShiftLegalizationStrategy(DAG, N,
3385                                                             ExpansionFactor);
3386 }
3387 
shouldSplatInsEltVarIndex(EVT VT) const3388 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
3389   // Any legal vector type can be splatted more efficiently than
3390   // loading/spilling from memory.
3391   return isTypeLegal(VT);
3392 }
3393 
hasFastEqualityCompare(unsigned NumBits) const3394 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
3395   MVT VT = MVT::getIntegerVT(NumBits);
3396   if (isTypeLegal(VT))
3397     return VT;
3398 
3399   // PMOVMSKB can handle this.
3400   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
3401     return MVT::v16i8;
3402 
3403   // VPMOVMSKB can handle this.
3404   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
3405     return MVT::v32i8;
3406 
3407   // TODO: Allow 64-bit type for 32-bit target.
3408   // TODO: 512-bit types should be allowed, but make sure that those
3409   // cases are handled in combineVectorSizedSetCCEquality().
3410 
3411   return MVT::INVALID_SIMPLE_VALUE_TYPE;
3412 }
3413 
3414 /// Val is the undef sentinel value or equal to the specified value.
isUndefOrEqual(int Val,int CmpVal)3415 static bool isUndefOrEqual(int Val, int CmpVal) {
3416   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
3417 }
3418 
3419 /// Return true if every element in Mask is the undef sentinel value or equal to
3420 /// the specified value.
isUndefOrEqual(ArrayRef<int> Mask,int CmpVal)3421 static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
3422   return llvm::all_of(Mask, [CmpVal](int M) {
3423     return (M == SM_SentinelUndef) || (M == CmpVal);
3424   });
3425 }
3426 
3427 /// Return true if every element in Mask, beginning from position Pos and ending
3428 /// in Pos+Size is the undef sentinel value or equal to the specified value.
isUndefOrEqualInRange(ArrayRef<int> Mask,int CmpVal,unsigned Pos,unsigned Size)3429 static bool isUndefOrEqualInRange(ArrayRef<int> Mask, int CmpVal, unsigned Pos,
3430                                   unsigned Size) {
3431   return llvm::all_of(Mask.slice(Pos, Size),
3432                       [CmpVal](int M) { return isUndefOrEqual(M, CmpVal); });
3433 }
3434 
3435 /// Val is either the undef or zero sentinel value.
isUndefOrZero(int Val)3436 static bool isUndefOrZero(int Val) {
3437   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
3438 }
3439 
3440 /// Return true if every element in Mask, beginning from position Pos and ending
3441 /// in Pos+Size is the undef sentinel value.
isUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)3442 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3443   return llvm::all_of(Mask.slice(Pos, Size),
3444                       [](int M) { return M == SM_SentinelUndef; });
3445 }
3446 
3447 /// Return true if the mask creates a vector whose lower half is undefined.
isUndefLowerHalf(ArrayRef<int> Mask)3448 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
3449   unsigned NumElts = Mask.size();
3450   return isUndefInRange(Mask, 0, NumElts / 2);
3451 }
3452 
3453 /// Return true if the mask creates a vector whose upper half is undefined.
isUndefUpperHalf(ArrayRef<int> Mask)3454 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
3455   unsigned NumElts = Mask.size();
3456   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
3457 }
3458 
3459 /// Return true if Val falls within the specified range (L, H].
isInRange(int Val,int Low,int Hi)3460 static bool isInRange(int Val, int Low, int Hi) {
3461   return (Val >= Low && Val < Hi);
3462 }
3463 
3464 /// Return true if the value of any element in Mask falls within the specified
3465 /// range (L, H].
isAnyInRange(ArrayRef<int> Mask,int Low,int Hi)3466 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
3467   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
3468 }
3469 
3470 /// Return true if the value of any element in Mask is the zero sentinel value.
isAnyZero(ArrayRef<int> Mask)3471 static bool isAnyZero(ArrayRef<int> Mask) {
3472   return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
3473 }
3474 
3475 /// Return true if the value of any element in Mask is the zero or undef
3476 /// sentinel values.
isAnyZeroOrUndef(ArrayRef<int> Mask)3477 static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
3478   return llvm::any_of(Mask, [](int M) {
3479     return M == SM_SentinelZero || M == SM_SentinelUndef;
3480   });
3481 }
3482 
3483 /// Return true if Val is undef or if its value falls within the
3484 /// specified range (L, H].
isUndefOrInRange(int Val,int Low,int Hi)3485 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3486   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
3487 }
3488 
3489 /// Return true if every element in Mask is undef or if its value
3490 /// falls within the specified range (L, H].
isUndefOrInRange(ArrayRef<int> Mask,int Low,int Hi)3491 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
3492   return llvm::all_of(
3493       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
3494 }
3495 
3496 /// Return true if Val is undef, zero or if its value falls within the
3497 /// specified range (L, H].
isUndefOrZeroOrInRange(int Val,int Low,int Hi)3498 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
3499   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
3500 }
3501 
3502 /// Return true if every element in Mask is undef, zero or if its value
3503 /// falls within the specified range (L, H].
isUndefOrZeroOrInRange(ArrayRef<int> Mask,int Low,int Hi)3504 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
3505   return llvm::all_of(
3506       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
3507 }
3508 
3509 /// Return true if every element in Mask, beginning
3510 /// from position Pos and ending in Pos + Size, falls within the specified
3511 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
isSequentialOrUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)3512 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
3513                                        unsigned Size, int Low, int Step = 1) {
3514   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
3515     if (!isUndefOrEqual(Mask[i], Low))
3516       return false;
3517   return true;
3518 }
3519 
3520 /// Return true if every element in Mask, beginning
3521 /// from position Pos and ending in Pos+Size, falls within the specified
3522 /// sequential range (Low, Low+Size], or is undef or is zero.
isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)3523 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
3524                                              unsigned Size, int Low,
3525                                              int Step = 1) {
3526   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
3527     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
3528       return false;
3529   return true;
3530 }
3531 
3532 /// Return true if every element in Mask, beginning
3533 /// from position Pos and ending in Pos+Size is undef or is zero.
isUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)3534 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
3535                                  unsigned Size) {
3536   return llvm::all_of(Mask.slice(Pos, Size), isUndefOrZero);
3537 }
3538 
3539 /// Helper function to test whether a shuffle mask could be
3540 /// simplified by widening the elements being shuffled.
3541 ///
3542 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
3543 /// leaves it in an unspecified state.
3544 ///
3545 /// NOTE: This must handle normal vector shuffle masks and *target* vector
3546 /// shuffle masks. The latter have the special property of a '-2' representing
3547 /// a zero-ed lane of a vector.
canWidenShuffleElements(ArrayRef<int> Mask,SmallVectorImpl<int> & WidenedMask)3548 static bool canWidenShuffleElements(ArrayRef<int> Mask,
3549                                     SmallVectorImpl<int> &WidenedMask) {
3550   WidenedMask.assign(Mask.size() / 2, 0);
3551   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
3552     int M0 = Mask[i];
3553     int M1 = Mask[i + 1];
3554 
3555     // If both elements are undef, its trivial.
3556     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
3557       WidenedMask[i / 2] = SM_SentinelUndef;
3558       continue;
3559     }
3560 
3561     // Check for an undef mask and a mask value properly aligned to fit with
3562     // a pair of values. If we find such a case, use the non-undef mask's value.
3563     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
3564       WidenedMask[i / 2] = M1 / 2;
3565       continue;
3566     }
3567     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
3568       WidenedMask[i / 2] = M0 / 2;
3569       continue;
3570     }
3571 
3572     // When zeroing, we need to spread the zeroing across both lanes to widen.
3573     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
3574       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
3575           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
3576         WidenedMask[i / 2] = SM_SentinelZero;
3577         continue;
3578       }
3579       return false;
3580     }
3581 
3582     // Finally check if the two mask values are adjacent and aligned with
3583     // a pair.
3584     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
3585       WidenedMask[i / 2] = M0 / 2;
3586       continue;
3587     }
3588 
3589     // Otherwise we can't safely widen the elements used in this shuffle.
3590     return false;
3591   }
3592   assert(WidenedMask.size() == Mask.size() / 2 &&
3593          "Incorrect size of mask after widening the elements!");
3594 
3595   return true;
3596 }
3597 
canWidenShuffleElements(ArrayRef<int> Mask,const APInt & Zeroable,bool V2IsZero,SmallVectorImpl<int> & WidenedMask)3598 static bool canWidenShuffleElements(ArrayRef<int> Mask,
3599                                     const APInt &Zeroable,
3600                                     bool V2IsZero,
3601                                     SmallVectorImpl<int> &WidenedMask) {
3602   // Create an alternative mask with info about zeroable elements.
3603   // Here we do not set undef elements as zeroable.
3604   SmallVector<int, 64> ZeroableMask(Mask);
3605   if (V2IsZero) {
3606     assert(!Zeroable.isZero() && "V2's non-undef elements are used?!");
3607     for (int i = 0, Size = Mask.size(); i != Size; ++i)
3608       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
3609         ZeroableMask[i] = SM_SentinelZero;
3610   }
3611   return canWidenShuffleElements(ZeroableMask, WidenedMask);
3612 }
3613 
canWidenShuffleElements(ArrayRef<int> Mask)3614 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
3615   SmallVector<int, 32> WidenedMask;
3616   return canWidenShuffleElements(Mask, WidenedMask);
3617 }
3618 
3619 // Attempt to narrow/widen shuffle mask until it matches the target number of
3620 // elements.
scaleShuffleElements(ArrayRef<int> Mask,unsigned NumDstElts,SmallVectorImpl<int> & ScaledMask)3621 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
3622                                  SmallVectorImpl<int> &ScaledMask) {
3623   unsigned NumSrcElts = Mask.size();
3624   assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
3625          "Illegal shuffle scale factor");
3626 
3627   // Narrowing is guaranteed to work.
3628   if (NumDstElts >= NumSrcElts) {
3629     int Scale = NumDstElts / NumSrcElts;
3630     llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
3631     return true;
3632   }
3633 
3634   // We have to repeat the widening until we reach the target size, but we can
3635   // split out the first widening as it sets up ScaledMask for us.
3636   if (canWidenShuffleElements(Mask, ScaledMask)) {
3637     while (ScaledMask.size() > NumDstElts) {
3638       SmallVector<int, 16> WidenedMask;
3639       if (!canWidenShuffleElements(ScaledMask, WidenedMask))
3640         return false;
3641       ScaledMask = std::move(WidenedMask);
3642     }
3643     return true;
3644   }
3645 
3646   return false;
3647 }
3648 
3649 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
isZeroNode(SDValue Elt)3650 bool X86::isZeroNode(SDValue Elt) {
3651   return isNullConstant(Elt) || isNullFPConstant(Elt);
3652 }
3653 
3654 // Build a vector of constants.
3655 // Use an UNDEF node if MaskElt == -1.
3656 // Split 64-bit constants in the 32-bit mode.
getConstVector(ArrayRef<int> Values,MVT VT,SelectionDAG & DAG,const SDLoc & dl,bool IsMask=false)3657 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
3658                               const SDLoc &dl, bool IsMask = false) {
3659 
3660   SmallVector<SDValue, 32>  Ops;
3661   bool Split = false;
3662 
3663   MVT ConstVecVT = VT;
3664   unsigned NumElts = VT.getVectorNumElements();
3665   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
3666   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
3667     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
3668     Split = true;
3669   }
3670 
3671   MVT EltVT = ConstVecVT.getVectorElementType();
3672   for (unsigned i = 0; i < NumElts; ++i) {
3673     bool IsUndef = Values[i] < 0 && IsMask;
3674     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
3675       DAG.getConstant(Values[i], dl, EltVT);
3676     Ops.push_back(OpNode);
3677     if (Split)
3678       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
3679                     DAG.getConstant(0, dl, EltVT));
3680   }
3681   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
3682   if (Split)
3683     ConstsNode = DAG.getBitcast(VT, ConstsNode);
3684   return ConstsNode;
3685 }
3686 
getConstVector(ArrayRef<APInt> Bits,const APInt & Undefs,MVT VT,SelectionDAG & DAG,const SDLoc & dl)3687 static SDValue getConstVector(ArrayRef<APInt> Bits, const APInt &Undefs,
3688                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
3689   assert(Bits.size() == Undefs.getBitWidth() &&
3690          "Unequal constant and undef arrays");
3691   SmallVector<SDValue, 32> Ops;
3692   bool Split = false;
3693 
3694   MVT ConstVecVT = VT;
3695   unsigned NumElts = VT.getVectorNumElements();
3696   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
3697   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
3698     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
3699     Split = true;
3700   }
3701 
3702   MVT EltVT = ConstVecVT.getVectorElementType();
3703   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
3704     if (Undefs[i]) {
3705       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
3706       continue;
3707     }
3708     const APInt &V = Bits[i];
3709     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
3710     if (Split) {
3711       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
3712       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
3713     } else if (EltVT == MVT::f32) {
3714       APFloat FV(APFloat::IEEEsingle(), V);
3715       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
3716     } else if (EltVT == MVT::f64) {
3717       APFloat FV(APFloat::IEEEdouble(), V);
3718       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
3719     } else {
3720       Ops.push_back(DAG.getConstant(V, dl, EltVT));
3721     }
3722   }
3723 
3724   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
3725   return DAG.getBitcast(VT, ConstsNode);
3726 }
3727 
getConstVector(ArrayRef<APInt> Bits,MVT VT,SelectionDAG & DAG,const SDLoc & dl)3728 static SDValue getConstVector(ArrayRef<APInt> Bits, MVT VT,
3729                               SelectionDAG &DAG, const SDLoc &dl) {
3730   APInt Undefs = APInt::getZero(Bits.size());
3731   return getConstVector(Bits, Undefs, VT, DAG, dl);
3732 }
3733 
3734 /// Returns a vector of specified type with all zero elements.
getZeroVector(MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)3735 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
3736                              SelectionDAG &DAG, const SDLoc &dl) {
3737   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
3738           VT.getVectorElementType() == MVT::i1) &&
3739          "Unexpected vector type");
3740 
3741   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
3742   // type. This ensures they get CSE'd. But if the integer type is not
3743   // available, use a floating-point +0.0 instead.
3744   SDValue Vec;
3745   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3746   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
3747     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
3748   } else if (VT.isFloatingPoint() &&
3749              TLI.isTypeLegal(VT.getVectorElementType())) {
3750     Vec = DAG.getConstantFP(+0.0, dl, VT);
3751   } else if (VT.getVectorElementType() == MVT::i1) {
3752     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
3753            "Unexpected vector type");
3754     Vec = DAG.getConstant(0, dl, VT);
3755   } else {
3756     unsigned Num32BitElts = VT.getSizeInBits() / 32;
3757     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
3758   }
3759   return DAG.getBitcast(VT, Vec);
3760 }
3761 
3762 // Helper to determine if the ops are all the extracted subvectors come from a
3763 // single source. If we allow commute they don't have to be in order (Lo/Hi).
getSplitVectorSrc(SDValue LHS,SDValue RHS,bool AllowCommute)3764 static SDValue getSplitVectorSrc(SDValue LHS, SDValue RHS, bool AllowCommute) {
3765   if (LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
3766       RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
3767       LHS.getValueType() != RHS.getValueType() ||
3768       LHS.getOperand(0) != RHS.getOperand(0))
3769     return SDValue();
3770 
3771   SDValue Src = LHS.getOperand(0);
3772   if (Src.getValueSizeInBits() != (LHS.getValueSizeInBits() * 2))
3773     return SDValue();
3774 
3775   unsigned NumElts = LHS.getValueType().getVectorNumElements();
3776   if ((LHS.getConstantOperandAPInt(1) == 0 &&
3777        RHS.getConstantOperandAPInt(1) == NumElts) ||
3778       (AllowCommute && RHS.getConstantOperandAPInt(1) == 0 &&
3779        LHS.getConstantOperandAPInt(1) == NumElts))
3780     return Src;
3781 
3782   return SDValue();
3783 }
3784 
extractSubVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)3785 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
3786                                 const SDLoc &dl, unsigned vectorWidth) {
3787   EVT VT = Vec.getValueType();
3788   EVT ElVT = VT.getVectorElementType();
3789   unsigned Factor = VT.getSizeInBits() / vectorWidth;
3790   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
3791                                   VT.getVectorNumElements() / Factor);
3792 
3793   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
3794   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
3795   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
3796 
3797   // This is the index of the first element of the vectorWidth-bit chunk
3798   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
3799   IdxVal &= ~(ElemsPerChunk - 1);
3800 
3801   // If the input is a buildvector just emit a smaller one.
3802   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
3803     return DAG.getBuildVector(ResultVT, dl,
3804                               Vec->ops().slice(IdxVal, ElemsPerChunk));
3805 
3806   // Check if we're extracting the upper undef of a widening pattern.
3807   if (Vec.getOpcode() == ISD::INSERT_SUBVECTOR && Vec.getOperand(0).isUndef() &&
3808       Vec.getOperand(1).getValueType().getVectorNumElements() <= IdxVal &&
3809       isNullConstant(Vec.getOperand(2)))
3810     return DAG.getUNDEF(ResultVT);
3811 
3812   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
3813   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
3814 }
3815 
3816 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
3817 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
3818 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
3819 /// instructions or a simple subregister reference. Idx is an index in the
3820 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
3821 /// lowering EXTRACT_VECTOR_ELT operations easier.
extract128BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)3822 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
3823                                    SelectionDAG &DAG, const SDLoc &dl) {
3824   assert((Vec.getValueType().is256BitVector() ||
3825           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
3826   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
3827 }
3828 
3829 /// Generate a DAG to grab 256-bits from a 512-bit vector.
extract256BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)3830 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
3831                                    SelectionDAG &DAG, const SDLoc &dl) {
3832   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
3833   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
3834 }
3835 
insertSubVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)3836 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
3837                                SelectionDAG &DAG, const SDLoc &dl,
3838                                unsigned vectorWidth) {
3839   assert((vectorWidth == 128 || vectorWidth == 256) &&
3840          "Unsupported vector width");
3841   // Inserting UNDEF is Result
3842   if (Vec.isUndef())
3843     return Result;
3844   EVT VT = Vec.getValueType();
3845   EVT ElVT = VT.getVectorElementType();
3846   EVT ResultVT = Result.getValueType();
3847 
3848   // Insert the relevant vectorWidth bits.
3849   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
3850   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
3851 
3852   // This is the index of the first element of the vectorWidth-bit chunk
3853   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
3854   IdxVal &= ~(ElemsPerChunk - 1);
3855 
3856   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
3857   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
3858 }
3859 
3860 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
3861 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
3862 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
3863 /// simple superregister reference.  Idx is an index in the 128 bits
3864 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
3865 /// lowering INSERT_VECTOR_ELT operations easier.
insert128BitVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)3866 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
3867                                   SelectionDAG &DAG, const SDLoc &dl) {
3868   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
3869   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
3870 }
3871 
3872 /// Widen a vector to a larger size with the same scalar type, with the new
3873 /// elements either zero or undef.
widenSubVector(MVT VT,SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)3874 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
3875                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
3876                               const SDLoc &dl) {
3877   assert(Vec.getValueSizeInBits().getFixedValue() <= VT.getFixedSizeInBits() &&
3878          Vec.getValueType().getScalarType() == VT.getScalarType() &&
3879          "Unsupported vector widening type");
3880   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
3881                                 : DAG.getUNDEF(VT);
3882   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
3883                      DAG.getIntPtrConstant(0, dl));
3884 }
3885 
3886 /// Widen a vector to a larger size with the same scalar type, with the new
3887 /// elements either zero or undef.
widenSubVector(SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl,unsigned WideSizeInBits)3888 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
3889                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
3890                               const SDLoc &dl, unsigned WideSizeInBits) {
3891   assert(Vec.getValueSizeInBits() <= WideSizeInBits &&
3892          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
3893          "Unsupported vector widening type");
3894   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
3895   MVT SVT = Vec.getSimpleValueType().getScalarType();
3896   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
3897   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
3898 }
3899 
3900 /// Widen a mask vector type to a minimum of v8i1/v16i1 to allow use of KSHIFT
3901 /// and bitcast with integer types.
widenMaskVectorType(MVT VT,const X86Subtarget & Subtarget)3902 static MVT widenMaskVectorType(MVT VT, const X86Subtarget &Subtarget) {
3903   assert(VT.getVectorElementType() == MVT::i1 && "Expected bool vector");
3904   unsigned NumElts = VT.getVectorNumElements();
3905   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
3906     return Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
3907   return VT;
3908 }
3909 
3910 /// Widen a mask vector to a minimum of v8i1/v16i1 to allow use of KSHIFT and
3911 /// bitcast with integer types.
widenMaskVector(SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)3912 static SDValue widenMaskVector(SDValue Vec, bool ZeroNewElements,
3913                                const X86Subtarget &Subtarget, SelectionDAG &DAG,
3914                                const SDLoc &dl) {
3915   MVT VT = widenMaskVectorType(Vec.getSimpleValueType(), Subtarget);
3916   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
3917 }
3918 
3919 // Helper function to collect subvector ops that are concatenated together,
3920 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
3921 // The subvectors in Ops are guaranteed to be the same type.
collectConcatOps(SDNode * N,SmallVectorImpl<SDValue> & Ops,SelectionDAG & DAG)3922 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops,
3923                              SelectionDAG &DAG) {
3924   assert(Ops.empty() && "Expected an empty ops vector");
3925 
3926   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
3927     Ops.append(N->op_begin(), N->op_end());
3928     return true;
3929   }
3930 
3931   if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
3932     SDValue Src = N->getOperand(0);
3933     SDValue Sub = N->getOperand(1);
3934     const APInt &Idx = N->getConstantOperandAPInt(2);
3935     EVT VT = Src.getValueType();
3936     EVT SubVT = Sub.getValueType();
3937 
3938     // TODO - Handle more general insert_subvector chains.
3939     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2)) {
3940       // insert_subvector(undef, x, lo)
3941       if (Idx == 0 && Src.isUndef()) {
3942         Ops.push_back(Sub);
3943         Ops.push_back(DAG.getUNDEF(SubVT));
3944         return true;
3945       }
3946       if (Idx == (VT.getVectorNumElements() / 2)) {
3947         // insert_subvector(insert_subvector(undef, x, lo), y, hi)
3948         if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
3949             Src.getOperand(1).getValueType() == SubVT &&
3950             isNullConstant(Src.getOperand(2))) {
3951           Ops.push_back(Src.getOperand(1));
3952           Ops.push_back(Sub);
3953           return true;
3954         }
3955         // insert_subvector(x, extract_subvector(x, lo), hi)
3956         if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
3957             Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
3958           Ops.append(2, Sub);
3959           return true;
3960         }
3961         // insert_subvector(undef, x, hi)
3962         if (Src.isUndef()) {
3963           Ops.push_back(DAG.getUNDEF(SubVT));
3964           Ops.push_back(Sub);
3965           return true;
3966         }
3967       }
3968     }
3969   }
3970 
3971   return false;
3972 }
3973 
3974 // Helper to check if \p V can be split into subvectors and the upper subvectors
3975 // are all undef. In which case return the lower subvector.
isUpperSubvectorUndef(SDValue V,const SDLoc & DL,SelectionDAG & DAG)3976 static SDValue isUpperSubvectorUndef(SDValue V, const SDLoc &DL,
3977                                      SelectionDAG &DAG) {
3978   SmallVector<SDValue> SubOps;
3979   if (!collectConcatOps(V.getNode(), SubOps, DAG))
3980     return SDValue();
3981 
3982   unsigned NumSubOps = SubOps.size();
3983   unsigned HalfNumSubOps = NumSubOps / 2;
3984   assert((NumSubOps % 2) == 0 && "Unexpected number of subvectors");
3985 
3986   ArrayRef<SDValue> UpperOps(SubOps.begin() + HalfNumSubOps, SubOps.end());
3987   if (any_of(UpperOps, [](SDValue Op) { return !Op.isUndef(); }))
3988     return SDValue();
3989 
3990   EVT HalfVT = V.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
3991   ArrayRef<SDValue> LowerOps(SubOps.begin(), SubOps.begin() + HalfNumSubOps);
3992   return DAG.getNode(ISD::CONCAT_VECTORS, DL, HalfVT, LowerOps);
3993 }
3994 
3995 // Helper to check if we can access all the constituent subvectors without any
3996 // extract ops.
isFreeToSplitVector(SDNode * N,SelectionDAG & DAG)3997 static bool isFreeToSplitVector(SDNode *N, SelectionDAG &DAG) {
3998   SmallVector<SDValue> Ops;
3999   return collectConcatOps(N, Ops, DAG);
4000 }
4001 
splitVector(SDValue Op,SelectionDAG & DAG,const SDLoc & dl)4002 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
4003                                                const SDLoc &dl) {
4004   EVT VT = Op.getValueType();
4005   unsigned NumElems = VT.getVectorNumElements();
4006   unsigned SizeInBits = VT.getSizeInBits();
4007   assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
4008          "Can't split odd sized vector");
4009 
4010   // If this is a splat value (with no-undefs) then use the lower subvector,
4011   // which should be a free extraction.
4012   SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
4013   if (DAG.isSplatValue(Op, /*AllowUndefs*/ false))
4014     return std::make_pair(Lo, Lo);
4015 
4016   SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
4017   return std::make_pair(Lo, Hi);
4018 }
4019 
4020 /// Break an operation into 2 half sized ops and then concatenate the results.
splitVectorOp(SDValue Op,SelectionDAG & DAG)4021 static SDValue splitVectorOp(SDValue Op, SelectionDAG &DAG) {
4022   unsigned NumOps = Op.getNumOperands();
4023   EVT VT = Op.getValueType();
4024   SDLoc dl(Op);
4025 
4026   // Extract the LHS Lo/Hi vectors
4027   SmallVector<SDValue> LoOps(NumOps, SDValue());
4028   SmallVector<SDValue> HiOps(NumOps, SDValue());
4029   for (unsigned I = 0; I != NumOps; ++I) {
4030     SDValue SrcOp = Op.getOperand(I);
4031     if (!SrcOp.getValueType().isVector()) {
4032       LoOps[I] = HiOps[I] = SrcOp;
4033       continue;
4034     }
4035     std::tie(LoOps[I], HiOps[I]) = splitVector(SrcOp, DAG, dl);
4036   }
4037 
4038   EVT LoVT, HiVT;
4039   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
4040   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
4041                      DAG.getNode(Op.getOpcode(), dl, LoVT, LoOps),
4042                      DAG.getNode(Op.getOpcode(), dl, HiVT, HiOps));
4043 }
4044 
4045 /// Break an unary integer operation into 2 half sized ops and then
4046 /// concatenate the result back.
splitVectorIntUnary(SDValue Op,SelectionDAG & DAG)4047 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
4048   // Make sure we only try to split 256/512-bit types to avoid creating
4049   // narrow vectors.
4050   EVT VT = Op.getValueType();
4051   (void)VT;
4052   assert((Op.getOperand(0).getValueType().is256BitVector() ||
4053           Op.getOperand(0).getValueType().is512BitVector()) &&
4054          (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4055   assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
4056              VT.getVectorNumElements() &&
4057          "Unexpected VTs!");
4058   return splitVectorOp(Op, DAG);
4059 }
4060 
4061 /// Break a binary integer operation into 2 half sized ops and then
4062 /// concatenate the result back.
splitVectorIntBinary(SDValue Op,SelectionDAG & DAG)4063 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
4064   // Assert that all the types match.
4065   EVT VT = Op.getValueType();
4066   (void)VT;
4067   assert(Op.getOperand(0).getValueType() == VT &&
4068          Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
4069   assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
4070   return splitVectorOp(Op, DAG);
4071 }
4072 
4073 // Helper for splitting operands of an operation to legal target size and
4074 // apply a function on each part.
4075 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
4076 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
4077 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
4078 // The argument Builder is a function that will be applied on each split part:
4079 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
4080 template <typename F>
SplitOpsAndApply(SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,F Builder,bool CheckBWI=true)4081 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
4082                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
4083                          F Builder, bool CheckBWI = true) {
4084   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
4085   unsigned NumSubs = 1;
4086   if ((CheckBWI && Subtarget.useBWIRegs()) ||
4087       (!CheckBWI && Subtarget.useAVX512Regs())) {
4088     if (VT.getSizeInBits() > 512) {
4089       NumSubs = VT.getSizeInBits() / 512;
4090       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
4091     }
4092   } else if (Subtarget.hasAVX2()) {
4093     if (VT.getSizeInBits() > 256) {
4094       NumSubs = VT.getSizeInBits() / 256;
4095       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
4096     }
4097   } else {
4098     if (VT.getSizeInBits() > 128) {
4099       NumSubs = VT.getSizeInBits() / 128;
4100       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
4101     }
4102   }
4103 
4104   if (NumSubs == 1)
4105     return Builder(DAG, DL, Ops);
4106 
4107   SmallVector<SDValue, 4> Subs;
4108   for (unsigned i = 0; i != NumSubs; ++i) {
4109     SmallVector<SDValue, 2> SubOps;
4110     for (SDValue Op : Ops) {
4111       EVT OpVT = Op.getValueType();
4112       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
4113       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
4114       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
4115     }
4116     Subs.push_back(Builder(DAG, DL, SubOps));
4117   }
4118   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
4119 }
4120 
4121 // Helper function that extends a non-512-bit vector op to 512-bits on non-VLX
4122 // targets.
getAVX512Node(unsigned Opcode,const SDLoc & DL,MVT VT,ArrayRef<SDValue> Ops,SelectionDAG & DAG,const X86Subtarget & Subtarget)4123 static SDValue getAVX512Node(unsigned Opcode, const SDLoc &DL, MVT VT,
4124                              ArrayRef<SDValue> Ops, SelectionDAG &DAG,
4125                              const X86Subtarget &Subtarget) {
4126   assert(Subtarget.hasAVX512() && "AVX512 target expected");
4127   MVT SVT = VT.getScalarType();
4128 
4129   // If we have a 32/64 splatted constant, splat it to DstTy to
4130   // encourage a foldable broadcast'd operand.
4131   auto MakeBroadcastOp = [&](SDValue Op, MVT OpVT, MVT DstVT) {
4132     unsigned OpEltSizeInBits = OpVT.getScalarSizeInBits();
4133     // AVX512 broadcasts 32/64-bit operands.
4134     // TODO: Support float once getAVX512Node is used by fp-ops.
4135     if (!OpVT.isInteger() || OpEltSizeInBits < 32 ||
4136         !DAG.getTargetLoweringInfo().isTypeLegal(SVT))
4137       return SDValue();
4138     // If we're not widening, don't bother if we're not bitcasting.
4139     if (OpVT == DstVT && Op.getOpcode() != ISD::BITCAST)
4140       return SDValue();
4141     if (auto *BV = dyn_cast<BuildVectorSDNode>(peekThroughBitcasts(Op))) {
4142       APInt SplatValue, SplatUndef;
4143       unsigned SplatBitSize;
4144       bool HasAnyUndefs;
4145       if (BV->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
4146                               HasAnyUndefs, OpEltSizeInBits) &&
4147           !HasAnyUndefs && SplatValue.getBitWidth() == OpEltSizeInBits)
4148         return DAG.getConstant(SplatValue, DL, DstVT);
4149     }
4150     return SDValue();
4151   };
4152 
4153   bool Widen = !(Subtarget.hasVLX() || VT.is512BitVector());
4154 
4155   MVT DstVT = VT;
4156   if (Widen)
4157     DstVT = MVT::getVectorVT(SVT, 512 / SVT.getSizeInBits());
4158 
4159   // Canonicalize src operands.
4160   SmallVector<SDValue> SrcOps(Ops.begin(), Ops.end());
4161   for (SDValue &Op : SrcOps) {
4162     MVT OpVT = Op.getSimpleValueType();
4163     // Just pass through scalar operands.
4164     if (!OpVT.isVector())
4165       continue;
4166     assert(OpVT == VT && "Vector type mismatch");
4167 
4168     if (SDValue BroadcastOp = MakeBroadcastOp(Op, OpVT, DstVT)) {
4169       Op = BroadcastOp;
4170       continue;
4171     }
4172 
4173     // Just widen the subvector by inserting into an undef wide vector.
4174     if (Widen)
4175       Op = widenSubVector(Op, false, Subtarget, DAG, DL, 512);
4176   }
4177 
4178   SDValue Res = DAG.getNode(Opcode, DL, DstVT, SrcOps);
4179 
4180   // Perform the 512-bit op then extract the bottom subvector.
4181   if (Widen)
4182     Res = extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
4183   return Res;
4184 }
4185 
4186 /// Insert i1-subvector to i1-vector.
insert1BitVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)4187 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
4188                                 const X86Subtarget &Subtarget) {
4189 
4190   SDLoc dl(Op);
4191   SDValue Vec = Op.getOperand(0);
4192   SDValue SubVec = Op.getOperand(1);
4193   SDValue Idx = Op.getOperand(2);
4194   unsigned IdxVal = Op.getConstantOperandVal(2);
4195 
4196   // Inserting undef is a nop. We can just return the original vector.
4197   if (SubVec.isUndef())
4198     return Vec;
4199 
4200   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4201     return Op;
4202 
4203   MVT OpVT = Op.getSimpleValueType();
4204   unsigned NumElems = OpVT.getVectorNumElements();
4205   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4206 
4207   // Extend to natively supported kshift.
4208   MVT WideOpVT = widenMaskVectorType(OpVT, Subtarget);
4209 
4210   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
4211   // if necessary.
4212   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
4213     // May need to promote to a legal type.
4214     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4215                      DAG.getConstant(0, dl, WideOpVT),
4216                      SubVec, Idx);
4217     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4218   }
4219 
4220   MVT SubVecVT = SubVec.getSimpleValueType();
4221   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4222   assert(IdxVal + SubVecNumElems <= NumElems &&
4223          IdxVal % SubVecVT.getSizeInBits() == 0 &&
4224          "Unexpected index value in INSERT_SUBVECTOR");
4225 
4226   SDValue Undef = DAG.getUNDEF(WideOpVT);
4227 
4228   if (IdxVal == 0) {
4229     // Zero lower bits of the Vec
4230     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
4231     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
4232                       ZeroIdx);
4233     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4234     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4235     // Merge them together, SubVec should be zero extended.
4236     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4237                          DAG.getConstant(0, dl, WideOpVT),
4238                          SubVec, ZeroIdx);
4239     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4240     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4241   }
4242 
4243   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4244                        Undef, SubVec, ZeroIdx);
4245 
4246   if (Vec.isUndef()) {
4247     assert(IdxVal != 0 && "Unexpected index");
4248     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4249                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4250     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4251   }
4252 
4253   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4254     assert(IdxVal != 0 && "Unexpected index");
4255     // If upper elements of Vec are known undef, then just shift into place.
4256     if (llvm::all_of(Vec->ops().slice(IdxVal + SubVecNumElems),
4257                      [](SDValue V) { return V.isUndef(); })) {
4258       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4259                            DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4260     } else {
4261       NumElems = WideOpVT.getVectorNumElements();
4262       unsigned ShiftLeft = NumElems - SubVecNumElems;
4263       unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4264       SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4265                            DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4266       if (ShiftRight != 0)
4267         SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4268                              DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4269     }
4270     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4271   }
4272 
4273   // Simple case when we put subvector in the upper part
4274   if (IdxVal + SubVecNumElems == NumElems) {
4275     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4276                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
4277     if (SubVecNumElems * 2 == NumElems) {
4278       // Special case, use legal zero extending insert_subvector. This allows
4279       // isel to optimize when bits are known zero.
4280       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
4281       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4282                         DAG.getConstant(0, dl, WideOpVT),
4283                         Vec, ZeroIdx);
4284     } else {
4285       // Otherwise use explicit shifts to zero the bits.
4286       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
4287                         Undef, Vec, ZeroIdx);
4288       NumElems = WideOpVT.getVectorNumElements();
4289       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
4290       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
4291       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
4292     }
4293     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4294     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4295   }
4296 
4297   // Inserting into the middle is more complicated.
4298 
4299   NumElems = WideOpVT.getVectorNumElements();
4300 
4301   // Widen the vector if needed.
4302   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
4303 
4304   unsigned ShiftLeft = NumElems - SubVecNumElems;
4305   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4306 
4307   // Do an optimization for the most frequently used types.
4308   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
4309     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
4310     Mask0.flipAllBits();
4311     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
4312     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
4313     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
4314     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4315                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4316     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4317                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4318     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
4319 
4320     // Reduce to original width if needed.
4321     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
4322   }
4323 
4324   // Clear the upper bits of the subvector and move it to its insert position.
4325   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
4326                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
4327   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
4328                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
4329 
4330   // Isolate the bits below the insertion point.
4331   unsigned LowShift = NumElems - IdxVal;
4332   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
4333                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
4334   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
4335                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
4336 
4337   // Isolate the bits after the last inserted bit.
4338   unsigned HighShift = IdxVal + SubVecNumElems;
4339   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
4340                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
4341   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
4342                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
4343 
4344   // Now OR all 3 pieces together.
4345   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
4346   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
4347 
4348   // Reduce to original width if needed.
4349   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
4350 }
4351 
concatSubVectors(SDValue V1,SDValue V2,SelectionDAG & DAG,const SDLoc & dl)4352 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
4353                                 const SDLoc &dl) {
4354   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
4355   EVT SubVT = V1.getValueType();
4356   EVT SubSVT = SubVT.getScalarType();
4357   unsigned SubNumElts = SubVT.getVectorNumElements();
4358   unsigned SubVectorWidth = SubVT.getSizeInBits();
4359   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
4360   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
4361   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
4362 }
4363 
4364 /// Returns a vector of specified type with all bits set.
4365 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
4366 /// Then bitcast to their original type, ensuring they get CSE'd.
getOnesVector(EVT VT,SelectionDAG & DAG,const SDLoc & dl)4367 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4368   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
4369          "Expected a 128/256/512-bit vector type");
4370 
4371   APInt Ones = APInt::getAllOnes(32);
4372   unsigned NumElts = VT.getSizeInBits() / 32;
4373   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
4374   return DAG.getBitcast(VT, Vec);
4375 }
4376 
getEXTEND_VECTOR_INREG(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue In,SelectionDAG & DAG)4377 static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
4378                                       SDValue In, SelectionDAG &DAG) {
4379   EVT InVT = In.getValueType();
4380   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
4381   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
4382           ISD::ZERO_EXTEND == Opcode) &&
4383          "Unknown extension opcode");
4384 
4385   // For 256-bit vectors, we only need the lower (128-bit) input half.
4386   // For 512-bit vectors, we only need the lower input half or quarter.
4387   if (InVT.getSizeInBits() > 128) {
4388     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
4389            "Expected VTs to be the same size!");
4390     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
4391     In = extractSubVector(In, 0, DAG, DL,
4392                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
4393     InVT = In.getValueType();
4394   }
4395 
4396   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
4397     Opcode = DAG.getOpcode_EXTEND_VECTOR_INREG(Opcode);
4398 
4399   return DAG.getNode(Opcode, DL, VT, In);
4400 }
4401 
4402 // Create OR(AND(LHS,MASK),AND(RHS,~MASK)) bit select pattern
getBitSelect(const SDLoc & DL,MVT VT,SDValue LHS,SDValue RHS,SDValue Mask,SelectionDAG & DAG)4403 static SDValue getBitSelect(const SDLoc &DL, MVT VT, SDValue LHS, SDValue RHS,
4404                             SDValue Mask, SelectionDAG &DAG) {
4405   LHS = DAG.getNode(ISD::AND, DL, VT, LHS, Mask);
4406   RHS = DAG.getNode(X86ISD::ANDNP, DL, VT, Mask, RHS);
4407   return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
4408 }
4409 
createUnpackShuffleMask(EVT VT,SmallVectorImpl<int> & Mask,bool Lo,bool Unary)4410 void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
4411                                    bool Lo, bool Unary) {
4412   assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
4413          "Illegal vector type to unpack");
4414   assert(Mask.empty() && "Expected an empty shuffle mask vector");
4415   int NumElts = VT.getVectorNumElements();
4416   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
4417   for (int i = 0; i < NumElts; ++i) {
4418     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
4419     int Pos = (i % NumEltsInLane) / 2 + LaneStart;
4420     Pos += (Unary ? 0 : NumElts * (i % 2));
4421     Pos += (Lo ? 0 : NumEltsInLane / 2);
4422     Mask.push_back(Pos);
4423   }
4424 }
4425 
4426 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
4427 /// imposed by AVX and specific to the unary pattern. Example:
4428 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
4429 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
createSplat2ShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Lo)4430 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
4431                                    bool Lo) {
4432   assert(Mask.empty() && "Expected an empty shuffle mask vector");
4433   int NumElts = VT.getVectorNumElements();
4434   for (int i = 0; i < NumElts; ++i) {
4435     int Pos = i / 2;
4436     Pos += (Lo ? 0 : NumElts / 2);
4437     Mask.push_back(Pos);
4438   }
4439 }
4440 
4441 // Attempt to constant fold, else just create a VECTOR_SHUFFLE.
getVectorShuffle(SelectionDAG & DAG,EVT VT,const SDLoc & dl,SDValue V1,SDValue V2,ArrayRef<int> Mask)4442 static SDValue getVectorShuffle(SelectionDAG &DAG, EVT VT, const SDLoc &dl,
4443                                 SDValue V1, SDValue V2, ArrayRef<int> Mask) {
4444   if ((ISD::isBuildVectorOfConstantSDNodes(V1.getNode()) || V1.isUndef()) &&
4445       (ISD::isBuildVectorOfConstantSDNodes(V2.getNode()) || V2.isUndef())) {
4446     SmallVector<SDValue> Ops(Mask.size(), DAG.getUNDEF(VT.getScalarType()));
4447     for (int I = 0, NumElts = Mask.size(); I != NumElts; ++I) {
4448       int M = Mask[I];
4449       if (M < 0)
4450         continue;
4451       SDValue V = (M < NumElts) ? V1 : V2;
4452       if (V.isUndef())
4453         continue;
4454       Ops[I] = V.getOperand(M % NumElts);
4455     }
4456     return DAG.getBuildVector(VT, dl, Ops);
4457   }
4458 
4459   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
4460 }
4461 
4462 /// Returns a vector_shuffle node for an unpackl operation.
getUnpackl(SelectionDAG & DAG,const SDLoc & dl,EVT VT,SDValue V1,SDValue V2)4463 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
4464                           SDValue V1, SDValue V2) {
4465   SmallVector<int, 8> Mask;
4466   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
4467   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
4468 }
4469 
4470 /// Returns a vector_shuffle node for an unpackh operation.
getUnpackh(SelectionDAG & DAG,const SDLoc & dl,EVT VT,SDValue V1,SDValue V2)4471 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
4472                           SDValue V1, SDValue V2) {
4473   SmallVector<int, 8> Mask;
4474   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
4475   return getVectorShuffle(DAG, VT, dl, V1, V2, Mask);
4476 }
4477 
4478 /// Returns a node that packs the LHS + RHS nodes together at half width.
4479 /// May return X86ISD::PACKSS/PACKUS, packing the top/bottom half.
4480 /// TODO: Add subvector splitting if/when we have a need for it.
getPack(SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & dl,MVT VT,SDValue LHS,SDValue RHS,bool PackHiHalf=false)4481 static SDValue getPack(SelectionDAG &DAG, const X86Subtarget &Subtarget,
4482                        const SDLoc &dl, MVT VT, SDValue LHS, SDValue RHS,
4483                        bool PackHiHalf = false) {
4484   MVT OpVT = LHS.getSimpleValueType();
4485   unsigned EltSizeInBits = VT.getScalarSizeInBits();
4486   bool UsePackUS = Subtarget.hasSSE41() || EltSizeInBits == 8;
4487   assert(OpVT == RHS.getSimpleValueType() &&
4488          VT.getSizeInBits() == OpVT.getSizeInBits() &&
4489          (EltSizeInBits * 2) == OpVT.getScalarSizeInBits() &&
4490          "Unexpected PACK operand types");
4491   assert((EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) &&
4492          "Unexpected PACK result type");
4493 
4494   // Rely on vector shuffles for vXi64 -> vXi32 packing.
4495   if (EltSizeInBits == 32) {
4496     SmallVector<int> PackMask;
4497     int Offset = PackHiHalf ? 1 : 0;
4498     int NumElts = VT.getVectorNumElements();
4499     for (int I = 0; I != NumElts; I += 4) {
4500       PackMask.push_back(I + Offset);
4501       PackMask.push_back(I + Offset + 2);
4502       PackMask.push_back(I + Offset + NumElts);
4503       PackMask.push_back(I + Offset + NumElts + 2);
4504     }
4505     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, LHS),
4506                                 DAG.getBitcast(VT, RHS), PackMask);
4507   }
4508 
4509   // See if we already have sufficient leading bits for PACKSS/PACKUS.
4510   if (!PackHiHalf) {
4511     if (UsePackUS &&
4512         DAG.computeKnownBits(LHS).countMaxActiveBits() <= EltSizeInBits &&
4513         DAG.computeKnownBits(RHS).countMaxActiveBits() <= EltSizeInBits)
4514       return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
4515 
4516     if (DAG.ComputeMaxSignificantBits(LHS) <= EltSizeInBits &&
4517         DAG.ComputeMaxSignificantBits(RHS) <= EltSizeInBits)
4518       return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
4519   }
4520 
4521   // Fallback to sign/zero extending the requested half and pack.
4522   SDValue Amt = DAG.getTargetConstant(EltSizeInBits, dl, MVT::i8);
4523   if (UsePackUS) {
4524     if (PackHiHalf) {
4525       LHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, LHS, Amt);
4526       RHS = DAG.getNode(X86ISD::VSRLI, dl, OpVT, RHS, Amt);
4527     } else {
4528       SDValue Mask = DAG.getConstant((1ULL << EltSizeInBits) - 1, dl, OpVT);
4529       LHS = DAG.getNode(ISD::AND, dl, OpVT, LHS, Mask);
4530       RHS = DAG.getNode(ISD::AND, dl, OpVT, RHS, Mask);
4531     };
4532     return DAG.getNode(X86ISD::PACKUS, dl, VT, LHS, RHS);
4533   };
4534 
4535   if (!PackHiHalf) {
4536     LHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, LHS, Amt);
4537     RHS = DAG.getNode(X86ISD::VSHLI, dl, OpVT, RHS, Amt);
4538   }
4539   LHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, LHS, Amt);
4540   RHS = DAG.getNode(X86ISD::VSRAI, dl, OpVT, RHS, Amt);
4541   return DAG.getNode(X86ISD::PACKSS, dl, VT, LHS, RHS);
4542 }
4543 
4544 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4545 /// This produces a shuffle where the low element of V2 is swizzled into the
4546 /// zero/undef vector, landing at element Idx.
4547 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
getShuffleVectorZeroOrUndef(SDValue V2,int Idx,bool IsZero,const X86Subtarget & Subtarget,SelectionDAG & DAG)4548 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
4549                                            bool IsZero,
4550                                            const X86Subtarget &Subtarget,
4551                                            SelectionDAG &DAG) {
4552   MVT VT = V2.getSimpleValueType();
4553   SDValue V1 = IsZero
4554     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4555   int NumElems = VT.getVectorNumElements();
4556   SmallVector<int, 16> MaskVec(NumElems);
4557   for (int i = 0; i != NumElems; ++i)
4558     // If this is the insertion idx, put the low elt of V2 here.
4559     MaskVec[i] = (i == Idx) ? NumElems : i;
4560   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
4561 }
4562 
getTargetConstantPoolFromBasePtr(SDValue Ptr)4563 static ConstantPoolSDNode *getTargetConstantPoolFromBasePtr(SDValue Ptr) {
4564   if (Ptr.getOpcode() == X86ISD::Wrapper ||
4565       Ptr.getOpcode() == X86ISD::WrapperRIP)
4566     Ptr = Ptr.getOperand(0);
4567   return dyn_cast<ConstantPoolSDNode>(Ptr);
4568 }
4569 
getTargetConstantFromBasePtr(SDValue Ptr)4570 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
4571   ConstantPoolSDNode *CNode = getTargetConstantPoolFromBasePtr(Ptr);
4572   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
4573     return nullptr;
4574   return CNode->getConstVal();
4575 }
4576 
getTargetConstantFromNode(LoadSDNode * Load)4577 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
4578   if (!Load || !ISD::isNormalLoad(Load))
4579     return nullptr;
4580   return getTargetConstantFromBasePtr(Load->getBasePtr());
4581 }
4582 
getTargetConstantFromNode(SDValue Op)4583 static const Constant *getTargetConstantFromNode(SDValue Op) {
4584   Op = peekThroughBitcasts(Op);
4585   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
4586 }
4587 
4588 const Constant *
getTargetConstantFromLoad(LoadSDNode * LD) const4589 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
4590   assert(LD && "Unexpected null LoadSDNode");
4591   return getTargetConstantFromNode(LD);
4592 }
4593 
4594 // Extract raw constant bits from constant pools.
getTargetConstantBitsFromNode(SDValue Op,unsigned EltSizeInBits,APInt & UndefElts,SmallVectorImpl<APInt> & EltBits,bool AllowWholeUndefs=true,bool AllowPartialUndefs=true)4595 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
4596                                           APInt &UndefElts,
4597                                           SmallVectorImpl<APInt> &EltBits,
4598                                           bool AllowWholeUndefs = true,
4599                                           bool AllowPartialUndefs = true) {
4600   assert(EltBits.empty() && "Expected an empty EltBits vector");
4601 
4602   Op = peekThroughBitcasts(Op);
4603 
4604   EVT VT = Op.getValueType();
4605   unsigned SizeInBits = VT.getSizeInBits();
4606   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
4607   unsigned NumElts = SizeInBits / EltSizeInBits;
4608 
4609   // Bitcast a source array of element bits to the target size.
4610   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
4611     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
4612     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
4613     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
4614            "Constant bit sizes don't match");
4615 
4616     // Don't split if we don't allow undef bits.
4617     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
4618     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
4619       return false;
4620 
4621     // If we're already the right size, don't bother bitcasting.
4622     if (NumSrcElts == NumElts) {
4623       UndefElts = UndefSrcElts;
4624       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
4625       return true;
4626     }
4627 
4628     // Extract all the undef/constant element data and pack into single bitsets.
4629     APInt UndefBits(SizeInBits, 0);
4630     APInt MaskBits(SizeInBits, 0);
4631 
4632     for (unsigned i = 0; i != NumSrcElts; ++i) {
4633       unsigned BitOffset = i * SrcEltSizeInBits;
4634       if (UndefSrcElts[i])
4635         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
4636       MaskBits.insertBits(SrcEltBits[i], BitOffset);
4637     }
4638 
4639     // Split the undef/constant single bitset data into the target elements.
4640     UndefElts = APInt(NumElts, 0);
4641     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
4642 
4643     for (unsigned i = 0; i != NumElts; ++i) {
4644       unsigned BitOffset = i * EltSizeInBits;
4645       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
4646 
4647       // Only treat an element as UNDEF if all bits are UNDEF.
4648       if (UndefEltBits.isAllOnes()) {
4649         if (!AllowWholeUndefs)
4650           return false;
4651         UndefElts.setBit(i);
4652         continue;
4653       }
4654 
4655       // If only some bits are UNDEF then treat them as zero (or bail if not
4656       // supported).
4657       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
4658         return false;
4659 
4660       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
4661     }
4662     return true;
4663   };
4664 
4665   // Collect constant bits and insert into mask/undef bit masks.
4666   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
4667                                 unsigned UndefBitIndex) {
4668     if (!Cst)
4669       return false;
4670     if (isa<UndefValue>(Cst)) {
4671       Undefs.setBit(UndefBitIndex);
4672       return true;
4673     }
4674     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4675       Mask = CInt->getValue();
4676       return true;
4677     }
4678     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4679       Mask = CFP->getValueAPF().bitcastToAPInt();
4680       return true;
4681     }
4682     if (auto *CDS = dyn_cast<ConstantDataSequential>(Cst)) {
4683       Type *Ty = CDS->getType();
4684       Mask = APInt::getZero(Ty->getPrimitiveSizeInBits());
4685       Type *EltTy = CDS->getElementType();
4686       bool IsInteger = EltTy->isIntegerTy();
4687       bool IsFP =
4688           EltTy->isHalfTy() || EltTy->isFloatTy() || EltTy->isDoubleTy();
4689       if (!IsInteger && !IsFP)
4690         return false;
4691       unsigned EltBits = EltTy->getPrimitiveSizeInBits();
4692       for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
4693         if (IsInteger)
4694           Mask.insertBits(CDS->getElementAsAPInt(I), I * EltBits);
4695         else
4696           Mask.insertBits(CDS->getElementAsAPFloat(I).bitcastToAPInt(),
4697                           I * EltBits);
4698       return true;
4699     }
4700     return false;
4701   };
4702 
4703   // Handle UNDEFs.
4704   if (Op.isUndef()) {
4705     APInt UndefSrcElts = APInt::getAllOnes(NumElts);
4706     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
4707     return CastBitData(UndefSrcElts, SrcEltBits);
4708   }
4709 
4710   // Extract scalar constant bits.
4711   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
4712     APInt UndefSrcElts = APInt::getZero(1);
4713     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
4714     return CastBitData(UndefSrcElts, SrcEltBits);
4715   }
4716   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
4717     APInt UndefSrcElts = APInt::getZero(1);
4718     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
4719     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
4720     return CastBitData(UndefSrcElts, SrcEltBits);
4721   }
4722 
4723   // Extract constant bits from build vector.
4724   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op)) {
4725     BitVector Undefs;
4726     SmallVector<APInt> SrcEltBits;
4727     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
4728     if (BV->getConstantRawBits(true, SrcEltSizeInBits, SrcEltBits, Undefs)) {
4729       APInt UndefSrcElts = APInt::getZero(SrcEltBits.size());
4730       for (unsigned I = 0, E = SrcEltBits.size(); I != E; ++I)
4731         if (Undefs[I])
4732           UndefSrcElts.setBit(I);
4733       return CastBitData(UndefSrcElts, SrcEltBits);
4734     }
4735   }
4736 
4737   // Extract constant bits from constant pool vector.
4738   if (auto *Cst = getTargetConstantFromNode(Op)) {
4739     Type *CstTy = Cst->getType();
4740     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
4741     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
4742       return false;
4743 
4744     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
4745     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
4746     if ((SizeInBits % SrcEltSizeInBits) != 0)
4747       return false;
4748 
4749     APInt UndefSrcElts(NumSrcElts, 0);
4750     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
4751     for (unsigned i = 0; i != NumSrcElts; ++i)
4752       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
4753                                UndefSrcElts, i))
4754         return false;
4755 
4756     return CastBitData(UndefSrcElts, SrcEltBits);
4757   }
4758 
4759   // Extract constant bits from a broadcasted constant pool scalar.
4760   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
4761       EltSizeInBits <= VT.getScalarSizeInBits()) {
4762     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
4763     if (MemIntr->getMemoryVT().getStoreSizeInBits() != VT.getScalarSizeInBits())
4764       return false;
4765 
4766     SDValue Ptr = MemIntr->getBasePtr();
4767     if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
4768       unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
4769       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
4770 
4771       APInt UndefSrcElts(NumSrcElts, 0);
4772       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
4773       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
4774         if (UndefSrcElts[0])
4775           UndefSrcElts.setBits(0, NumSrcElts);
4776         if (SrcEltBits[0].getBitWidth() != SrcEltSizeInBits)
4777           SrcEltBits[0] = SrcEltBits[0].trunc(SrcEltSizeInBits);
4778         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
4779         return CastBitData(UndefSrcElts, SrcEltBits);
4780       }
4781     }
4782   }
4783 
4784   // Extract constant bits from a subvector broadcast.
4785   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
4786     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
4787     SDValue Ptr = MemIntr->getBasePtr();
4788     // The source constant may be larger than the subvector broadcast,
4789     // ensure we extract the correct subvector constants.
4790     if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
4791       Type *CstTy = Cst->getType();
4792       unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
4793       unsigned SubVecSizeInBits = MemIntr->getMemoryVT().getStoreSizeInBits();
4794       if (!CstTy->isVectorTy() || (CstSizeInBits % SubVecSizeInBits) != 0 ||
4795           (SizeInBits % SubVecSizeInBits) != 0)
4796         return false;
4797       unsigned CstEltSizeInBits = CstTy->getScalarSizeInBits();
4798       unsigned NumSubElts = SubVecSizeInBits / CstEltSizeInBits;
4799       unsigned NumSubVecs = SizeInBits / SubVecSizeInBits;
4800       APInt UndefSubElts(NumSubElts, 0);
4801       SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
4802                                         APInt(CstEltSizeInBits, 0));
4803       for (unsigned i = 0; i != NumSubElts; ++i) {
4804         if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
4805                                  UndefSubElts, i))
4806           return false;
4807         for (unsigned j = 1; j != NumSubVecs; ++j)
4808           SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
4809       }
4810       UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
4811                                      UndefSubElts);
4812       return CastBitData(UndefSubElts, SubEltBits);
4813     }
4814   }
4815 
4816   // Extract a rematerialized scalar constant insertion.
4817   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
4818       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
4819       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
4820     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
4821     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
4822 
4823     APInt UndefSrcElts(NumSrcElts, 0);
4824     SmallVector<APInt, 64> SrcEltBits;
4825     const APInt &C = Op.getOperand(0).getConstantOperandAPInt(0);
4826     SrcEltBits.push_back(C.zextOrTrunc(SrcEltSizeInBits));
4827     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
4828     return CastBitData(UndefSrcElts, SrcEltBits);
4829   }
4830 
4831   // Insert constant bits from a base and sub vector sources.
4832   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
4833     // If bitcasts to larger elements we might lose track of undefs - don't
4834     // allow any to be safe.
4835     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
4836     bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
4837 
4838     APInt UndefSrcElts, UndefSubElts;
4839     SmallVector<APInt, 32> EltSrcBits, EltSubBits;
4840     if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
4841                                       UndefSubElts, EltSubBits,
4842                                       AllowWholeUndefs && AllowUndefs,
4843                                       AllowPartialUndefs && AllowUndefs) &&
4844         getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
4845                                       UndefSrcElts, EltSrcBits,
4846                                       AllowWholeUndefs && AllowUndefs,
4847                                       AllowPartialUndefs && AllowUndefs)) {
4848       unsigned BaseIdx = Op.getConstantOperandVal(2);
4849       UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
4850       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
4851         EltSrcBits[BaseIdx + i] = EltSubBits[i];
4852       return CastBitData(UndefSrcElts, EltSrcBits);
4853     }
4854   }
4855 
4856   // Extract constant bits from a subvector's source.
4857   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4858     // TODO - support extract_subvector through bitcasts.
4859     if (EltSizeInBits != VT.getScalarSizeInBits())
4860       return false;
4861 
4862     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
4863                                       UndefElts, EltBits, AllowWholeUndefs,
4864                                       AllowPartialUndefs)) {
4865       EVT SrcVT = Op.getOperand(0).getValueType();
4866       unsigned NumSrcElts = SrcVT.getVectorNumElements();
4867       unsigned NumSubElts = VT.getVectorNumElements();
4868       unsigned BaseIdx = Op.getConstantOperandVal(1);
4869       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
4870       if ((BaseIdx + NumSubElts) != NumSrcElts)
4871         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
4872       if (BaseIdx != 0)
4873         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
4874       return true;
4875     }
4876   }
4877 
4878   // Extract constant bits from shuffle node sources.
4879   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
4880     // TODO - support shuffle through bitcasts.
4881     if (EltSizeInBits != VT.getScalarSizeInBits())
4882       return false;
4883 
4884     ArrayRef<int> Mask = SVN->getMask();
4885     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
4886         llvm::any_of(Mask, [](int M) { return M < 0; }))
4887       return false;
4888 
4889     APInt UndefElts0, UndefElts1;
4890     SmallVector<APInt, 32> EltBits0, EltBits1;
4891     if (isAnyInRange(Mask, 0, NumElts) &&
4892         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
4893                                        UndefElts0, EltBits0, AllowWholeUndefs,
4894                                        AllowPartialUndefs))
4895       return false;
4896     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
4897         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
4898                                        UndefElts1, EltBits1, AllowWholeUndefs,
4899                                        AllowPartialUndefs))
4900       return false;
4901 
4902     UndefElts = APInt::getZero(NumElts);
4903     for (int i = 0; i != (int)NumElts; ++i) {
4904       int M = Mask[i];
4905       if (M < 0) {
4906         UndefElts.setBit(i);
4907         EltBits.push_back(APInt::getZero(EltSizeInBits));
4908       } else if (M < (int)NumElts) {
4909         if (UndefElts0[M])
4910           UndefElts.setBit(i);
4911         EltBits.push_back(EltBits0[M]);
4912       } else {
4913         if (UndefElts1[M - NumElts])
4914           UndefElts.setBit(i);
4915         EltBits.push_back(EltBits1[M - NumElts]);
4916       }
4917     }
4918     return true;
4919   }
4920 
4921   return false;
4922 }
4923 
4924 namespace llvm {
4925 namespace X86 {
isConstantSplat(SDValue Op,APInt & SplatVal,bool AllowPartialUndefs)4926 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
4927   APInt UndefElts;
4928   SmallVector<APInt, 16> EltBits;
4929   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
4930                                     UndefElts, EltBits, true,
4931                                     AllowPartialUndefs)) {
4932     int SplatIndex = -1;
4933     for (int i = 0, e = EltBits.size(); i != e; ++i) {
4934       if (UndefElts[i])
4935         continue;
4936       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
4937         SplatIndex = -1;
4938         break;
4939       }
4940       SplatIndex = i;
4941     }
4942     if (0 <= SplatIndex) {
4943       SplatVal = EltBits[SplatIndex];
4944       return true;
4945     }
4946   }
4947 
4948   return false;
4949 }
4950 } // namespace X86
4951 } // namespace llvm
4952 
getTargetShuffleMaskIndices(SDValue MaskNode,unsigned MaskEltSizeInBits,SmallVectorImpl<uint64_t> & RawMask,APInt & UndefElts)4953 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
4954                                         unsigned MaskEltSizeInBits,
4955                                         SmallVectorImpl<uint64_t> &RawMask,
4956                                         APInt &UndefElts) {
4957   // Extract the raw target constant bits.
4958   SmallVector<APInt, 64> EltBits;
4959   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
4960                                      EltBits, /* AllowWholeUndefs */ true,
4961                                      /* AllowPartialUndefs */ false))
4962     return false;
4963 
4964   // Insert the extracted elements into the mask.
4965   for (const APInt &Elt : EltBits)
4966     RawMask.push_back(Elt.getZExtValue());
4967 
4968   return true;
4969 }
4970 
4971 // Match not(xor X, -1) -> X.
4972 // Match not(pcmpgt(C, X)) -> pcmpgt(X, C - 1).
4973 // Match not(extract_subvector(xor X, -1)) -> extract_subvector(X).
4974 // Match not(concat_vectors(xor X, -1, xor Y, -1)) -> concat_vectors(X, Y).
IsNOT(SDValue V,SelectionDAG & DAG)4975 static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
4976   V = peekThroughBitcasts(V);
4977   if (V.getOpcode() == ISD::XOR &&
4978       (ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()) ||
4979        isAllOnesConstant(V.getOperand(1))))
4980     return V.getOperand(0);
4981   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4982       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
4983     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
4984       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
4985       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
4986                          Not, V.getOperand(1));
4987     }
4988   }
4989   if (V.getOpcode() == X86ISD::PCMPGT &&
4990       !ISD::isBuildVectorAllZeros(V.getOperand(0).getNode()) &&
4991       !ISD::isBuildVectorAllOnes(V.getOperand(0).getNode()) &&
4992       V.getOperand(0).hasOneUse()) {
4993     APInt UndefElts;
4994     SmallVector<APInt> EltBits;
4995     if (getTargetConstantBitsFromNode(V.getOperand(0),
4996                                       V.getScalarValueSizeInBits(), UndefElts,
4997                                       EltBits)) {
4998       // Don't fold min_signed_value -> (min_signed_value - 1)
4999       bool MinSigned = false;
5000       for (APInt &Elt : EltBits) {
5001         MinSigned |= Elt.isMinSignedValue();
5002         Elt -= 1;
5003       }
5004       if (!MinSigned) {
5005         SDLoc DL(V);
5006         MVT VT = V.getSimpleValueType();
5007         return DAG.getNode(X86ISD::PCMPGT, DL, VT, V.getOperand(1),
5008                            getConstVector(EltBits, UndefElts, VT, DAG, DL));
5009       }
5010     }
5011   }
5012   SmallVector<SDValue, 2> CatOps;
5013   if (collectConcatOps(V.getNode(), CatOps, DAG)) {
5014     for (SDValue &CatOp : CatOps) {
5015       SDValue NotCat = IsNOT(CatOp, DAG);
5016       if (!NotCat) return SDValue();
5017       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5018     }
5019     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
5020   }
5021   return SDValue();
5022 }
5023 
5024 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5025 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
5026 /// Note: This ignores saturation, so inputs must be checked first.
createPackShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Unary,unsigned NumStages=1)5027 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
5028                                   bool Unary, unsigned NumStages = 1) {
5029   assert(Mask.empty() && "Expected an empty shuffle mask vector");
5030   unsigned NumElts = VT.getVectorNumElements();
5031   unsigned NumLanes = VT.getSizeInBits() / 128;
5032   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5033   unsigned Offset = Unary ? 0 : NumElts;
5034   unsigned Repetitions = 1u << (NumStages - 1);
5035   unsigned Increment = 1u << NumStages;
5036   assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
5037 
5038   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5039     for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
5040       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5041         Mask.push_back(Elt + (Lane * NumEltsPerLane));
5042       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
5043         Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5044     }
5045   }
5046 }
5047 
5048 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
getPackDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)5049 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
5050                                 APInt &DemandedLHS, APInt &DemandedRHS) {
5051   int NumLanes = VT.getSizeInBits() / 128;
5052   int NumElts = DemandedElts.getBitWidth();
5053   int NumInnerElts = NumElts / 2;
5054   int NumEltsPerLane = NumElts / NumLanes;
5055   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
5056 
5057   DemandedLHS = APInt::getZero(NumInnerElts);
5058   DemandedRHS = APInt::getZero(NumInnerElts);
5059 
5060   // Map DemandedElts to the packed operands.
5061   for (int Lane = 0; Lane != NumLanes; ++Lane) {
5062     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
5063       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
5064       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
5065       if (DemandedElts[OuterIdx])
5066         DemandedLHS.setBit(InnerIdx);
5067       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
5068         DemandedRHS.setBit(InnerIdx);
5069     }
5070   }
5071 }
5072 
5073 // Split the demanded elts of a HADD/HSUB node between its operands.
getHorizDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)5074 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
5075                                  APInt &DemandedLHS, APInt &DemandedRHS) {
5076   int NumLanes = VT.getSizeInBits() / 128;
5077   int NumElts = DemandedElts.getBitWidth();
5078   int NumEltsPerLane = NumElts / NumLanes;
5079   int HalfEltsPerLane = NumEltsPerLane / 2;
5080 
5081   DemandedLHS = APInt::getZero(NumElts);
5082   DemandedRHS = APInt::getZero(NumElts);
5083 
5084   // Map DemandedElts to the horizontal operands.
5085   for (int Idx = 0; Idx != NumElts; ++Idx) {
5086     if (!DemandedElts[Idx])
5087       continue;
5088     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
5089     int LocalIdx = Idx % NumEltsPerLane;
5090     if (LocalIdx < HalfEltsPerLane) {
5091       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
5092       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
5093     } else {
5094       LocalIdx -= HalfEltsPerLane;
5095       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
5096       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
5097     }
5098   }
5099 }
5100 
5101 /// Calculates the shuffle mask corresponding to the target-specific opcode.
5102 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
5103 /// operands in \p Ops, and returns true.
5104 /// Sets \p IsUnary to true if only one source is used. Note that this will set
5105 /// IsUnary for shuffles which use a single input multiple times, and in those
5106 /// cases it will adjust the mask to only have indices within that single input.
5107 /// It is an error to call this with non-empty Mask/Ops vectors.
getTargetShuffleMask(SDNode * N,MVT VT,bool AllowSentinelZero,SmallVectorImpl<SDValue> & Ops,SmallVectorImpl<int> & Mask,bool & IsUnary)5108 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
5109                                  SmallVectorImpl<SDValue> &Ops,
5110                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5111   unsigned NumElems = VT.getVectorNumElements();
5112   unsigned MaskEltSize = VT.getScalarSizeInBits();
5113   SmallVector<uint64_t, 32> RawMask;
5114   APInt RawUndefs;
5115   uint64_t ImmN;
5116 
5117   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
5118   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
5119 
5120   IsUnary = false;
5121   bool IsFakeUnary = false;
5122   switch (N->getOpcode()) {
5123   case X86ISD::BLENDI:
5124     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5125     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5126     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5127     DecodeBLENDMask(NumElems, ImmN, Mask);
5128     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5129     break;
5130   case X86ISD::SHUFP:
5131     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5132     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5133     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5134     DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
5135     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5136     break;
5137   case X86ISD::INSERTPS:
5138     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5139     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5140     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5141     DecodeINSERTPSMask(ImmN, Mask);
5142     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5143     break;
5144   case X86ISD::EXTRQI:
5145     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5146     if (isa<ConstantSDNode>(N->getOperand(1)) &&
5147         isa<ConstantSDNode>(N->getOperand(2))) {
5148       int BitLen = N->getConstantOperandVal(1);
5149       int BitIdx = N->getConstantOperandVal(2);
5150       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
5151       IsUnary = true;
5152     }
5153     break;
5154   case X86ISD::INSERTQI:
5155     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5156     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5157     if (isa<ConstantSDNode>(N->getOperand(2)) &&
5158         isa<ConstantSDNode>(N->getOperand(3))) {
5159       int BitLen = N->getConstantOperandVal(2);
5160       int BitIdx = N->getConstantOperandVal(3);
5161       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
5162       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5163     }
5164     break;
5165   case X86ISD::UNPCKH:
5166     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5167     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5168     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
5169     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5170     break;
5171   case X86ISD::UNPCKL:
5172     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5173     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5174     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
5175     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5176     break;
5177   case X86ISD::MOVHLPS:
5178     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5179     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5180     DecodeMOVHLPSMask(NumElems, Mask);
5181     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5182     break;
5183   case X86ISD::MOVLHPS:
5184     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5185     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5186     DecodeMOVLHPSMask(NumElems, Mask);
5187     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5188     break;
5189   case X86ISD::VALIGN:
5190     assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
5191            "Only 32-bit and 64-bit elements are supported!");
5192     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5193     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5194     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5195     DecodeVALIGNMask(NumElems, ImmN, Mask);
5196     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5197     Ops.push_back(N->getOperand(1));
5198     Ops.push_back(N->getOperand(0));
5199     break;
5200   case X86ISD::PALIGNR:
5201     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5202     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5203     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5204     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5205     DecodePALIGNRMask(NumElems, ImmN, Mask);
5206     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5207     Ops.push_back(N->getOperand(1));
5208     Ops.push_back(N->getOperand(0));
5209     break;
5210   case X86ISD::VSHLDQ:
5211     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5212     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5213     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5214     DecodePSLLDQMask(NumElems, ImmN, Mask);
5215     IsUnary = true;
5216     break;
5217   case X86ISD::VSRLDQ:
5218     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5219     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5220     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5221     DecodePSRLDQMask(NumElems, ImmN, Mask);
5222     IsUnary = true;
5223     break;
5224   case X86ISD::PSHUFD:
5225   case X86ISD::VPERMILPI:
5226     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5227     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5228     DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
5229     IsUnary = true;
5230     break;
5231   case X86ISD::PSHUFHW:
5232     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5233     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5234     DecodePSHUFHWMask(NumElems, ImmN, Mask);
5235     IsUnary = true;
5236     break;
5237   case X86ISD::PSHUFLW:
5238     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5239     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5240     DecodePSHUFLWMask(NumElems, ImmN, Mask);
5241     IsUnary = true;
5242     break;
5243   case X86ISD::VZEXT_MOVL:
5244     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5245     DecodeZeroMoveLowMask(NumElems, Mask);
5246     IsUnary = true;
5247     break;
5248   case X86ISD::VBROADCAST:
5249     // We only decode broadcasts of same-sized vectors, peeking through to
5250     // extracted subvectors is likely to cause hasOneUse issues with
5251     // SimplifyDemandedBits etc.
5252     if (N->getOperand(0).getValueType() == VT) {
5253       DecodeVectorBroadcast(NumElems, Mask);
5254       IsUnary = true;
5255       break;
5256     }
5257     return false;
5258   case X86ISD::VPERMILPV: {
5259     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5260     IsUnary = true;
5261     SDValue MaskNode = N->getOperand(1);
5262     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5263                                     RawUndefs)) {
5264       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
5265       break;
5266     }
5267     return false;
5268   }
5269   case X86ISD::PSHUFB: {
5270     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
5271     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5272     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5273     IsUnary = true;
5274     SDValue MaskNode = N->getOperand(1);
5275     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
5276       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
5277       break;
5278     }
5279     return false;
5280   }
5281   case X86ISD::VPERMI:
5282     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5283     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5284     DecodeVPERMMask(NumElems, ImmN, Mask);
5285     IsUnary = true;
5286     break;
5287   case X86ISD::MOVSS:
5288   case X86ISD::MOVSD:
5289   case X86ISD::MOVSH:
5290     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5291     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5292     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
5293     break;
5294   case X86ISD::VPERM2X128:
5295     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5296     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5297     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5298     DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
5299     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5300     break;
5301   case X86ISD::SHUF128:
5302     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5303     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5304     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
5305     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
5306     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5307     break;
5308   case X86ISD::MOVSLDUP:
5309     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5310     DecodeMOVSLDUPMask(NumElems, Mask);
5311     IsUnary = true;
5312     break;
5313   case X86ISD::MOVSHDUP:
5314     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5315     DecodeMOVSHDUPMask(NumElems, Mask);
5316     IsUnary = true;
5317     break;
5318   case X86ISD::MOVDDUP:
5319     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5320     DecodeMOVDDUPMask(NumElems, Mask);
5321     IsUnary = true;
5322     break;
5323   case X86ISD::VPERMIL2: {
5324     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5325     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5326     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5327     SDValue MaskNode = N->getOperand(2);
5328     SDValue CtrlNode = N->getOperand(3);
5329     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
5330       unsigned CtrlImm = CtrlOp->getZExtValue();
5331       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5332                                       RawUndefs)) {
5333         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
5334                             Mask);
5335         break;
5336       }
5337     }
5338     return false;
5339   }
5340   case X86ISD::VPPERM: {
5341     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5342     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5343     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5344     SDValue MaskNode = N->getOperand(2);
5345     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
5346       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
5347       break;
5348     }
5349     return false;
5350   }
5351   case X86ISD::VPERMV: {
5352     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
5353     IsUnary = true;
5354     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
5355     Ops.push_back(N->getOperand(1));
5356     SDValue MaskNode = N->getOperand(0);
5357     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5358                                     RawUndefs)) {
5359       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
5360       break;
5361     }
5362     return false;
5363   }
5364   case X86ISD::VPERMV3: {
5365     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
5366     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
5367     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
5368     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
5369     Ops.push_back(N->getOperand(0));
5370     Ops.push_back(N->getOperand(2));
5371     SDValue MaskNode = N->getOperand(1);
5372     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
5373                                     RawUndefs)) {
5374       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
5375       break;
5376     }
5377     return false;
5378   }
5379   default: llvm_unreachable("unknown target shuffle node");
5380   }
5381 
5382   // Empty mask indicates the decode failed.
5383   if (Mask.empty())
5384     return false;
5385 
5386   // Check if we're getting a shuffle mask with zero'd elements.
5387   if (!AllowSentinelZero && isAnyZero(Mask))
5388     return false;
5389 
5390   // If we have a fake unary shuffle, the shuffle mask is spread across two
5391   // inputs that are actually the same node. Re-map the mask to always point
5392   // into the first input.
5393   if (IsFakeUnary)
5394     for (int &M : Mask)
5395       if (M >= (int)Mask.size())
5396         M -= Mask.size();
5397 
5398   // If we didn't already add operands in the opcode-specific code, default to
5399   // adding 1 or 2 operands starting at 0.
5400   if (Ops.empty()) {
5401     Ops.push_back(N->getOperand(0));
5402     if (!IsUnary || IsFakeUnary)
5403       Ops.push_back(N->getOperand(1));
5404   }
5405 
5406   return true;
5407 }
5408 
5409 // Wrapper for getTargetShuffleMask with InUnary;
getTargetShuffleMask(SDNode * N,MVT VT,bool AllowSentinelZero,SmallVectorImpl<SDValue> & Ops,SmallVectorImpl<int> & Mask)5410 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
5411                                  SmallVectorImpl<SDValue> &Ops,
5412                                  SmallVectorImpl<int> &Mask) {
5413   bool IsUnary;
5414   return getTargetShuffleMask(N, VT, AllowSentinelZero, Ops, Mask, IsUnary);
5415 }
5416 
5417 /// Compute whether each element of a shuffle is zeroable.
5418 ///
5419 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
5420 /// Either it is an undef element in the shuffle mask, the element of the input
5421 /// referenced is undef, or the element of the input referenced is known to be
5422 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
5423 /// as many lanes with this technique as possible to simplify the remaining
5424 /// shuffle.
computeZeroableShuffleElements(ArrayRef<int> Mask,SDValue V1,SDValue V2,APInt & KnownUndef,APInt & KnownZero)5425 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
5426                                            SDValue V1, SDValue V2,
5427                                            APInt &KnownUndef, APInt &KnownZero) {
5428   int Size = Mask.size();
5429   KnownUndef = KnownZero = APInt::getZero(Size);
5430 
5431   V1 = peekThroughBitcasts(V1);
5432   V2 = peekThroughBitcasts(V2);
5433 
5434   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
5435   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
5436 
5437   int VectorSizeInBits = V1.getValueSizeInBits();
5438   int ScalarSizeInBits = VectorSizeInBits / Size;
5439   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
5440 
5441   for (int i = 0; i < Size; ++i) {
5442     int M = Mask[i];
5443     // Handle the easy cases.
5444     if (M < 0) {
5445       KnownUndef.setBit(i);
5446       continue;
5447     }
5448     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
5449       KnownZero.setBit(i);
5450       continue;
5451     }
5452 
5453     // Determine shuffle input and normalize the mask.
5454     SDValue V = M < Size ? V1 : V2;
5455     M %= Size;
5456 
5457     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
5458     if (V.getOpcode() != ISD::BUILD_VECTOR)
5459       continue;
5460 
5461     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
5462     // the (larger) source element must be UNDEF/ZERO.
5463     if ((Size % V.getNumOperands()) == 0) {
5464       int Scale = Size / V->getNumOperands();
5465       SDValue Op = V.getOperand(M / Scale);
5466       if (Op.isUndef())
5467         KnownUndef.setBit(i);
5468       if (X86::isZeroNode(Op))
5469         KnownZero.setBit(i);
5470       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
5471         APInt Val = Cst->getAPIntValue();
5472         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
5473         if (Val == 0)
5474           KnownZero.setBit(i);
5475       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5476         APInt Val = Cst->getValueAPF().bitcastToAPInt();
5477         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
5478         if (Val == 0)
5479           KnownZero.setBit(i);
5480       }
5481       continue;
5482     }
5483 
5484     // If the BUILD_VECTOR has more elements then all the (smaller) source
5485     // elements must be UNDEF or ZERO.
5486     if ((V.getNumOperands() % Size) == 0) {
5487       int Scale = V->getNumOperands() / Size;
5488       bool AllUndef = true;
5489       bool AllZero = true;
5490       for (int j = 0; j < Scale; ++j) {
5491         SDValue Op = V.getOperand((M * Scale) + j);
5492         AllUndef &= Op.isUndef();
5493         AllZero &= X86::isZeroNode(Op);
5494       }
5495       if (AllUndef)
5496         KnownUndef.setBit(i);
5497       if (AllZero)
5498         KnownZero.setBit(i);
5499       continue;
5500     }
5501   }
5502 }
5503 
5504 /// Decode a target shuffle mask and inputs and see if any values are
5505 /// known to be undef or zero from their inputs.
5506 /// Returns true if the target shuffle mask was decoded.
5507 /// FIXME: Merge this with computeZeroableShuffleElements?
getTargetShuffleAndZeroables(SDValue N,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,APInt & KnownUndef,APInt & KnownZero)5508 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
5509                                          SmallVectorImpl<SDValue> &Ops,
5510                                          APInt &KnownUndef, APInt &KnownZero) {
5511   bool IsUnary;
5512   if (!isTargetShuffle(N.getOpcode()))
5513     return false;
5514 
5515   MVT VT = N.getSimpleValueType();
5516   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
5517     return false;
5518 
5519   int Size = Mask.size();
5520   SDValue V1 = Ops[0];
5521   SDValue V2 = IsUnary ? V1 : Ops[1];
5522   KnownUndef = KnownZero = APInt::getZero(Size);
5523 
5524   V1 = peekThroughBitcasts(V1);
5525   V2 = peekThroughBitcasts(V2);
5526 
5527   assert((VT.getSizeInBits() % Size) == 0 &&
5528          "Illegal split of shuffle value type");
5529   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
5530 
5531   // Extract known constant input data.
5532   APInt UndefSrcElts[2];
5533   SmallVector<APInt, 32> SrcEltBits[2];
5534   bool IsSrcConstant[2] = {
5535       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
5536                                     SrcEltBits[0], true, false),
5537       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
5538                                     SrcEltBits[1], true, false)};
5539 
5540   for (int i = 0; i < Size; ++i) {
5541     int M = Mask[i];
5542 
5543     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
5544     if (M < 0) {
5545       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
5546       if (SM_SentinelUndef == M)
5547         KnownUndef.setBit(i);
5548       if (SM_SentinelZero == M)
5549         KnownZero.setBit(i);
5550       continue;
5551     }
5552 
5553     // Determine shuffle input and normalize the mask.
5554     unsigned SrcIdx = M / Size;
5555     SDValue V = M < Size ? V1 : V2;
5556     M %= Size;
5557 
5558     // We are referencing an UNDEF input.
5559     if (V.isUndef()) {
5560       KnownUndef.setBit(i);
5561       continue;
5562     }
5563 
5564     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
5565     // TODO: We currently only set UNDEF for integer types - floats use the same
5566     // registers as vectors and many of the scalar folded loads rely on the
5567     // SCALAR_TO_VECTOR pattern.
5568     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5569         (Size % V.getValueType().getVectorNumElements()) == 0) {
5570       int Scale = Size / V.getValueType().getVectorNumElements();
5571       int Idx = M / Scale;
5572       if (Idx != 0 && !VT.isFloatingPoint())
5573         KnownUndef.setBit(i);
5574       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
5575         KnownZero.setBit(i);
5576       continue;
5577     }
5578 
5579     // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
5580     // base vectors.
5581     if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
5582       SDValue Vec = V.getOperand(0);
5583       int NumVecElts = Vec.getValueType().getVectorNumElements();
5584       if (Vec.isUndef() && Size == NumVecElts) {
5585         int Idx = V.getConstantOperandVal(2);
5586         int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
5587         if (M < Idx || (Idx + NumSubElts) <= M)
5588           KnownUndef.setBit(i);
5589       }
5590       continue;
5591     }
5592 
5593     // Attempt to extract from the source's constant bits.
5594     if (IsSrcConstant[SrcIdx]) {
5595       if (UndefSrcElts[SrcIdx][M])
5596         KnownUndef.setBit(i);
5597       else if (SrcEltBits[SrcIdx][M] == 0)
5598         KnownZero.setBit(i);
5599     }
5600   }
5601 
5602   assert(VT.getVectorNumElements() == (unsigned)Size &&
5603          "Different mask size from vector size!");
5604   return true;
5605 }
5606 
5607 // Replace target shuffle mask elements with known undef/zero sentinels.
resolveTargetShuffleFromZeroables(SmallVectorImpl<int> & Mask,const APInt & KnownUndef,const APInt & KnownZero,bool ResolveKnownZeros=true)5608 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
5609                                               const APInt &KnownUndef,
5610                                               const APInt &KnownZero,
5611                                               bool ResolveKnownZeros= true) {
5612   unsigned NumElts = Mask.size();
5613   assert(KnownUndef.getBitWidth() == NumElts &&
5614          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
5615 
5616   for (unsigned i = 0; i != NumElts; ++i) {
5617     if (KnownUndef[i])
5618       Mask[i] = SM_SentinelUndef;
5619     else if (ResolveKnownZeros && KnownZero[i])
5620       Mask[i] = SM_SentinelZero;
5621   }
5622 }
5623 
5624 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> & Mask,APInt & KnownUndef,APInt & KnownZero)5625 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
5626                                               APInt &KnownUndef,
5627                                               APInt &KnownZero) {
5628   unsigned NumElts = Mask.size();
5629   KnownUndef = KnownZero = APInt::getZero(NumElts);
5630 
5631   for (unsigned i = 0; i != NumElts; ++i) {
5632     int M = Mask[i];
5633     if (SM_SentinelUndef == M)
5634       KnownUndef.setBit(i);
5635     if (SM_SentinelZero == M)
5636       KnownZero.setBit(i);
5637   }
5638 }
5639 
5640 // Attempt to create a shuffle mask from a VSELECT/BLENDV condition mask.
createShuffleMaskFromVSELECT(SmallVectorImpl<int> & Mask,SDValue Cond,bool IsBLENDV=false)5641 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
5642                                          SDValue Cond, bool IsBLENDV = false) {
5643   EVT CondVT = Cond.getValueType();
5644   unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
5645   unsigned NumElts = CondVT.getVectorNumElements();
5646 
5647   APInt UndefElts;
5648   SmallVector<APInt, 32> EltBits;
5649   if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
5650                                      true, false))
5651     return false;
5652 
5653   Mask.resize(NumElts, SM_SentinelUndef);
5654 
5655   for (int i = 0; i != (int)NumElts; ++i) {
5656     Mask[i] = i;
5657     // Arbitrarily choose from the 2nd operand if the select condition element
5658     // is undef.
5659     // TODO: Can we do better by matching patterns such as even/odd?
5660     if (UndefElts[i] || (!IsBLENDV && EltBits[i].isZero()) ||
5661         (IsBLENDV && EltBits[i].isNonNegative()))
5662       Mask[i] += NumElts;
5663   }
5664 
5665   return true;
5666 }
5667 
5668 // Forward declaration (for getFauxShuffleMask recursive check).
5669 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
5670                                    SmallVectorImpl<SDValue> &Inputs,
5671                                    SmallVectorImpl<int> &Mask,
5672                                    const SelectionDAG &DAG, unsigned Depth,
5673                                    bool ResolveKnownElts);
5674 
5675 // Attempt to decode ops that could be represented as a shuffle mask.
5676 // The decoded shuffle mask may contain a different number of elements to the
5677 // destination value type.
5678 // TODO: Merge into getTargetShuffleInputs()
getFauxShuffleMask(SDValue N,const APInt & DemandedElts,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,const SelectionDAG & DAG,unsigned Depth,bool ResolveKnownElts)5679 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
5680                                SmallVectorImpl<int> &Mask,
5681                                SmallVectorImpl<SDValue> &Ops,
5682                                const SelectionDAG &DAG, unsigned Depth,
5683                                bool ResolveKnownElts) {
5684   Mask.clear();
5685   Ops.clear();
5686 
5687   MVT VT = N.getSimpleValueType();
5688   unsigned NumElts = VT.getVectorNumElements();
5689   unsigned NumSizeInBits = VT.getSizeInBits();
5690   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
5691   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
5692     return false;
5693   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
5694   unsigned NumSizeInBytes = NumSizeInBits / 8;
5695   unsigned NumBytesPerElt = NumBitsPerElt / 8;
5696 
5697   unsigned Opcode = N.getOpcode();
5698   switch (Opcode) {
5699   case ISD::VECTOR_SHUFFLE: {
5700     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
5701     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
5702     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
5703       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
5704       Ops.push_back(N.getOperand(0));
5705       Ops.push_back(N.getOperand(1));
5706       return true;
5707     }
5708     return false;
5709   }
5710   case ISD::AND:
5711   case X86ISD::ANDNP: {
5712     // Attempt to decode as a per-byte mask.
5713     APInt UndefElts;
5714     SmallVector<APInt, 32> EltBits;
5715     SDValue N0 = N.getOperand(0);
5716     SDValue N1 = N.getOperand(1);
5717     bool IsAndN = (X86ISD::ANDNP == Opcode);
5718     uint64_t ZeroMask = IsAndN ? 255 : 0;
5719     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
5720       return false;
5721     // We can't assume an undef src element gives an undef dst - the other src
5722     // might be zero.
5723     if (!UndefElts.isZero())
5724       return false;
5725     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
5726       const APInt &ByteBits = EltBits[i];
5727       if (ByteBits != 0 && ByteBits != 255)
5728         return false;
5729       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
5730     }
5731     Ops.push_back(IsAndN ? N1 : N0);
5732     return true;
5733   }
5734   case ISD::OR: {
5735     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
5736     // is a valid shuffle index.
5737     SDValue N0 = peekThroughBitcasts(N.getOperand(0));
5738     SDValue N1 = peekThroughBitcasts(N.getOperand(1));
5739     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
5740       return false;
5741 
5742     SmallVector<int, 64> SrcMask0, SrcMask1;
5743     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
5744     APInt Demand0 = APInt::getAllOnes(N0.getValueType().getVectorNumElements());
5745     APInt Demand1 = APInt::getAllOnes(N1.getValueType().getVectorNumElements());
5746     if (!getTargetShuffleInputs(N0, Demand0, SrcInputs0, SrcMask0, DAG,
5747                                 Depth + 1, true) ||
5748         !getTargetShuffleInputs(N1, Demand1, SrcInputs1, SrcMask1, DAG,
5749                                 Depth + 1, true))
5750       return false;
5751 
5752     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
5753     SmallVector<int, 64> Mask0, Mask1;
5754     narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
5755     narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
5756     for (int i = 0; i != (int)MaskSize; ++i) {
5757       // NOTE: Don't handle SM_SentinelUndef, as we can end up in infinite
5758       // loops converting between OR and BLEND shuffles due to
5759       // canWidenShuffleElements merging away undef elements, meaning we
5760       // fail to recognise the OR as the undef element isn't known zero.
5761       if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
5762         Mask.push_back(SM_SentinelZero);
5763       else if (Mask1[i] == SM_SentinelZero)
5764         Mask.push_back(i);
5765       else if (Mask0[i] == SM_SentinelZero)
5766         Mask.push_back(i + MaskSize);
5767       else
5768         return false;
5769     }
5770     Ops.push_back(N0);
5771     Ops.push_back(N1);
5772     return true;
5773   }
5774   case ISD::INSERT_SUBVECTOR: {
5775     SDValue Src = N.getOperand(0);
5776     SDValue Sub = N.getOperand(1);
5777     EVT SubVT = Sub.getValueType();
5778     unsigned NumSubElts = SubVT.getVectorNumElements();
5779     if (!N->isOnlyUserOf(Sub.getNode()))
5780       return false;
5781     SDValue SubBC = peekThroughBitcasts(Sub);
5782     uint64_t InsertIdx = N.getConstantOperandVal(2);
5783     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
5784     if (SubBC.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5785         SubBC.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
5786       uint64_t ExtractIdx = SubBC.getConstantOperandVal(1);
5787       SDValue SubBCSrc = SubBC.getOperand(0);
5788       unsigned NumSubSrcBCElts = SubBCSrc.getValueType().getVectorNumElements();
5789       unsigned MaxElts = std::max(NumElts, NumSubSrcBCElts);
5790       assert((MaxElts % NumElts) == 0 && (MaxElts % NumSubSrcBCElts) == 0 &&
5791              "Subvector valuetype mismatch");
5792       InsertIdx *= (MaxElts / NumElts);
5793       ExtractIdx *= (MaxElts / NumSubSrcBCElts);
5794       NumSubElts *= (MaxElts / NumElts);
5795       bool SrcIsUndef = Src.isUndef();
5796       for (int i = 0; i != (int)MaxElts; ++i)
5797         Mask.push_back(SrcIsUndef ? SM_SentinelUndef : i);
5798       for (int i = 0; i != (int)NumSubElts; ++i)
5799         Mask[InsertIdx + i] = (SrcIsUndef ? 0 : MaxElts) + ExtractIdx + i;
5800       if (!SrcIsUndef)
5801         Ops.push_back(Src);
5802       Ops.push_back(SubBCSrc);
5803       return true;
5804     }
5805     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
5806     SmallVector<int, 64> SubMask;
5807     SmallVector<SDValue, 2> SubInputs;
5808     SDValue SubSrc = peekThroughOneUseBitcasts(Sub);
5809     EVT SubSrcVT = SubSrc.getValueType();
5810     if (!SubSrcVT.isVector())
5811       return false;
5812 
5813     APInt SubDemand = APInt::getAllOnes(SubSrcVT.getVectorNumElements());
5814     if (!getTargetShuffleInputs(SubSrc, SubDemand, SubInputs, SubMask, DAG,
5815                                 Depth + 1, ResolveKnownElts))
5816       return false;
5817 
5818     // Subvector shuffle inputs must not be larger than the subvector.
5819     if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
5820           return SubVT.getFixedSizeInBits() <
5821                  SubInput.getValueSizeInBits().getFixedValue();
5822         }))
5823       return false;
5824 
5825     if (SubMask.size() != NumSubElts) {
5826       assert(((SubMask.size() % NumSubElts) == 0 ||
5827               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
5828       if ((NumSubElts % SubMask.size()) == 0) {
5829         int Scale = NumSubElts / SubMask.size();
5830         SmallVector<int,64> ScaledSubMask;
5831         narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
5832         SubMask = ScaledSubMask;
5833       } else {
5834         int Scale = SubMask.size() / NumSubElts;
5835         NumSubElts = SubMask.size();
5836         NumElts *= Scale;
5837         InsertIdx *= Scale;
5838       }
5839     }
5840     Ops.push_back(Src);
5841     Ops.append(SubInputs.begin(), SubInputs.end());
5842     if (ISD::isBuildVectorAllZeros(Src.getNode()))
5843       Mask.append(NumElts, SM_SentinelZero);
5844     else
5845       for (int i = 0; i != (int)NumElts; ++i)
5846         Mask.push_back(i);
5847     for (int i = 0; i != (int)NumSubElts; ++i) {
5848       int M = SubMask[i];
5849       if (0 <= M) {
5850         int InputIdx = M / NumSubElts;
5851         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
5852       }
5853       Mask[i + InsertIdx] = M;
5854     }
5855     return true;
5856   }
5857   case X86ISD::PINSRB:
5858   case X86ISD::PINSRW:
5859   case ISD::SCALAR_TO_VECTOR:
5860   case ISD::INSERT_VECTOR_ELT: {
5861     // Match against a insert_vector_elt/scalar_to_vector of an extract from a
5862     // vector, for matching src/dst vector types.
5863     SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
5864 
5865     unsigned DstIdx = 0;
5866     if (Opcode != ISD::SCALAR_TO_VECTOR) {
5867       // Check we have an in-range constant insertion index.
5868       if (!isa<ConstantSDNode>(N.getOperand(2)) ||
5869           N.getConstantOperandAPInt(2).uge(NumElts))
5870         return false;
5871       DstIdx = N.getConstantOperandVal(2);
5872 
5873       // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
5874       if (X86::isZeroNode(Scl)) {
5875         Ops.push_back(N.getOperand(0));
5876         for (unsigned i = 0; i != NumElts; ++i)
5877           Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
5878         return true;
5879       }
5880     }
5881 
5882     // Peek through trunc/aext/zext.
5883     // TODO: aext shouldn't require SM_SentinelZero padding.
5884     // TODO: handle shift of scalars.
5885     unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
5886     while (Scl.getOpcode() == ISD::TRUNCATE ||
5887            Scl.getOpcode() == ISD::ANY_EXTEND ||
5888            Scl.getOpcode() == ISD::ZERO_EXTEND) {
5889       Scl = Scl.getOperand(0);
5890       MinBitsPerElt =
5891           std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
5892     }
5893     if ((MinBitsPerElt % 8) != 0)
5894       return false;
5895 
5896     // Attempt to find the source vector the scalar was extracted from.
5897     SDValue SrcExtract;
5898     if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
5899          Scl.getOpcode() == X86ISD::PEXTRW ||
5900          Scl.getOpcode() == X86ISD::PEXTRB) &&
5901         Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
5902       SrcExtract = Scl;
5903     }
5904     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
5905       return false;
5906 
5907     SDValue SrcVec = SrcExtract.getOperand(0);
5908     EVT SrcVT = SrcVec.getValueType();
5909     if (!SrcVT.getScalarType().isByteSized())
5910       return false;
5911     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
5912     unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
5913     unsigned DstByte = DstIdx * NumBytesPerElt;
5914     MinBitsPerElt =
5915         std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
5916 
5917     // Create 'identity' byte level shuffle mask and then add inserted bytes.
5918     if (Opcode == ISD::SCALAR_TO_VECTOR) {
5919       Ops.push_back(SrcVec);
5920       Mask.append(NumSizeInBytes, SM_SentinelUndef);
5921     } else {
5922       Ops.push_back(SrcVec);
5923       Ops.push_back(N.getOperand(0));
5924       for (int i = 0; i != (int)NumSizeInBytes; ++i)
5925         Mask.push_back(NumSizeInBytes + i);
5926     }
5927 
5928     unsigned MinBytesPerElts = MinBitsPerElt / 8;
5929     MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
5930     for (unsigned i = 0; i != MinBytesPerElts; ++i)
5931       Mask[DstByte + i] = SrcByte + i;
5932     for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
5933       Mask[DstByte + i] = SM_SentinelZero;
5934     return true;
5935   }
5936   case X86ISD::PACKSS:
5937   case X86ISD::PACKUS: {
5938     SDValue N0 = N.getOperand(0);
5939     SDValue N1 = N.getOperand(1);
5940     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
5941            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
5942            "Unexpected input value type");
5943 
5944     APInt EltsLHS, EltsRHS;
5945     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
5946 
5947     // If we know input saturation won't happen (or we don't care for particular
5948     // lanes), we can treat this as a truncation shuffle.
5949     bool Offset0 = false, Offset1 = false;
5950     if (Opcode == X86ISD::PACKSS) {
5951       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
5952            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
5953           (!(N1.isUndef() || EltsRHS.isZero()) &&
5954            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
5955         return false;
5956       // We can't easily fold ASHR into a shuffle, but if it was feeding a
5957       // PACKSS then it was likely being used for sign-extension for a
5958       // truncation, so just peek through and adjust the mask accordingly.
5959       if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
5960           N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
5961         Offset0 = true;
5962         N0 = N0.getOperand(0);
5963       }
5964       if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
5965           N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
5966         Offset1 = true;
5967         N1 = N1.getOperand(0);
5968       }
5969     } else {
5970       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
5971       if ((!(N0.isUndef() || EltsLHS.isZero()) &&
5972            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
5973           (!(N1.isUndef() || EltsRHS.isZero()) &&
5974            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
5975         return false;
5976     }
5977 
5978     bool IsUnary = (N0 == N1);
5979 
5980     Ops.push_back(N0);
5981     if (!IsUnary)
5982       Ops.push_back(N1);
5983 
5984     createPackShuffleMask(VT, Mask, IsUnary);
5985 
5986     if (Offset0 || Offset1) {
5987       for (int &M : Mask)
5988         if ((Offset0 && isInRange(M, 0, NumElts)) ||
5989             (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
5990           ++M;
5991     }
5992     return true;
5993   }
5994   case ISD::VSELECT:
5995   case X86ISD::BLENDV: {
5996     SDValue Cond = N.getOperand(0);
5997     if (createShuffleMaskFromVSELECT(Mask, Cond, Opcode == X86ISD::BLENDV)) {
5998       Ops.push_back(N.getOperand(1));
5999       Ops.push_back(N.getOperand(2));
6000       return true;
6001     }
6002     return false;
6003   }
6004   case X86ISD::VTRUNC: {
6005     SDValue Src = N.getOperand(0);
6006     EVT SrcVT = Src.getValueType();
6007     // Truncated source must be a simple vector.
6008     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6009         (SrcVT.getScalarSizeInBits() % 8) != 0)
6010       return false;
6011     unsigned NumSrcElts = SrcVT.getVectorNumElements();
6012     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
6013     unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
6014     assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
6015     for (unsigned i = 0; i != NumSrcElts; ++i)
6016       Mask.push_back(i * Scale);
6017     Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
6018     Ops.push_back(Src);
6019     return true;
6020   }
6021   case X86ISD::VSHLI:
6022   case X86ISD::VSRLI: {
6023     uint64_t ShiftVal = N.getConstantOperandVal(1);
6024     // Out of range bit shifts are guaranteed to be zero.
6025     if (NumBitsPerElt <= ShiftVal) {
6026       Mask.append(NumElts, SM_SentinelZero);
6027       return true;
6028     }
6029 
6030     // We can only decode 'whole byte' bit shifts as shuffles.
6031     if ((ShiftVal % 8) != 0)
6032       break;
6033 
6034     uint64_t ByteShift = ShiftVal / 8;
6035     Ops.push_back(N.getOperand(0));
6036 
6037     // Clear mask to all zeros and insert the shifted byte indices.
6038     Mask.append(NumSizeInBytes, SM_SentinelZero);
6039 
6040     if (X86ISD::VSHLI == Opcode) {
6041       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
6042         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6043           Mask[i + j] = i + j - ByteShift;
6044     } else {
6045       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
6046         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6047           Mask[i + j - ByteShift] = i + j;
6048     }
6049     return true;
6050   }
6051   case X86ISD::VROTLI:
6052   case X86ISD::VROTRI: {
6053     // We can only decode 'whole byte' bit rotates as shuffles.
6054     uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
6055     if ((RotateVal % 8) != 0)
6056       return false;
6057     Ops.push_back(N.getOperand(0));
6058     int Offset = RotateVal / 8;
6059     Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
6060     for (int i = 0; i != (int)NumElts; ++i) {
6061       int BaseIdx = i * NumBytesPerElt;
6062       for (int j = 0; j != (int)NumBytesPerElt; ++j) {
6063         Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
6064       }
6065     }
6066     return true;
6067   }
6068   case X86ISD::VBROADCAST: {
6069     SDValue Src = N.getOperand(0);
6070     if (!Src.getSimpleValueType().isVector()) {
6071       if (Src.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6072           !isNullConstant(Src.getOperand(1)) ||
6073           Src.getOperand(0).getValueType().getScalarType() !=
6074               VT.getScalarType())
6075         return false;
6076       Src = Src.getOperand(0);
6077     }
6078     Ops.push_back(Src);
6079     Mask.append(NumElts, 0);
6080     return true;
6081   }
6082   case ISD::SIGN_EXTEND_VECTOR_INREG: {
6083     SDValue Src = N.getOperand(0);
6084     EVT SrcVT = Src.getValueType();
6085     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
6086 
6087     // Extended source must be a simple vector.
6088     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6089         (NumBitsPerSrcElt % 8) != 0)
6090       return false;
6091 
6092     // We can only handle all-signbits extensions.
6093     APInt DemandedSrcElts =
6094         DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
6095     if (DAG.ComputeNumSignBits(Src, DemandedSrcElts) != NumBitsPerSrcElt)
6096       return false;
6097 
6098     assert((NumBitsPerElt % NumBitsPerSrcElt) == 0 && "Unexpected extension");
6099     unsigned Scale = NumBitsPerElt / NumBitsPerSrcElt;
6100     for (unsigned I = 0; I != NumElts; ++I)
6101       Mask.append(Scale, I);
6102     Ops.push_back(Src);
6103     return true;
6104   }
6105   case ISD::ZERO_EXTEND:
6106   case ISD::ANY_EXTEND:
6107   case ISD::ZERO_EXTEND_VECTOR_INREG:
6108   case ISD::ANY_EXTEND_VECTOR_INREG: {
6109     SDValue Src = N.getOperand(0);
6110     EVT SrcVT = Src.getValueType();
6111 
6112     // Extended source must be a simple vector.
6113     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6114         (SrcVT.getScalarSizeInBits() % 8) != 0)
6115       return false;
6116 
6117     bool IsAnyExtend =
6118         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
6119     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
6120                          IsAnyExtend, Mask);
6121     Ops.push_back(Src);
6122     return true;
6123   }
6124   }
6125 
6126   return false;
6127 }
6128 
6129 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask)6130 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
6131                                               SmallVectorImpl<int> &Mask) {
6132   int MaskWidth = Mask.size();
6133   SmallVector<SDValue, 16> UsedInputs;
6134   for (int i = 0, e = Inputs.size(); i < e; ++i) {
6135     int lo = UsedInputs.size() * MaskWidth;
6136     int hi = lo + MaskWidth;
6137 
6138     // Strip UNDEF input usage.
6139     if (Inputs[i].isUndef())
6140       for (int &M : Mask)
6141         if ((lo <= M) && (M < hi))
6142           M = SM_SentinelUndef;
6143 
6144     // Check for unused inputs.
6145     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
6146       for (int &M : Mask)
6147         if (lo <= M)
6148           M -= MaskWidth;
6149       continue;
6150     }
6151 
6152     // Check for repeated inputs.
6153     bool IsRepeat = false;
6154     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
6155       if (UsedInputs[j] != Inputs[i])
6156         continue;
6157       for (int &M : Mask)
6158         if (lo <= M)
6159           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
6160       IsRepeat = true;
6161       break;
6162     }
6163     if (IsRepeat)
6164       continue;
6165 
6166     UsedInputs.push_back(Inputs[i]);
6167   }
6168   Inputs = UsedInputs;
6169 }
6170 
6171 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
6172 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
6173 /// Returns true if the target shuffle mask was decoded.
getTargetShuffleInputs(SDValue Op,const APInt & DemandedElts,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,APInt & KnownUndef,APInt & KnownZero,const SelectionDAG & DAG,unsigned Depth,bool ResolveKnownElts)6174 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6175                                    SmallVectorImpl<SDValue> &Inputs,
6176                                    SmallVectorImpl<int> &Mask,
6177                                    APInt &KnownUndef, APInt &KnownZero,
6178                                    const SelectionDAG &DAG, unsigned Depth,
6179                                    bool ResolveKnownElts) {
6180   if (Depth >= SelectionDAG::MaxRecursionDepth)
6181     return false; // Limit search depth.
6182 
6183   EVT VT = Op.getValueType();
6184   if (!VT.isSimple() || !VT.isVector())
6185     return false;
6186 
6187   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
6188     if (ResolveKnownElts)
6189       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
6190     return true;
6191   }
6192   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
6193                          ResolveKnownElts)) {
6194     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
6195     return true;
6196   }
6197   return false;
6198 }
6199 
getTargetShuffleInputs(SDValue Op,const APInt & DemandedElts,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,const SelectionDAG & DAG,unsigned Depth,bool ResolveKnownElts)6200 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
6201                                    SmallVectorImpl<SDValue> &Inputs,
6202                                    SmallVectorImpl<int> &Mask,
6203                                    const SelectionDAG &DAG, unsigned Depth,
6204                                    bool ResolveKnownElts) {
6205   APInt KnownUndef, KnownZero;
6206   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
6207                                 KnownZero, DAG, Depth, ResolveKnownElts);
6208 }
6209 
getTargetShuffleInputs(SDValue Op,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,const SelectionDAG & DAG,unsigned Depth=0,bool ResolveKnownElts=true)6210 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
6211                                    SmallVectorImpl<int> &Mask,
6212                                    const SelectionDAG &DAG, unsigned Depth = 0,
6213                                    bool ResolveKnownElts = true) {
6214   EVT VT = Op.getValueType();
6215   if (!VT.isSimple() || !VT.isVector())
6216     return false;
6217 
6218   unsigned NumElts = Op.getValueType().getVectorNumElements();
6219   APInt DemandedElts = APInt::getAllOnes(NumElts);
6220   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, DAG, Depth,
6221                                 ResolveKnownElts);
6222 }
6223 
6224 // Attempt to create a scalar/subvector broadcast from the base MemSDNode.
getBROADCAST_LOAD(unsigned Opcode,const SDLoc & DL,EVT VT,EVT MemVT,MemSDNode * Mem,unsigned Offset,SelectionDAG & DAG)6225 static SDValue getBROADCAST_LOAD(unsigned Opcode, const SDLoc &DL, EVT VT,
6226                                  EVT MemVT, MemSDNode *Mem, unsigned Offset,
6227                                  SelectionDAG &DAG) {
6228   assert((Opcode == X86ISD::VBROADCAST_LOAD ||
6229           Opcode == X86ISD::SUBV_BROADCAST_LOAD) &&
6230          "Unknown broadcast load type");
6231 
6232   // Ensure this is a simple (non-atomic, non-voltile), temporal read memop.
6233   if (!Mem || !Mem->readMem() || !Mem->isSimple() || Mem->isNonTemporal())
6234     return SDValue();
6235 
6236   SDValue Ptr = DAG.getMemBasePlusOffset(Mem->getBasePtr(),
6237                                          TypeSize::getFixed(Offset), DL);
6238   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
6239   SDValue Ops[] = {Mem->getChain(), Ptr};
6240   SDValue BcstLd = DAG.getMemIntrinsicNode(
6241       Opcode, DL, Tys, Ops, MemVT,
6242       DAG.getMachineFunction().getMachineMemOperand(
6243           Mem->getMemOperand(), Offset, MemVT.getStoreSize()));
6244   DAG.makeEquivalentMemoryOrdering(SDValue(Mem, 1), BcstLd.getValue(1));
6245   return BcstLd;
6246 }
6247 
6248 /// Returns the scalar element that will make up the i'th
6249 /// element of the result of the vector shuffle.
getShuffleScalarElt(SDValue Op,unsigned Index,SelectionDAG & DAG,unsigned Depth)6250 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
6251                                    SelectionDAG &DAG, unsigned Depth) {
6252   if (Depth >= SelectionDAG::MaxRecursionDepth)
6253     return SDValue(); // Limit search depth.
6254 
6255   EVT VT = Op.getValueType();
6256   unsigned Opcode = Op.getOpcode();
6257   unsigned NumElems = VT.getVectorNumElements();
6258 
6259   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
6260   if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
6261     int Elt = SV->getMaskElt(Index);
6262 
6263     if (Elt < 0)
6264       return DAG.getUNDEF(VT.getVectorElementType());
6265 
6266     SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
6267     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
6268   }
6269 
6270   // Recurse into target specific vector shuffles to find scalars.
6271   if (isTargetShuffle(Opcode)) {
6272     MVT ShufVT = VT.getSimpleVT();
6273     MVT ShufSVT = ShufVT.getVectorElementType();
6274     int NumElems = (int)ShufVT.getVectorNumElements();
6275     SmallVector<int, 16> ShuffleMask;
6276     SmallVector<SDValue, 16> ShuffleOps;
6277     if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
6278                               ShuffleMask))
6279       return SDValue();
6280 
6281     int Elt = ShuffleMask[Index];
6282     if (Elt == SM_SentinelZero)
6283       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
6284                                  : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
6285     if (Elt == SM_SentinelUndef)
6286       return DAG.getUNDEF(ShufSVT);
6287 
6288     assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
6289     SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
6290     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
6291   }
6292 
6293   // Recurse into insert_subvector base/sub vector to find scalars.
6294   if (Opcode == ISD::INSERT_SUBVECTOR) {
6295     SDValue Vec = Op.getOperand(0);
6296     SDValue Sub = Op.getOperand(1);
6297     uint64_t SubIdx = Op.getConstantOperandVal(2);
6298     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
6299 
6300     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
6301       return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
6302     return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
6303   }
6304 
6305   // Recurse into concat_vectors sub vector to find scalars.
6306   if (Opcode == ISD::CONCAT_VECTORS) {
6307     EVT SubVT = Op.getOperand(0).getValueType();
6308     unsigned NumSubElts = SubVT.getVectorNumElements();
6309     uint64_t SubIdx = Index / NumSubElts;
6310     uint64_t SubElt = Index % NumSubElts;
6311     return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
6312   }
6313 
6314   // Recurse into extract_subvector src vector to find scalars.
6315   if (Opcode == ISD::EXTRACT_SUBVECTOR) {
6316     SDValue Src = Op.getOperand(0);
6317     uint64_t SrcIdx = Op.getConstantOperandVal(1);
6318     return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
6319   }
6320 
6321   // We only peek through bitcasts of the same vector width.
6322   if (Opcode == ISD::BITCAST) {
6323     SDValue Src = Op.getOperand(0);
6324     EVT SrcVT = Src.getValueType();
6325     if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
6326       return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
6327     return SDValue();
6328   }
6329 
6330   // Actual nodes that may contain scalar elements
6331 
6332   // For insert_vector_elt - either return the index matching scalar or recurse
6333   // into the base vector.
6334   if (Opcode == ISD::INSERT_VECTOR_ELT &&
6335       isa<ConstantSDNode>(Op.getOperand(2))) {
6336     if (Op.getConstantOperandAPInt(2) == Index)
6337       return Op.getOperand(1);
6338     return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
6339   }
6340 
6341   if (Opcode == ISD::SCALAR_TO_VECTOR)
6342     return (Index == 0) ? Op.getOperand(0)
6343                         : DAG.getUNDEF(VT.getVectorElementType());
6344 
6345   if (Opcode == ISD::BUILD_VECTOR)
6346     return Op.getOperand(Index);
6347 
6348   return SDValue();
6349 }
6350 
6351 // Use PINSRB/PINSRW/PINSRD to create a build vector.
LowerBuildVectorAsInsert(SDValue Op,const APInt & NonZeroMask,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)6352 static SDValue LowerBuildVectorAsInsert(SDValue Op, const APInt &NonZeroMask,
6353                                         unsigned NumNonZero, unsigned NumZero,
6354                                         SelectionDAG &DAG,
6355                                         const X86Subtarget &Subtarget) {
6356   MVT VT = Op.getSimpleValueType();
6357   unsigned NumElts = VT.getVectorNumElements();
6358   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
6359           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
6360          "Illegal vector insertion");
6361 
6362   SDLoc dl(Op);
6363   SDValue V;
6364   bool First = true;
6365 
6366   for (unsigned i = 0; i < NumElts; ++i) {
6367     bool IsNonZero = NonZeroMask[i];
6368     if (!IsNonZero)
6369       continue;
6370 
6371     // If the build vector contains zeros or our first insertion is not the
6372     // first index then insert into zero vector to break any register
6373     // dependency else use SCALAR_TO_VECTOR.
6374     if (First) {
6375       First = false;
6376       if (NumZero || 0 != i)
6377         V = getZeroVector(VT, Subtarget, DAG, dl);
6378       else {
6379         assert(0 == i && "Expected insertion into zero-index");
6380         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
6381         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
6382         V = DAG.getBitcast(VT, V);
6383         continue;
6384       }
6385     }
6386     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
6387                     DAG.getIntPtrConstant(i, dl));
6388   }
6389 
6390   return V;
6391 }
6392 
6393 /// Custom lower build_vector of v16i8.
LowerBuildVectorv16i8(SDValue Op,const APInt & NonZeroMask,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)6394 static SDValue LowerBuildVectorv16i8(SDValue Op, const APInt &NonZeroMask,
6395                                      unsigned NumNonZero, unsigned NumZero,
6396                                      SelectionDAG &DAG,
6397                                      const X86Subtarget &Subtarget) {
6398   if (NumNonZero > 8 && !Subtarget.hasSSE41())
6399     return SDValue();
6400 
6401   // SSE4.1 - use PINSRB to insert each byte directly.
6402   if (Subtarget.hasSSE41())
6403     return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
6404                                     Subtarget);
6405 
6406   SDLoc dl(Op);
6407   SDValue V;
6408 
6409   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
6410   // If both the lowest 16-bits are non-zero, then convert to MOVD.
6411   if (!NonZeroMask.extractBits(2, 0).isZero() &&
6412       !NonZeroMask.extractBits(2, 2).isZero()) {
6413     for (unsigned I = 0; I != 4; ++I) {
6414       if (!NonZeroMask[I])
6415         continue;
6416       SDValue Elt = DAG.getZExtOrTrunc(Op.getOperand(I), dl, MVT::i32);
6417       if (I != 0)
6418         Elt = DAG.getNode(ISD::SHL, dl, MVT::i32, Elt,
6419                           DAG.getConstant(I * 8, dl, MVT::i8));
6420       V = V ? DAG.getNode(ISD::OR, dl, MVT::i32, V, Elt) : Elt;
6421     }
6422     assert(V && "Failed to fold v16i8 vector to zero");
6423     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
6424     V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
6425     V = DAG.getBitcast(MVT::v8i16, V);
6426   }
6427   for (unsigned i = V ? 4 : 0; i < 16; i += 2) {
6428     bool ThisIsNonZero = NonZeroMask[i];
6429     bool NextIsNonZero = NonZeroMask[i + 1];
6430     if (!ThisIsNonZero && !NextIsNonZero)
6431       continue;
6432 
6433     SDValue Elt;
6434     if (ThisIsNonZero) {
6435       if (NumZero || NextIsNonZero)
6436         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
6437       else
6438         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
6439     }
6440 
6441     if (NextIsNonZero) {
6442       SDValue NextElt = Op.getOperand(i + 1);
6443       if (i == 0 && NumZero)
6444         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
6445       else
6446         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
6447       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
6448                             DAG.getConstant(8, dl, MVT::i8));
6449       if (ThisIsNonZero)
6450         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
6451       else
6452         Elt = NextElt;
6453     }
6454 
6455     // If our first insertion is not the first index or zeros are needed, then
6456     // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
6457     // elements undefined).
6458     if (!V) {
6459       if (i != 0 || NumZero)
6460         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
6461       else {
6462         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
6463         V = DAG.getBitcast(MVT::v8i16, V);
6464         continue;
6465       }
6466     }
6467     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
6468     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
6469                     DAG.getIntPtrConstant(i / 2, dl));
6470   }
6471 
6472   return DAG.getBitcast(MVT::v16i8, V);
6473 }
6474 
6475 /// Custom lower build_vector of v8i16.
LowerBuildVectorv8i16(SDValue Op,const APInt & NonZeroMask,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)6476 static SDValue LowerBuildVectorv8i16(SDValue Op, const APInt &NonZeroMask,
6477                                      unsigned NumNonZero, unsigned NumZero,
6478                                      SelectionDAG &DAG,
6479                                      const X86Subtarget &Subtarget) {
6480   if (NumNonZero > 4 && !Subtarget.hasSSE41())
6481     return SDValue();
6482 
6483   // Use PINSRW to insert each byte directly.
6484   return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
6485                                   Subtarget);
6486 }
6487 
6488 /// Custom lower build_vector of v4i32 or v4f32.
LowerBuildVectorv4x32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)6489 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
6490                                      const X86Subtarget &Subtarget) {
6491   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
6492   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
6493   // Because we're creating a less complicated build vector here, we may enable
6494   // further folding of the MOVDDUP via shuffle transforms.
6495   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
6496       Op.getOperand(0) == Op.getOperand(2) &&
6497       Op.getOperand(1) == Op.getOperand(3) &&
6498       Op.getOperand(0) != Op.getOperand(1)) {
6499     SDLoc DL(Op);
6500     MVT VT = Op.getSimpleValueType();
6501     MVT EltVT = VT.getVectorElementType();
6502     // Create a new build vector with the first 2 elements followed by undef
6503     // padding, bitcast to v2f64, duplicate, and bitcast back.
6504     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
6505                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
6506     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
6507     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
6508     return DAG.getBitcast(VT, Dup);
6509   }
6510 
6511   // Find all zeroable elements.
6512   std::bitset<4> Zeroable, Undefs;
6513   for (int i = 0; i < 4; ++i) {
6514     SDValue Elt = Op.getOperand(i);
6515     Undefs[i] = Elt.isUndef();
6516     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
6517   }
6518   assert(Zeroable.size() - Zeroable.count() > 1 &&
6519          "We expect at least two non-zero elements!");
6520 
6521   // We only know how to deal with build_vector nodes where elements are either
6522   // zeroable or extract_vector_elt with constant index.
6523   SDValue FirstNonZero;
6524   unsigned FirstNonZeroIdx;
6525   for (unsigned i = 0; i < 4; ++i) {
6526     if (Zeroable[i])
6527       continue;
6528     SDValue Elt = Op.getOperand(i);
6529     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6530         !isa<ConstantSDNode>(Elt.getOperand(1)))
6531       return SDValue();
6532     // Make sure that this node is extracting from a 128-bit vector.
6533     MVT VT = Elt.getOperand(0).getSimpleValueType();
6534     if (!VT.is128BitVector())
6535       return SDValue();
6536     if (!FirstNonZero.getNode()) {
6537       FirstNonZero = Elt;
6538       FirstNonZeroIdx = i;
6539     }
6540   }
6541 
6542   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
6543   SDValue V1 = FirstNonZero.getOperand(0);
6544   MVT VT = V1.getSimpleValueType();
6545 
6546   // See if this build_vector can be lowered as a blend with zero.
6547   SDValue Elt;
6548   unsigned EltMaskIdx, EltIdx;
6549   int Mask[4];
6550   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
6551     if (Zeroable[EltIdx]) {
6552       // The zero vector will be on the right hand side.
6553       Mask[EltIdx] = EltIdx+4;
6554       continue;
6555     }
6556 
6557     Elt = Op->getOperand(EltIdx);
6558     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
6559     EltMaskIdx = Elt.getConstantOperandVal(1);
6560     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
6561       break;
6562     Mask[EltIdx] = EltIdx;
6563   }
6564 
6565   if (EltIdx == 4) {
6566     // Let the shuffle legalizer deal with blend operations.
6567     SDValue VZeroOrUndef = (Zeroable == Undefs)
6568                                ? DAG.getUNDEF(VT)
6569                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
6570     if (V1.getSimpleValueType() != VT)
6571       V1 = DAG.getBitcast(VT, V1);
6572     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
6573   }
6574 
6575   // See if we can lower this build_vector to a INSERTPS.
6576   if (!Subtarget.hasSSE41())
6577     return SDValue();
6578 
6579   SDValue V2 = Elt.getOperand(0);
6580   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
6581     V1 = SDValue();
6582 
6583   bool CanFold = true;
6584   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
6585     if (Zeroable[i])
6586       continue;
6587 
6588     SDValue Current = Op->getOperand(i);
6589     SDValue SrcVector = Current->getOperand(0);
6590     if (!V1.getNode())
6591       V1 = SrcVector;
6592     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
6593   }
6594 
6595   if (!CanFold)
6596     return SDValue();
6597 
6598   assert(V1.getNode() && "Expected at least two non-zero elements!");
6599   if (V1.getSimpleValueType() != MVT::v4f32)
6600     V1 = DAG.getBitcast(MVT::v4f32, V1);
6601   if (V2.getSimpleValueType() != MVT::v4f32)
6602     V2 = DAG.getBitcast(MVT::v4f32, V2);
6603 
6604   // Ok, we can emit an INSERTPS instruction.
6605   unsigned ZMask = Zeroable.to_ulong();
6606 
6607   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
6608   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
6609   SDLoc DL(Op);
6610   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
6611                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
6612   return DAG.getBitcast(VT, Result);
6613 }
6614 
6615 /// Return a vector logical shift node.
getVShift(bool isLeft,EVT VT,SDValue SrcOp,unsigned NumBits,SelectionDAG & DAG,const TargetLowering & TLI,const SDLoc & dl)6616 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
6617                          SelectionDAG &DAG, const TargetLowering &TLI,
6618                          const SDLoc &dl) {
6619   assert(VT.is128BitVector() && "Unknown type for VShift");
6620   MVT ShVT = MVT::v16i8;
6621   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
6622   SrcOp = DAG.getBitcast(ShVT, SrcOp);
6623   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
6624   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
6625   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
6626 }
6627 
LowerAsSplatVectorLoad(SDValue SrcOp,MVT VT,const SDLoc & dl,SelectionDAG & DAG)6628 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
6629                                       SelectionDAG &DAG) {
6630 
6631   // Check if the scalar load can be widened into a vector load. And if
6632   // the address is "base + cst" see if the cst can be "absorbed" into
6633   // the shuffle mask.
6634   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
6635     SDValue Ptr = LD->getBasePtr();
6636     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
6637       return SDValue();
6638     EVT PVT = LD->getValueType(0);
6639     if (PVT != MVT::i32 && PVT != MVT::f32)
6640       return SDValue();
6641 
6642     int FI = -1;
6643     int64_t Offset = 0;
6644     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
6645       FI = FINode->getIndex();
6646       Offset = 0;
6647     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
6648                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6649       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6650       Offset = Ptr.getConstantOperandVal(1);
6651       Ptr = Ptr.getOperand(0);
6652     } else {
6653       return SDValue();
6654     }
6655 
6656     // FIXME: 256-bit vector instructions don't require a strict alignment,
6657     // improve this code to support it better.
6658     Align RequiredAlign(VT.getSizeInBits() / 8);
6659     SDValue Chain = LD->getChain();
6660     // Make sure the stack object alignment is at least 16 or 32.
6661     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6662     MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
6663     if (!InferredAlign || *InferredAlign < RequiredAlign) {
6664       if (MFI.isFixedObjectIndex(FI)) {
6665         // Can't change the alignment. FIXME: It's possible to compute
6666         // the exact stack offset and reference FI + adjust offset instead.
6667         // If someone *really* cares about this. That's the way to implement it.
6668         return SDValue();
6669       } else {
6670         MFI.setObjectAlignment(FI, RequiredAlign);
6671       }
6672     }
6673 
6674     // (Offset % 16 or 32) must be multiple of 4. Then address is then
6675     // Ptr + (Offset & ~15).
6676     if (Offset < 0)
6677       return SDValue();
6678     if ((Offset % RequiredAlign.value()) & 3)
6679       return SDValue();
6680     int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
6681     if (StartOffset) {
6682       SDLoc DL(Ptr);
6683       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6684                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
6685     }
6686 
6687     int EltNo = (Offset - StartOffset) >> 2;
6688     unsigned NumElems = VT.getVectorNumElements();
6689 
6690     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
6691     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
6692                              LD->getPointerInfo().getWithOffset(StartOffset));
6693 
6694     SmallVector<int, 8> Mask(NumElems, EltNo);
6695 
6696     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
6697   }
6698 
6699   return SDValue();
6700 }
6701 
6702 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
findEltLoadSrc(SDValue Elt,LoadSDNode * & Ld,int64_t & ByteOffset)6703 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
6704   if (ISD::isNON_EXTLoad(Elt.getNode())) {
6705     auto *BaseLd = cast<LoadSDNode>(Elt);
6706     if (!BaseLd->isSimple())
6707       return false;
6708     Ld = BaseLd;
6709     ByteOffset = 0;
6710     return true;
6711   }
6712 
6713   switch (Elt.getOpcode()) {
6714   case ISD::BITCAST:
6715   case ISD::TRUNCATE:
6716   case ISD::SCALAR_TO_VECTOR:
6717     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
6718   case ISD::SRL:
6719     if (auto *AmtC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
6720       uint64_t Amt = AmtC->getZExtValue();
6721       if ((Amt % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
6722         ByteOffset += Amt / 8;
6723         return true;
6724       }
6725     }
6726     break;
6727   case ISD::EXTRACT_VECTOR_ELT:
6728     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
6729       SDValue Src = Elt.getOperand(0);
6730       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
6731       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
6732       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
6733           findEltLoadSrc(Src, Ld, ByteOffset)) {
6734         uint64_t Idx = IdxC->getZExtValue();
6735         ByteOffset += Idx * (SrcSizeInBits / 8);
6736         return true;
6737       }
6738     }
6739     break;
6740   }
6741 
6742   return false;
6743 }
6744 
6745 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
6746 /// elements can be replaced by a single large load which has the same value as
6747 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
6748 ///
6749 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
EltsFromConsecutiveLoads(EVT VT,ArrayRef<SDValue> Elts,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool IsAfterLegalize)6750 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
6751                                         const SDLoc &DL, SelectionDAG &DAG,
6752                                         const X86Subtarget &Subtarget,
6753                                         bool IsAfterLegalize) {
6754   if ((VT.getScalarSizeInBits() % 8) != 0)
6755     return SDValue();
6756 
6757   unsigned NumElems = Elts.size();
6758 
6759   int LastLoadedElt = -1;
6760   APInt LoadMask = APInt::getZero(NumElems);
6761   APInt ZeroMask = APInt::getZero(NumElems);
6762   APInt UndefMask = APInt::getZero(NumElems);
6763 
6764   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
6765   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
6766 
6767   // For each element in the initializer, see if we've found a load, zero or an
6768   // undef.
6769   for (unsigned i = 0; i < NumElems; ++i) {
6770     SDValue Elt = peekThroughBitcasts(Elts[i]);
6771     if (!Elt.getNode())
6772       return SDValue();
6773     if (Elt.isUndef()) {
6774       UndefMask.setBit(i);
6775       continue;
6776     }
6777     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
6778       ZeroMask.setBit(i);
6779       continue;
6780     }
6781 
6782     // Each loaded element must be the correct fractional portion of the
6783     // requested vector load.
6784     unsigned EltSizeInBits = Elt.getValueSizeInBits();
6785     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
6786       return SDValue();
6787 
6788     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
6789       return SDValue();
6790     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
6791     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
6792       return SDValue();
6793 
6794     LoadMask.setBit(i);
6795     LastLoadedElt = i;
6796   }
6797   assert((ZeroMask.popcount() + UndefMask.popcount() + LoadMask.popcount()) ==
6798              NumElems &&
6799          "Incomplete element masks");
6800 
6801   // Handle Special Cases - all undef or undef/zero.
6802   if (UndefMask.popcount() == NumElems)
6803     return DAG.getUNDEF(VT);
6804   if ((ZeroMask.popcount() + UndefMask.popcount()) == NumElems)
6805     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
6806                           : DAG.getConstantFP(0.0, DL, VT);
6807 
6808   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6809   int FirstLoadedElt = LoadMask.countr_zero();
6810   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
6811   EVT EltBaseVT = EltBase.getValueType();
6812   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
6813          "Register/Memory size mismatch");
6814   LoadSDNode *LDBase = Loads[FirstLoadedElt];
6815   assert(LDBase && "Did not find base load for merging consecutive loads");
6816   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
6817   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
6818   int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
6819   int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
6820   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
6821 
6822   // TODO: Support offsetting the base load.
6823   if (ByteOffsets[FirstLoadedElt] != 0)
6824     return SDValue();
6825 
6826   // Check to see if the element's load is consecutive to the base load
6827   // or offset from a previous (already checked) load.
6828   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
6829     LoadSDNode *Ld = Loads[EltIdx];
6830     int64_t ByteOffset = ByteOffsets[EltIdx];
6831     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
6832       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
6833       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
6834               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
6835     }
6836     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
6837                                               EltIdx - FirstLoadedElt);
6838   };
6839 
6840   // Consecutive loads can contain UNDEFS but not ZERO elements.
6841   // Consecutive loads with UNDEFs and ZEROs elements require a
6842   // an additional shuffle stage to clear the ZERO elements.
6843   bool IsConsecutiveLoad = true;
6844   bool IsConsecutiveLoadWithZeros = true;
6845   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
6846     if (LoadMask[i]) {
6847       if (!CheckConsecutiveLoad(LDBase, i)) {
6848         IsConsecutiveLoad = false;
6849         IsConsecutiveLoadWithZeros = false;
6850         break;
6851       }
6852     } else if (ZeroMask[i]) {
6853       IsConsecutiveLoad = false;
6854     }
6855   }
6856 
6857   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
6858     auto MMOFlags = LDBase->getMemOperand()->getFlags();
6859     assert(LDBase->isSimple() &&
6860            "Cannot merge volatile or atomic loads.");
6861     SDValue NewLd =
6862         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6863                     LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
6864                     MMOFlags);
6865     for (auto *LD : Loads)
6866       if (LD)
6867         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
6868     return NewLd;
6869   };
6870 
6871   // Check if the base load is entirely dereferenceable.
6872   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
6873       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
6874 
6875   // LOAD - all consecutive load/undefs (must start/end with a load or be
6876   // entirely dereferenceable). If we have found an entire vector of loads and
6877   // undefs, then return a large load of the entire vector width starting at the
6878   // base pointer. If the vector contains zeros, then attempt to shuffle those
6879   // elements.
6880   if (FirstLoadedElt == 0 &&
6881       (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
6882       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
6883     if (IsAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
6884       return SDValue();
6885 
6886     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
6887     // will lower to regular temporal loads and use the cache.
6888     if (LDBase->isNonTemporal() && LDBase->getAlign() >= Align(32) &&
6889         VT.is256BitVector() && !Subtarget.hasInt256())
6890       return SDValue();
6891 
6892     if (NumElems == 1)
6893       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
6894 
6895     if (!ZeroMask)
6896       return CreateLoad(VT, LDBase);
6897 
6898     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
6899     // vector and a zero vector to clear out the zero elements.
6900     if (!IsAfterLegalize && VT.isVector()) {
6901       unsigned NumMaskElts = VT.getVectorNumElements();
6902       if ((NumMaskElts % NumElems) == 0) {
6903         unsigned Scale = NumMaskElts / NumElems;
6904         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
6905         for (unsigned i = 0; i < NumElems; ++i) {
6906           if (UndefMask[i])
6907             continue;
6908           int Offset = ZeroMask[i] ? NumMaskElts : 0;
6909           for (unsigned j = 0; j != Scale; ++j)
6910             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
6911         }
6912         SDValue V = CreateLoad(VT, LDBase);
6913         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
6914                                    : DAG.getConstantFP(0.0, DL, VT);
6915         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
6916       }
6917     }
6918   }
6919 
6920   // If the upper half of a ymm/zmm load is undef then just load the lower half.
6921   if (VT.is256BitVector() || VT.is512BitVector()) {
6922     unsigned HalfNumElems = NumElems / 2;
6923     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnes()) {
6924       EVT HalfVT =
6925           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
6926       SDValue HalfLD =
6927           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
6928                                    DAG, Subtarget, IsAfterLegalize);
6929       if (HalfLD)
6930         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
6931                            HalfLD, DAG.getIntPtrConstant(0, DL));
6932     }
6933   }
6934 
6935   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
6936   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
6937       ((LoadSizeInBits == 16 && Subtarget.hasFP16()) || LoadSizeInBits == 32 ||
6938        LoadSizeInBits == 64) &&
6939       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
6940     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
6941                                       : MVT::getIntegerVT(LoadSizeInBits);
6942     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
6943     // Allow v4f32 on SSE1 only targets.
6944     // FIXME: Add more isel patterns so we can just use VT directly.
6945     if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
6946       VecVT = MVT::v4f32;
6947     if (TLI.isTypeLegal(VecVT)) {
6948       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
6949       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6950       SDValue ResNode = DAG.getMemIntrinsicNode(
6951           X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
6952           LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
6953       for (auto *LD : Loads)
6954         if (LD)
6955           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
6956       return DAG.getBitcast(VT, ResNode);
6957     }
6958   }
6959 
6960   // BROADCAST - match the smallest possible repetition pattern, load that
6961   // scalar/subvector element and then broadcast to the entire vector.
6962   if (ZeroMask.isZero() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
6963       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
6964     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
6965       unsigned RepeatSize = SubElems * BaseSizeInBits;
6966       unsigned ScalarSize = std::min(RepeatSize, 64u);
6967       if (!Subtarget.hasAVX2() && ScalarSize < 32)
6968         continue;
6969 
6970       // Don't attempt a 1:N subvector broadcast - it should be caught by
6971       // combineConcatVectorOps, else will cause infinite loops.
6972       if (RepeatSize > ScalarSize && SubElems == 1)
6973         continue;
6974 
6975       bool Match = true;
6976       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
6977       for (unsigned i = 0; i != NumElems && Match; ++i) {
6978         if (!LoadMask[i])
6979           continue;
6980         SDValue Elt = peekThroughBitcasts(Elts[i]);
6981         if (RepeatedLoads[i % SubElems].isUndef())
6982           RepeatedLoads[i % SubElems] = Elt;
6983         else
6984           Match &= (RepeatedLoads[i % SubElems] == Elt);
6985       }
6986 
6987       // We must have loads at both ends of the repetition.
6988       Match &= !RepeatedLoads.front().isUndef();
6989       Match &= !RepeatedLoads.back().isUndef();
6990       if (!Match)
6991         continue;
6992 
6993       EVT RepeatVT =
6994           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
6995               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
6996               : EVT::getFloatingPointVT(ScalarSize);
6997       if (RepeatSize > ScalarSize)
6998         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
6999                                     RepeatSize / ScalarSize);
7000       EVT BroadcastVT =
7001           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
7002                            VT.getSizeInBits() / ScalarSize);
7003       if (TLI.isTypeLegal(BroadcastVT)) {
7004         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
7005                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, IsAfterLegalize)) {
7006           SDValue Broadcast = RepeatLoad;
7007           if (RepeatSize > ScalarSize) {
7008             while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
7009               Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
7010           } else {
7011             if (!Subtarget.hasAVX2() &&
7012                 !X86::mayFoldLoadIntoBroadcastFromMem(
7013                     RepeatLoad, RepeatVT.getScalarType().getSimpleVT(),
7014                     Subtarget,
7015                     /*AssumeSingleUse=*/true))
7016               return SDValue();
7017             Broadcast =
7018                 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
7019           }
7020           return DAG.getBitcast(VT, Broadcast);
7021         }
7022       }
7023     }
7024   }
7025 
7026   return SDValue();
7027 }
7028 
7029 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
7030 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
7031 // are consecutive, non-overlapping, and in the right order.
combineToConsecutiveLoads(EVT VT,SDValue Op,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool IsAfterLegalize)7032 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
7033                                          SelectionDAG &DAG,
7034                                          const X86Subtarget &Subtarget,
7035                                          bool IsAfterLegalize) {
7036   SmallVector<SDValue, 64> Elts;
7037   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7038     if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
7039       Elts.push_back(Elt);
7040       continue;
7041     }
7042     return SDValue();
7043   }
7044   assert(Elts.size() == VT.getVectorNumElements());
7045   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
7046                                   IsAfterLegalize);
7047 }
7048 
getConstantVector(MVT VT,ArrayRef<APInt> Bits,const APInt & Undefs,LLVMContext & C)7049 static Constant *getConstantVector(MVT VT, ArrayRef<APInt> Bits,
7050                                    const APInt &Undefs, LLVMContext &C) {
7051   unsigned ScalarSize = VT.getScalarSizeInBits();
7052   Type *Ty = EVT(VT.getScalarType()).getTypeForEVT(C);
7053 
7054   auto getConstantScalar = [&](const APInt &Val) -> Constant * {
7055     if (VT.isFloatingPoint()) {
7056       if (ScalarSize == 16)
7057         return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
7058       if (ScalarSize == 32)
7059         return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
7060       assert(ScalarSize == 64 && "Unsupported floating point scalar size");
7061       return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
7062     }
7063     return Constant::getIntegerValue(Ty, Val);
7064   };
7065 
7066   SmallVector<Constant *, 32> ConstantVec;
7067   for (unsigned I = 0, E = Bits.size(); I != E; ++I)
7068     ConstantVec.push_back(Undefs[I] ? UndefValue::get(Ty)
7069                                     : getConstantScalar(Bits[I]));
7070 
7071   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
7072 }
7073 
getConstantVector(MVT VT,const APInt & SplatValue,unsigned SplatBitSize,LLVMContext & C)7074 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
7075                                    unsigned SplatBitSize, LLVMContext &C) {
7076   unsigned ScalarSize = VT.getScalarSizeInBits();
7077 
7078   auto getConstantScalar = [&](const APInt &Val) -> Constant * {
7079     if (VT.isFloatingPoint()) {
7080       if (ScalarSize == 16)
7081         return ConstantFP::get(C, APFloat(APFloat::IEEEhalf(), Val));
7082       if (ScalarSize == 32)
7083         return ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
7084       assert(ScalarSize == 64 && "Unsupported floating point scalar size");
7085       return ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
7086     }
7087     return Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
7088   };
7089 
7090   if (ScalarSize == SplatBitSize)
7091     return getConstantScalar(SplatValue);
7092 
7093   unsigned NumElm = SplatBitSize / ScalarSize;
7094   SmallVector<Constant *, 32> ConstantVec;
7095   for (unsigned I = 0; I != NumElm; ++I) {
7096     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * I);
7097     ConstantVec.push_back(getConstantScalar(Val));
7098   }
7099   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
7100 }
7101 
isFoldableUseOfShuffle(SDNode * N)7102 static bool isFoldableUseOfShuffle(SDNode *N) {
7103   for (auto *U : N->uses()) {
7104     unsigned Opc = U->getOpcode();
7105     // VPERMV/VPERMV3 shuffles can never fold their index operands.
7106     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
7107       return false;
7108     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
7109       return false;
7110     if (isTargetShuffle(Opc))
7111       return true;
7112     if (Opc == ISD::BITCAST) // Ignore bitcasts
7113       return isFoldableUseOfShuffle(U);
7114     if (N->hasOneUse()) {
7115       // TODO, there may be some general way to know if a SDNode can
7116       // be folded. We now only know whether an MI is foldable.
7117       if (Opc == X86ISD::VPDPBUSD && U->getOperand(2).getNode() != N)
7118         return false;
7119       return true;
7120     }
7121   }
7122   return false;
7123 }
7124 
7125 /// Attempt to use the vbroadcast instruction to generate a splat value
7126 /// from a splat BUILD_VECTOR which uses:
7127 ///  a. A single scalar load, or a constant.
7128 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
7129 ///
7130 /// The VBROADCAST node is returned when a pattern is found,
7131 /// or SDValue() otherwise.
lowerBuildVectorAsBroadcast(BuildVectorSDNode * BVOp,const X86Subtarget & Subtarget,SelectionDAG & DAG)7132 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
7133                                            const X86Subtarget &Subtarget,
7134                                            SelectionDAG &DAG) {
7135   // VBROADCAST requires AVX.
7136   // TODO: Splats could be generated for non-AVX CPUs using SSE
7137   // instructions, but there's less potential gain for only 128-bit vectors.
7138   if (!Subtarget.hasAVX())
7139     return SDValue();
7140 
7141   MVT VT = BVOp->getSimpleValueType(0);
7142   unsigned NumElts = VT.getVectorNumElements();
7143   SDLoc dl(BVOp);
7144 
7145   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
7146          "Unsupported vector type for broadcast.");
7147 
7148   // See if the build vector is a repeating sequence of scalars (inc. splat).
7149   SDValue Ld;
7150   BitVector UndefElements;
7151   SmallVector<SDValue, 16> Sequence;
7152   if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
7153     assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
7154     if (Sequence.size() == 1)
7155       Ld = Sequence[0];
7156   }
7157 
7158   // Attempt to use VBROADCASTM
7159   // From this pattern:
7160   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
7161   // b. t1 = (build_vector t0 t0)
7162   //
7163   // Create (VBROADCASTM v2i1 X)
7164   if (!Sequence.empty() && Subtarget.hasCDI()) {
7165     // If not a splat, are the upper sequence values zeroable?
7166     unsigned SeqLen = Sequence.size();
7167     bool UpperZeroOrUndef =
7168         SeqLen == 1 ||
7169         llvm::all_of(ArrayRef(Sequence).drop_front(), [](SDValue V) {
7170           return !V || V.isUndef() || isNullConstant(V);
7171         });
7172     SDValue Op0 = Sequence[0];
7173     if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
7174                              (Op0.getOpcode() == ISD::ZERO_EXTEND &&
7175                               Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
7176       SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
7177                              ? Op0.getOperand(0)
7178                              : Op0.getOperand(0).getOperand(0);
7179       MVT MaskVT = BOperand.getSimpleValueType();
7180       MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
7181       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) ||  // for broadcastmb2q
7182           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
7183         MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
7184         if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
7185           unsigned Scale = 512 / VT.getSizeInBits();
7186           BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
7187         }
7188         SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
7189         if (BcstVT.getSizeInBits() != VT.getSizeInBits())
7190           Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
7191         return DAG.getBitcast(VT, Bcst);
7192       }
7193     }
7194   }
7195 
7196   unsigned NumUndefElts = UndefElements.count();
7197   if (!Ld || (NumElts - NumUndefElts) <= 1) {
7198     APInt SplatValue, Undef;
7199     unsigned SplatBitSize;
7200     bool HasUndef;
7201     // Check if this is a repeated constant pattern suitable for broadcasting.
7202     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
7203         SplatBitSize > VT.getScalarSizeInBits() &&
7204         SplatBitSize < VT.getSizeInBits()) {
7205       // Avoid replacing with broadcast when it's a use of a shuffle
7206       // instruction to preserve the present custom lowering of shuffles.
7207       if (isFoldableUseOfShuffle(BVOp))
7208         return SDValue();
7209       // replace BUILD_VECTOR with broadcast of the repeated constants.
7210       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7211       LLVMContext *Ctx = DAG.getContext();
7212       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
7213       if (SplatBitSize == 32 || SplatBitSize == 64 ||
7214           (SplatBitSize < 32 && Subtarget.hasAVX2())) {
7215         // Load the constant scalar/subvector and broadcast it.
7216         MVT CVT = MVT::getIntegerVT(SplatBitSize);
7217         Constant *C = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
7218         SDValue CP = DAG.getConstantPool(C, PVT);
7219         unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
7220 
7221         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
7222         SDVTList Tys = DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
7223         SDValue Ops[] = {DAG.getEntryNode(), CP};
7224         MachinePointerInfo MPI =
7225             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
7226         SDValue Brdcst =
7227             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
7228                                     MPI, Alignment, MachineMemOperand::MOLoad);
7229         return DAG.getBitcast(VT, Brdcst);
7230       }
7231       if (SplatBitSize > 64) {
7232         // Load the vector of constants and broadcast it.
7233         Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize, *Ctx);
7234         SDValue VCP = DAG.getConstantPool(VecC, PVT);
7235         unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
7236         MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
7237         Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
7238         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7239         SDValue Ops[] = {DAG.getEntryNode(), VCP};
7240         MachinePointerInfo MPI =
7241             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
7242         return DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, dl, Tys,
7243                                        Ops, VVT, MPI, Alignment,
7244                                        MachineMemOperand::MOLoad);
7245       }
7246     }
7247 
7248     // If we are moving a scalar into a vector (Ld must be set and all elements
7249     // but 1 are undef) and that operation is not obviously supported by
7250     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
7251     // That's better than general shuffling and may eliminate a load to GPR and
7252     // move from scalar to vector register.
7253     if (!Ld || NumElts - NumUndefElts != 1)
7254       return SDValue();
7255     unsigned ScalarSize = Ld.getValueSizeInBits();
7256     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
7257       return SDValue();
7258   }
7259 
7260   bool ConstSplatVal =
7261       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
7262   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
7263 
7264   // TODO: Handle broadcasts of non-constant sequences.
7265 
7266   // Make sure that all of the users of a non-constant load are from the
7267   // BUILD_VECTOR node.
7268   // FIXME: Is the use count needed for non-constant, non-load case?
7269   if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
7270     return SDValue();
7271 
7272   unsigned ScalarSize = Ld.getValueSizeInBits();
7273   bool IsGE256 = (VT.getSizeInBits() >= 256);
7274 
7275   // When optimizing for size, generate up to 5 extra bytes for a broadcast
7276   // instruction to save 8 or more bytes of constant pool data.
7277   // TODO: If multiple splats are generated to load the same constant,
7278   // it may be detrimental to overall size. There needs to be a way to detect
7279   // that condition to know if this is truly a size win.
7280   bool OptForSize = DAG.shouldOptForSize();
7281 
7282   // Handle broadcasting a single constant scalar from the constant pool
7283   // into a vector.
7284   // On Sandybridge (no AVX2), it is still better to load a constant vector
7285   // from the constant pool and not to broadcast it from a scalar.
7286   // But override that restriction when optimizing for size.
7287   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
7288   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
7289     EVT CVT = Ld.getValueType();
7290     assert(!CVT.isVector() && "Must not broadcast a vector type");
7291 
7292     // Splat f16, f32, i32, v4f64, v4i64 in all cases with AVX2.
7293     // For size optimization, also splat v2f64 and v2i64, and for size opt
7294     // with AVX2, also splat i8 and i16.
7295     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
7296     if (ScalarSize == 32 ||
7297         (ScalarSize == 64 && (IsGE256 || Subtarget.hasVLX())) ||
7298         CVT == MVT::f16 ||
7299         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
7300       const Constant *C = nullptr;
7301       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
7302         C = CI->getConstantIntValue();
7303       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
7304         C = CF->getConstantFPValue();
7305 
7306       assert(C && "Invalid constant type");
7307 
7308       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7309       SDValue CP =
7310           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
7311       Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
7312 
7313       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7314       SDValue Ops[] = {DAG.getEntryNode(), CP};
7315       MachinePointerInfo MPI =
7316           MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
7317       return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
7318                                      MPI, Alignment, MachineMemOperand::MOLoad);
7319     }
7320   }
7321 
7322   // Handle AVX2 in-register broadcasts.
7323   if (!IsLoad && Subtarget.hasInt256() &&
7324       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
7325     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7326 
7327   // The scalar source must be a normal load.
7328   if (!IsLoad)
7329     return SDValue();
7330 
7331   // Make sure the non-chain result is only used by this build vector.
7332   if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
7333     return SDValue();
7334 
7335   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
7336       (Subtarget.hasVLX() && ScalarSize == 64)) {
7337     auto *LN = cast<LoadSDNode>(Ld);
7338     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7339     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
7340     SDValue BCast =
7341         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
7342                                 LN->getMemoryVT(), LN->getMemOperand());
7343     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
7344     return BCast;
7345   }
7346 
7347   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
7348   // double since there is no vbroadcastsd xmm
7349   if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
7350       (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
7351     auto *LN = cast<LoadSDNode>(Ld);
7352     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7353     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
7354     SDValue BCast =
7355         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
7356                                 LN->getMemoryVT(), LN->getMemOperand());
7357     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
7358     return BCast;
7359   }
7360 
7361   if (ScalarSize == 16 && Subtarget.hasFP16() && IsGE256)
7362     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7363 
7364   // Unsupported broadcast.
7365   return SDValue();
7366 }
7367 
7368 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
7369 /// underlying vector and index.
7370 ///
7371 /// Modifies \p ExtractedFromVec to the real vector and returns the real
7372 /// index.
getUnderlyingExtractedFromVec(SDValue & ExtractedFromVec,SDValue ExtIdx)7373 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
7374                                          SDValue ExtIdx) {
7375   int Idx = ExtIdx->getAsZExtVal();
7376   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
7377     return Idx;
7378 
7379   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
7380   // lowered this:
7381   //   (extract_vector_elt (v8f32 %1), Constant<6>)
7382   // to:
7383   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
7384   //                           (extract_subvector (v8f32 %0), Constant<4>),
7385   //                           undef)
7386   //                       Constant<0>)
7387   // In this case the vector is the extract_subvector expression and the index
7388   // is 2, as specified by the shuffle.
7389   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
7390   SDValue ShuffleVec = SVOp->getOperand(0);
7391   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
7392   assert(ShuffleVecVT.getVectorElementType() ==
7393          ExtractedFromVec.getSimpleValueType().getVectorElementType());
7394 
7395   int ShuffleIdx = SVOp->getMaskElt(Idx);
7396   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
7397     ExtractedFromVec = ShuffleVec;
7398     return ShuffleIdx;
7399   }
7400   return Idx;
7401 }
7402 
buildFromShuffleMostly(SDValue Op,SelectionDAG & DAG)7403 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
7404   MVT VT = Op.getSimpleValueType();
7405 
7406   // Skip if insert_vec_elt is not supported.
7407   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7408   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
7409     return SDValue();
7410 
7411   SDLoc DL(Op);
7412   unsigned NumElems = Op.getNumOperands();
7413 
7414   SDValue VecIn1;
7415   SDValue VecIn2;
7416   SmallVector<unsigned, 4> InsertIndices;
7417   SmallVector<int, 8> Mask(NumElems, -1);
7418 
7419   for (unsigned i = 0; i != NumElems; ++i) {
7420     unsigned Opc = Op.getOperand(i).getOpcode();
7421 
7422     if (Opc == ISD::UNDEF)
7423       continue;
7424 
7425     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
7426       // Quit if more than 1 elements need inserting.
7427       if (InsertIndices.size() > 1)
7428         return SDValue();
7429 
7430       InsertIndices.push_back(i);
7431       continue;
7432     }
7433 
7434     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
7435     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
7436 
7437     // Quit if non-constant index.
7438     if (!isa<ConstantSDNode>(ExtIdx))
7439       return SDValue();
7440     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
7441 
7442     // Quit if extracted from vector of different type.
7443     if (ExtractedFromVec.getValueType() != VT)
7444       return SDValue();
7445 
7446     if (!VecIn1.getNode())
7447       VecIn1 = ExtractedFromVec;
7448     else if (VecIn1 != ExtractedFromVec) {
7449       if (!VecIn2.getNode())
7450         VecIn2 = ExtractedFromVec;
7451       else if (VecIn2 != ExtractedFromVec)
7452         // Quit if more than 2 vectors to shuffle
7453         return SDValue();
7454     }
7455 
7456     if (ExtractedFromVec == VecIn1)
7457       Mask[i] = Idx;
7458     else if (ExtractedFromVec == VecIn2)
7459       Mask[i] = Idx + NumElems;
7460   }
7461 
7462   if (!VecIn1.getNode())
7463     return SDValue();
7464 
7465   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7466   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
7467 
7468   for (unsigned Idx : InsertIndices)
7469     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
7470                      DAG.getIntPtrConstant(Idx, DL));
7471 
7472   return NV;
7473 }
7474 
7475 // Lower BUILD_VECTOR operation for v8bf16, v16bf16 and v32bf16 types.
LowerBUILD_VECTORvXbf16(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)7476 static SDValue LowerBUILD_VECTORvXbf16(SDValue Op, SelectionDAG &DAG,
7477                                        const X86Subtarget &Subtarget) {
7478   MVT VT = Op.getSimpleValueType();
7479   MVT IVT =
7480       VT.changeVectorElementType(Subtarget.hasFP16() ? MVT::f16 : MVT::i16);
7481   SmallVector<SDValue, 16> NewOps;
7482   for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I)
7483     NewOps.push_back(DAG.getBitcast(Subtarget.hasFP16() ? MVT::f16 : MVT::i16,
7484                                     Op.getOperand(I)));
7485   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(), IVT, NewOps);
7486   return DAG.getBitcast(VT, Res);
7487 }
7488 
7489 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
LowerBUILD_VECTORvXi1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)7490 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
7491                                      const X86Subtarget &Subtarget) {
7492 
7493   MVT VT = Op.getSimpleValueType();
7494   assert((VT.getVectorElementType() == MVT::i1) &&
7495          "Unexpected type in LowerBUILD_VECTORvXi1!");
7496 
7497   SDLoc dl(Op);
7498   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
7499       ISD::isBuildVectorAllOnes(Op.getNode()))
7500     return Op;
7501 
7502   uint64_t Immediate = 0;
7503   SmallVector<unsigned, 16> NonConstIdx;
7504   bool IsSplat = true;
7505   bool HasConstElts = false;
7506   int SplatIdx = -1;
7507   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
7508     SDValue In = Op.getOperand(idx);
7509     if (In.isUndef())
7510       continue;
7511     if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
7512       Immediate |= (InC->getZExtValue() & 0x1) << idx;
7513       HasConstElts = true;
7514     } else {
7515       NonConstIdx.push_back(idx);
7516     }
7517     if (SplatIdx < 0)
7518       SplatIdx = idx;
7519     else if (In != Op.getOperand(SplatIdx))
7520       IsSplat = false;
7521   }
7522 
7523   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
7524   if (IsSplat) {
7525     // The build_vector allows the scalar element to be larger than the vector
7526     // element type. We need to mask it to use as a condition unless we know
7527     // the upper bits are zero.
7528     // FIXME: Use computeKnownBits instead of checking specific opcode?
7529     SDValue Cond = Op.getOperand(SplatIdx);
7530     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
7531     if (Cond.getOpcode() != ISD::SETCC)
7532       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
7533                          DAG.getConstant(1, dl, MVT::i8));
7534 
7535     // Perform the select in the scalar domain so we can use cmov.
7536     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
7537       SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
7538                                      DAG.getAllOnesConstant(dl, MVT::i32),
7539                                      DAG.getConstant(0, dl, MVT::i32));
7540       Select = DAG.getBitcast(MVT::v32i1, Select);
7541       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
7542     } else {
7543       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
7544       SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
7545                                      DAG.getAllOnesConstant(dl, ImmVT),
7546                                      DAG.getConstant(0, dl, ImmVT));
7547       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
7548       Select = DAG.getBitcast(VecVT, Select);
7549       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
7550                          DAG.getIntPtrConstant(0, dl));
7551     }
7552   }
7553 
7554   // insert elements one by one
7555   SDValue DstVec;
7556   if (HasConstElts) {
7557     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
7558       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
7559       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
7560       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
7561       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
7562       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
7563     } else {
7564       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
7565       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
7566       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
7567       DstVec = DAG.getBitcast(VecVT, Imm);
7568       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
7569                            DAG.getIntPtrConstant(0, dl));
7570     }
7571   } else
7572     DstVec = DAG.getUNDEF(VT);
7573 
7574   for (unsigned InsertIdx : NonConstIdx) {
7575     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7576                          Op.getOperand(InsertIdx),
7577                          DAG.getIntPtrConstant(InsertIdx, dl));
7578   }
7579   return DstVec;
7580 }
7581 
isHorizOp(unsigned Opcode)7582 LLVM_ATTRIBUTE_UNUSED static bool isHorizOp(unsigned Opcode) {
7583   switch (Opcode) {
7584   case X86ISD::PACKSS:
7585   case X86ISD::PACKUS:
7586   case X86ISD::FHADD:
7587   case X86ISD::FHSUB:
7588   case X86ISD::HADD:
7589   case X86ISD::HSUB:
7590     return true;
7591   }
7592   return false;
7593 }
7594 
7595 /// This is a helper function of LowerToHorizontalOp().
7596 /// This function checks that the build_vector \p N in input implements a
7597 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
7598 /// may not match the layout of an x86 256-bit horizontal instruction.
7599 /// In other words, if this returns true, then some extraction/insertion will
7600 /// be required to produce a valid horizontal instruction.
7601 ///
7602 /// Parameter \p Opcode defines the kind of horizontal operation to match.
7603 /// For example, if \p Opcode is equal to ISD::ADD, then this function
7604 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
7605 /// is equal to ISD::SUB, then this function checks if this is a horizontal
7606 /// arithmetic sub.
7607 ///
7608 /// This function only analyzes elements of \p N whose indices are
7609 /// in range [BaseIdx, LastIdx).
7610 ///
7611 /// TODO: This function was originally used to match both real and fake partial
7612 /// horizontal operations, but the index-matching logic is incorrect for that.
7613 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
7614 /// code because it is only used for partial h-op matching now?
isHorizontalBinOpPart(const BuildVectorSDNode * N,unsigned Opcode,SelectionDAG & DAG,unsigned BaseIdx,unsigned LastIdx,SDValue & V0,SDValue & V1)7615 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
7616                                   SelectionDAG &DAG,
7617                                   unsigned BaseIdx, unsigned LastIdx,
7618                                   SDValue &V0, SDValue &V1) {
7619   EVT VT = N->getValueType(0);
7620   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
7621   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
7622   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
7623          "Invalid Vector in input!");
7624 
7625   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
7626   bool CanFold = true;
7627   unsigned ExpectedVExtractIdx = BaseIdx;
7628   unsigned NumElts = LastIdx - BaseIdx;
7629   V0 = DAG.getUNDEF(VT);
7630   V1 = DAG.getUNDEF(VT);
7631 
7632   // Check if N implements a horizontal binop.
7633   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
7634     SDValue Op = N->getOperand(i + BaseIdx);
7635 
7636     // Skip UNDEFs.
7637     if (Op->isUndef()) {
7638       // Update the expected vector extract index.
7639       if (i * 2 == NumElts)
7640         ExpectedVExtractIdx = BaseIdx;
7641       ExpectedVExtractIdx += 2;
7642       continue;
7643     }
7644 
7645     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
7646 
7647     if (!CanFold)
7648       break;
7649 
7650     SDValue Op0 = Op.getOperand(0);
7651     SDValue Op1 = Op.getOperand(1);
7652 
7653     // Try to match the following pattern:
7654     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
7655     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7656         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7657         Op0.getOperand(0) == Op1.getOperand(0) &&
7658         isa<ConstantSDNode>(Op0.getOperand(1)) &&
7659         isa<ConstantSDNode>(Op1.getOperand(1)));
7660     if (!CanFold)
7661       break;
7662 
7663     unsigned I0 = Op0.getConstantOperandVal(1);
7664     unsigned I1 = Op1.getConstantOperandVal(1);
7665 
7666     if (i * 2 < NumElts) {
7667       if (V0.isUndef()) {
7668         V0 = Op0.getOperand(0);
7669         if (V0.getValueType() != VT)
7670           return false;
7671       }
7672     } else {
7673       if (V1.isUndef()) {
7674         V1 = Op0.getOperand(0);
7675         if (V1.getValueType() != VT)
7676           return false;
7677       }
7678       if (i * 2 == NumElts)
7679         ExpectedVExtractIdx = BaseIdx;
7680     }
7681 
7682     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
7683     if (I0 == ExpectedVExtractIdx)
7684       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
7685     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
7686       // Try to match the following dag sequence:
7687       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
7688       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
7689     } else
7690       CanFold = false;
7691 
7692     ExpectedVExtractIdx += 2;
7693   }
7694 
7695   return CanFold;
7696 }
7697 
7698 /// Emit a sequence of two 128-bit horizontal add/sub followed by
7699 /// a concat_vector.
7700 ///
7701 /// This is a helper function of LowerToHorizontalOp().
7702 /// This function expects two 256-bit vectors called V0 and V1.
7703 /// At first, each vector is split into two separate 128-bit vectors.
7704 /// Then, the resulting 128-bit vectors are used to implement two
7705 /// horizontal binary operations.
7706 ///
7707 /// The kind of horizontal binary operation is defined by \p X86Opcode.
7708 ///
7709 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
7710 /// the two new horizontal binop.
7711 /// When Mode is set, the first horizontal binop dag node would take as input
7712 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
7713 /// horizontal binop dag node would take as input the lower 128-bit of V1
7714 /// and the upper 128-bit of V1.
7715 ///   Example:
7716 ///     HADD V0_LO, V0_HI
7717 ///     HADD V1_LO, V1_HI
7718 ///
7719 /// Otherwise, the first horizontal binop dag node takes as input the lower
7720 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
7721 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
7722 ///   Example:
7723 ///     HADD V0_LO, V1_LO
7724 ///     HADD V0_HI, V1_HI
7725 ///
7726 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
7727 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
7728 /// the upper 128-bits of the result.
ExpandHorizontalBinOp(const SDValue & V0,const SDValue & V1,const SDLoc & DL,SelectionDAG & DAG,unsigned X86Opcode,bool Mode,bool isUndefLO,bool isUndefHI)7729 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
7730                                      const SDLoc &DL, SelectionDAG &DAG,
7731                                      unsigned X86Opcode, bool Mode,
7732                                      bool isUndefLO, bool isUndefHI) {
7733   MVT VT = V0.getSimpleValueType();
7734   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
7735          "Invalid nodes in input!");
7736 
7737   unsigned NumElts = VT.getVectorNumElements();
7738   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
7739   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
7740   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
7741   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
7742   MVT NewVT = V0_LO.getSimpleValueType();
7743 
7744   SDValue LO = DAG.getUNDEF(NewVT);
7745   SDValue HI = DAG.getUNDEF(NewVT);
7746 
7747   if (Mode) {
7748     // Don't emit a horizontal binop if the result is expected to be UNDEF.
7749     if (!isUndefLO && !V0->isUndef())
7750       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
7751     if (!isUndefHI && !V1->isUndef())
7752       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
7753   } else {
7754     // Don't emit a horizontal binop if the result is expected to be UNDEF.
7755     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
7756       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
7757 
7758     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
7759       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
7760   }
7761 
7762   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
7763 }
7764 
7765 /// Returns true iff \p BV builds a vector with the result equivalent to
7766 /// the result of ADDSUB/SUBADD operation.
7767 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
7768 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
7769 /// \p Opnd0 and \p Opnd1.
isAddSubOrSubAdd(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,unsigned & NumExtracts,bool & IsSubAdd)7770 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
7771                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
7772                              SDValue &Opnd0, SDValue &Opnd1,
7773                              unsigned &NumExtracts,
7774                              bool &IsSubAdd) {
7775 
7776   MVT VT = BV->getSimpleValueType(0);
7777   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
7778     return false;
7779 
7780   unsigned NumElts = VT.getVectorNumElements();
7781   SDValue InVec0 = DAG.getUNDEF(VT);
7782   SDValue InVec1 = DAG.getUNDEF(VT);
7783 
7784   NumExtracts = 0;
7785 
7786   // Odd-numbered elements in the input build vector are obtained from
7787   // adding/subtracting two integer/float elements.
7788   // Even-numbered elements in the input build vector are obtained from
7789   // subtracting/adding two integer/float elements.
7790   unsigned Opc[2] = {0, 0};
7791   for (unsigned i = 0, e = NumElts; i != e; ++i) {
7792     SDValue Op = BV->getOperand(i);
7793 
7794     // Skip 'undef' values.
7795     unsigned Opcode = Op.getOpcode();
7796     if (Opcode == ISD::UNDEF)
7797       continue;
7798 
7799     // Early exit if we found an unexpected opcode.
7800     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
7801       return false;
7802 
7803     SDValue Op0 = Op.getOperand(0);
7804     SDValue Op1 = Op.getOperand(1);
7805 
7806     // Try to match the following pattern:
7807     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
7808     // Early exit if we cannot match that sequence.
7809     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7810         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7811         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
7812         Op0.getOperand(1) != Op1.getOperand(1))
7813       return false;
7814 
7815     unsigned I0 = Op0.getConstantOperandVal(1);
7816     if (I0 != i)
7817       return false;
7818 
7819     // We found a valid add/sub node, make sure its the same opcode as previous
7820     // elements for this parity.
7821     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
7822       return false;
7823     Opc[i % 2] = Opcode;
7824 
7825     // Update InVec0 and InVec1.
7826     if (InVec0.isUndef()) {
7827       InVec0 = Op0.getOperand(0);
7828       if (InVec0.getSimpleValueType() != VT)
7829         return false;
7830     }
7831     if (InVec1.isUndef()) {
7832       InVec1 = Op1.getOperand(0);
7833       if (InVec1.getSimpleValueType() != VT)
7834         return false;
7835     }
7836 
7837     // Make sure that operands in input to each add/sub node always
7838     // come from a same pair of vectors.
7839     if (InVec0 != Op0.getOperand(0)) {
7840       if (Opcode == ISD::FSUB)
7841         return false;
7842 
7843       // FADD is commutable. Try to commute the operands
7844       // and then test again.
7845       std::swap(Op0, Op1);
7846       if (InVec0 != Op0.getOperand(0))
7847         return false;
7848     }
7849 
7850     if (InVec1 != Op1.getOperand(0))
7851       return false;
7852 
7853     // Increment the number of extractions done.
7854     ++NumExtracts;
7855   }
7856 
7857   // Ensure we have found an opcode for both parities and that they are
7858   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
7859   // inputs are undef.
7860   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
7861       InVec0.isUndef() || InVec1.isUndef())
7862     return false;
7863 
7864   IsSubAdd = Opc[0] == ISD::FADD;
7865 
7866   Opnd0 = InVec0;
7867   Opnd1 = InVec1;
7868   return true;
7869 }
7870 
7871 /// Returns true if is possible to fold MUL and an idiom that has already been
7872 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
7873 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
7874 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
7875 ///
7876 /// Prior to calling this function it should be known that there is some
7877 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
7878 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
7879 /// before replacement of such SDNode with ADDSUB operation. Thus the number
7880 /// of \p Opnd0 uses is expected to be equal to 2.
7881 /// For example, this function may be called for the following IR:
7882 ///    %AB = fmul fast <2 x double> %A, %B
7883 ///    %Sub = fsub fast <2 x double> %AB, %C
7884 ///    %Add = fadd fast <2 x double> %AB, %C
7885 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
7886 ///                            <2 x i32> <i32 0, i32 3>
7887 /// There is a def for %Addsub here, which potentially can be replaced by
7888 /// X86ISD::ADDSUB operation:
7889 ///    %Addsub = X86ISD::ADDSUB %AB, %C
7890 /// and such ADDSUB can further be replaced with FMADDSUB:
7891 ///    %Addsub = FMADDSUB %A, %B, %C.
7892 ///
7893 /// The main reason why this method is called before the replacement of the
7894 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
7895 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
7896 /// FMADDSUB is.
isFMAddSubOrFMSubAdd(const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,SDValue & Opnd2,unsigned ExpectedUses)7897 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
7898                                  SelectionDAG &DAG,
7899                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
7900                                  unsigned ExpectedUses) {
7901   if (Opnd0.getOpcode() != ISD::FMUL ||
7902       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
7903     return false;
7904 
7905   // FIXME: These checks must match the similar ones in
7906   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
7907   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
7908   // or MUL + ADDSUB to FMADDSUB.
7909   const TargetOptions &Options = DAG.getTarget().Options;
7910   bool AllowFusion =
7911       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7912   if (!AllowFusion)
7913     return false;
7914 
7915   Opnd2 = Opnd1;
7916   Opnd1 = Opnd0.getOperand(1);
7917   Opnd0 = Opnd0.getOperand(0);
7918 
7919   return true;
7920 }
7921 
7922 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
7923 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
7924 /// X86ISD::FMSUBADD node.
lowerToAddSubOrFMAddSub(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)7925 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
7926                                        const X86Subtarget &Subtarget,
7927                                        SelectionDAG &DAG) {
7928   SDValue Opnd0, Opnd1;
7929   unsigned NumExtracts;
7930   bool IsSubAdd;
7931   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
7932                         IsSubAdd))
7933     return SDValue();
7934 
7935   MVT VT = BV->getSimpleValueType(0);
7936   SDLoc DL(BV);
7937 
7938   // Try to generate X86ISD::FMADDSUB node here.
7939   SDValue Opnd2;
7940   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
7941     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
7942     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
7943   }
7944 
7945   // We only support ADDSUB.
7946   if (IsSubAdd)
7947     return SDValue();
7948 
7949   // There are no known X86 targets with 512-bit ADDSUB instructions!
7950   // Convert to blend(fsub,fadd).
7951   if (VT.is512BitVector()) {
7952     SmallVector<int> Mask;
7953     for (int I = 0, E = VT.getVectorNumElements(); I != E; I += 2) {
7954         Mask.push_back(I);
7955         Mask.push_back(I + E + 1);
7956     }
7957     SDValue Sub = DAG.getNode(ISD::FSUB, DL, VT, Opnd0, Opnd1);
7958     SDValue Add = DAG.getNode(ISD::FADD, DL, VT, Opnd0, Opnd1);
7959     return DAG.getVectorShuffle(VT, DL, Sub, Add, Mask);
7960   }
7961 
7962   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
7963 }
7964 
isHopBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned & HOpcode,SDValue & V0,SDValue & V1)7965 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
7966                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
7967   // Initialize outputs to known values.
7968   MVT VT = BV->getSimpleValueType(0);
7969   HOpcode = ISD::DELETED_NODE;
7970   V0 = DAG.getUNDEF(VT);
7971   V1 = DAG.getUNDEF(VT);
7972 
7973   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
7974   // half of the result is calculated independently from the 128-bit halves of
7975   // the inputs, so that makes the index-checking logic below more complicated.
7976   unsigned NumElts = VT.getVectorNumElements();
7977   unsigned GenericOpcode = ISD::DELETED_NODE;
7978   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
7979   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
7980   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
7981   for (unsigned i = 0; i != Num128BitChunks; ++i) {
7982     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
7983       // Ignore undef elements.
7984       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
7985       if (Op.isUndef())
7986         continue;
7987 
7988       // If there's an opcode mismatch, we're done.
7989       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
7990         return false;
7991 
7992       // Initialize horizontal opcode.
7993       if (HOpcode == ISD::DELETED_NODE) {
7994         GenericOpcode = Op.getOpcode();
7995         switch (GenericOpcode) {
7996         case ISD::ADD: HOpcode = X86ISD::HADD; break;
7997         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
7998         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
7999         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
8000         default: return false;
8001         }
8002       }
8003 
8004       SDValue Op0 = Op.getOperand(0);
8005       SDValue Op1 = Op.getOperand(1);
8006       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8007           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8008           Op0.getOperand(0) != Op1.getOperand(0) ||
8009           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8010           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
8011         return false;
8012 
8013       // The source vector is chosen based on which 64-bit half of the
8014       // destination vector is being calculated.
8015       if (j < NumEltsIn64Bits) {
8016         if (V0.isUndef())
8017           V0 = Op0.getOperand(0);
8018       } else {
8019         if (V1.isUndef())
8020           V1 = Op0.getOperand(0);
8021       }
8022 
8023       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
8024       if (SourceVec != Op0.getOperand(0))
8025         return false;
8026 
8027       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
8028       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
8029       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
8030       unsigned ExpectedIndex = i * NumEltsIn128Bits +
8031                                (j % NumEltsIn64Bits) * 2;
8032       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
8033         continue;
8034 
8035       // If this is not a commutative op, this does not match.
8036       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
8037         return false;
8038 
8039       // Addition is commutative, so try swapping the extract indexes.
8040       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
8041       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
8042         continue;
8043 
8044       // Extract indexes do not match horizontal requirement.
8045       return false;
8046     }
8047   }
8048   // We matched. Opcode and operands are returned by reference as arguments.
8049   return true;
8050 }
8051 
getHopForBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned HOpcode,SDValue V0,SDValue V1)8052 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
8053                                     SelectionDAG &DAG, unsigned HOpcode,
8054                                     SDValue V0, SDValue V1) {
8055   // If either input vector is not the same size as the build vector,
8056   // extract/insert the low bits to the correct size.
8057   // This is free (examples: zmm --> xmm, xmm --> ymm).
8058   MVT VT = BV->getSimpleValueType(0);
8059   unsigned Width = VT.getSizeInBits();
8060   if (V0.getValueSizeInBits() > Width)
8061     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
8062   else if (V0.getValueSizeInBits() < Width)
8063     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
8064 
8065   if (V1.getValueSizeInBits() > Width)
8066     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
8067   else if (V1.getValueSizeInBits() < Width)
8068     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
8069 
8070   unsigned NumElts = VT.getVectorNumElements();
8071   APInt DemandedElts = APInt::getAllOnes(NumElts);
8072   for (unsigned i = 0; i != NumElts; ++i)
8073     if (BV->getOperand(i).isUndef())
8074       DemandedElts.clearBit(i);
8075 
8076   // If we don't need the upper xmm, then perform as a xmm hop.
8077   unsigned HalfNumElts = NumElts / 2;
8078   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
8079     MVT HalfVT = VT.getHalfNumVectorElementsVT();
8080     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
8081     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
8082     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
8083     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
8084   }
8085 
8086   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
8087 }
8088 
8089 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
LowerToHorizontalOp(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)8090 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
8091                                    const X86Subtarget &Subtarget,
8092                                    SelectionDAG &DAG) {
8093   // We need at least 2 non-undef elements to make this worthwhile by default.
8094   unsigned NumNonUndefs =
8095       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
8096   if (NumNonUndefs < 2)
8097     return SDValue();
8098 
8099   // There are 4 sets of horizontal math operations distinguished by type:
8100   // int/FP at 128-bit/256-bit. Each type was introduced with a different
8101   // subtarget feature. Try to match those "native" patterns first.
8102   MVT VT = BV->getSimpleValueType(0);
8103   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
8104       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
8105       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
8106       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
8107     unsigned HOpcode;
8108     SDValue V0, V1;
8109     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8110       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
8111   }
8112 
8113   // Try harder to match 256-bit ops by using extract/concat.
8114   if (!Subtarget.hasAVX() || !VT.is256BitVector())
8115     return SDValue();
8116 
8117   // Count the number of UNDEF operands in the build_vector in input.
8118   unsigned NumElts = VT.getVectorNumElements();
8119   unsigned Half = NumElts / 2;
8120   unsigned NumUndefsLO = 0;
8121   unsigned NumUndefsHI = 0;
8122   for (unsigned i = 0, e = Half; i != e; ++i)
8123     if (BV->getOperand(i)->isUndef())
8124       NumUndefsLO++;
8125 
8126   for (unsigned i = Half, e = NumElts; i != e; ++i)
8127     if (BV->getOperand(i)->isUndef())
8128       NumUndefsHI++;
8129 
8130   SDLoc DL(BV);
8131   SDValue InVec0, InVec1;
8132   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
8133     SDValue InVec2, InVec3;
8134     unsigned X86Opcode;
8135     bool CanFold = true;
8136 
8137     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
8138         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
8139                               InVec3) &&
8140         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8141         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8142       X86Opcode = X86ISD::HADD;
8143     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
8144                                    InVec1) &&
8145              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
8146                                    InVec3) &&
8147              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8148              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8149       X86Opcode = X86ISD::HSUB;
8150     else
8151       CanFold = false;
8152 
8153     if (CanFold) {
8154       // Do not try to expand this build_vector into a pair of horizontal
8155       // add/sub if we can emit a pair of scalar add/sub.
8156       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8157         return SDValue();
8158 
8159       // Convert this build_vector into a pair of horizontal binops followed by
8160       // a concat vector. We must adjust the outputs from the partial horizontal
8161       // matching calls above to account for undefined vector halves.
8162       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
8163       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
8164       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
8165       bool isUndefLO = NumUndefsLO == Half;
8166       bool isUndefHI = NumUndefsHI == Half;
8167       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
8168                                    isUndefHI);
8169     }
8170   }
8171 
8172   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
8173       VT == MVT::v16i16) {
8174     unsigned X86Opcode;
8175     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
8176       X86Opcode = X86ISD::HADD;
8177     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
8178                                    InVec1))
8179       X86Opcode = X86ISD::HSUB;
8180     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
8181                                    InVec1))
8182       X86Opcode = X86ISD::FHADD;
8183     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
8184                                    InVec1))
8185       X86Opcode = X86ISD::FHSUB;
8186     else
8187       return SDValue();
8188 
8189     // Don't try to expand this build_vector into a pair of horizontal add/sub
8190     // if we can simply emit a pair of scalar add/sub.
8191     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8192       return SDValue();
8193 
8194     // Convert this build_vector into two horizontal add/sub followed by
8195     // a concat vector.
8196     bool isUndefLO = NumUndefsLO == Half;
8197     bool isUndefHI = NumUndefsHI == Half;
8198     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
8199                                  isUndefLO, isUndefHI);
8200   }
8201 
8202   return SDValue();
8203 }
8204 
8205 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
8206                           SelectionDAG &DAG);
8207 
8208 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
8209 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8210 /// just apply the bit to the vectors.
8211 /// NOTE: Its not in our interest to start make a general purpose vectorizer
8212 /// from this, but enough scalar bit operations are created from the later
8213 /// legalization + scalarization stages to need basic support.
lowerBuildVectorToBitOp(BuildVectorSDNode * Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)8214 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
8215                                        const X86Subtarget &Subtarget,
8216                                        SelectionDAG &DAG) {
8217   SDLoc DL(Op);
8218   MVT VT = Op->getSimpleValueType(0);
8219   unsigned NumElems = VT.getVectorNumElements();
8220   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8221 
8222   // Check that all elements have the same opcode.
8223   // TODO: Should we allow UNDEFS and if so how many?
8224   unsigned Opcode = Op->getOperand(0).getOpcode();
8225   for (unsigned i = 1; i < NumElems; ++i)
8226     if (Opcode != Op->getOperand(i).getOpcode())
8227       return SDValue();
8228 
8229   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
8230   bool IsShift = false;
8231   switch (Opcode) {
8232   default:
8233     return SDValue();
8234   case ISD::SHL:
8235   case ISD::SRL:
8236   case ISD::SRA:
8237     IsShift = true;
8238     break;
8239   case ISD::AND:
8240   case ISD::XOR:
8241   case ISD::OR:
8242     // Don't do this if the buildvector is a splat - we'd replace one
8243     // constant with an entire vector.
8244     if (Op->getSplatValue())
8245       return SDValue();
8246     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8247       return SDValue();
8248     break;
8249   }
8250 
8251   SmallVector<SDValue, 4> LHSElts, RHSElts;
8252   for (SDValue Elt : Op->ops()) {
8253     SDValue LHS = Elt.getOperand(0);
8254     SDValue RHS = Elt.getOperand(1);
8255 
8256     // We expect the canonicalized RHS operand to be the constant.
8257     if (!isa<ConstantSDNode>(RHS))
8258       return SDValue();
8259 
8260     // Extend shift amounts.
8261     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
8262       if (!IsShift)
8263         return SDValue();
8264       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
8265     }
8266 
8267     LHSElts.push_back(LHS);
8268     RHSElts.push_back(RHS);
8269   }
8270 
8271   // Limit to shifts by uniform immediates.
8272   // TODO: Only accept vXi8/vXi64 special cases?
8273   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
8274   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
8275     return SDValue();
8276 
8277   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
8278   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
8279   SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
8280 
8281   if (!IsShift)
8282     return Res;
8283 
8284   // Immediately lower the shift to ensure the constant build vector doesn't
8285   // get converted to a constant pool before the shift is lowered.
8286   return LowerShift(Res, Subtarget, DAG);
8287 }
8288 
8289 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
8290 /// functionality to do this, so it's all zeros, all ones, or some derivation
8291 /// that is cheap to calculate.
materializeVectorConstant(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)8292 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
8293                                          const X86Subtarget &Subtarget) {
8294   SDLoc DL(Op);
8295   MVT VT = Op.getSimpleValueType();
8296 
8297   // Vectors containing all zeros can be matched by pxor and xorps.
8298   if (ISD::isBuildVectorAllZeros(Op.getNode()))
8299     return Op;
8300 
8301   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
8302   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
8303   // vpcmpeqd on 256-bit vectors.
8304   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
8305     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
8306       return Op;
8307 
8308     return getOnesVector(VT, DAG, DL);
8309   }
8310 
8311   return SDValue();
8312 }
8313 
8314 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
8315 /// from a vector of source values and a vector of extraction indices.
8316 /// The vectors might be manipulated to match the type of the permute op.
createVariablePermute(MVT VT,SDValue SrcVec,SDValue IndicesVec,SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)8317 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
8318                                      SDLoc &DL, SelectionDAG &DAG,
8319                                      const X86Subtarget &Subtarget) {
8320   MVT ShuffleVT = VT;
8321   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8322   unsigned NumElts = VT.getVectorNumElements();
8323   unsigned SizeInBits = VT.getSizeInBits();
8324 
8325   // Adjust IndicesVec to match VT size.
8326   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
8327          "Illegal variable permute mask size");
8328   if (IndicesVec.getValueType().getVectorNumElements() > NumElts) {
8329     // Narrow/widen the indices vector to the correct size.
8330     if (IndicesVec.getValueSizeInBits() > SizeInBits)
8331       IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
8332                                     NumElts * VT.getScalarSizeInBits());
8333     else if (IndicesVec.getValueSizeInBits() < SizeInBits)
8334       IndicesVec = widenSubVector(IndicesVec, false, Subtarget, DAG,
8335                                   SDLoc(IndicesVec), SizeInBits);
8336     // Zero-extend the index elements within the vector.
8337     if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
8338       IndicesVec = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(IndicesVec),
8339                                IndicesVT, IndicesVec);
8340   }
8341   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
8342 
8343   // Handle SrcVec that don't match VT type.
8344   if (SrcVec.getValueSizeInBits() != SizeInBits) {
8345     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
8346       // Handle larger SrcVec by treating it as a larger permute.
8347       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
8348       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
8349       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8350       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
8351                                   Subtarget, DAG, SDLoc(IndicesVec));
8352       SDValue NewSrcVec =
8353           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
8354       if (NewSrcVec)
8355         return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
8356       return SDValue();
8357     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
8358       // Widen smaller SrcVec to match VT.
8359       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
8360     } else
8361       return SDValue();
8362   }
8363 
8364   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
8365     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
8366     EVT SrcVT = Idx.getValueType();
8367     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
8368     uint64_t IndexScale = 0;
8369     uint64_t IndexOffset = 0;
8370 
8371     // If we're scaling a smaller permute op, then we need to repeat the
8372     // indices, scaling and offsetting them as well.
8373     // e.g. v4i32 -> v16i8 (Scale = 4)
8374     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
8375     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
8376     for (uint64_t i = 0; i != Scale; ++i) {
8377       IndexScale |= Scale << (i * NumDstBits);
8378       IndexOffset |= i << (i * NumDstBits);
8379     }
8380 
8381     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
8382                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
8383     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
8384                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
8385     return Idx;
8386   };
8387 
8388   unsigned Opcode = 0;
8389   switch (VT.SimpleTy) {
8390   default:
8391     break;
8392   case MVT::v16i8:
8393     if (Subtarget.hasSSSE3())
8394       Opcode = X86ISD::PSHUFB;
8395     break;
8396   case MVT::v8i16:
8397     if (Subtarget.hasVLX() && Subtarget.hasBWI())
8398       Opcode = X86ISD::VPERMV;
8399     else if (Subtarget.hasSSSE3()) {
8400       Opcode = X86ISD::PSHUFB;
8401       ShuffleVT = MVT::v16i8;
8402     }
8403     break;
8404   case MVT::v4f32:
8405   case MVT::v4i32:
8406     if (Subtarget.hasAVX()) {
8407       Opcode = X86ISD::VPERMILPV;
8408       ShuffleVT = MVT::v4f32;
8409     } else if (Subtarget.hasSSSE3()) {
8410       Opcode = X86ISD::PSHUFB;
8411       ShuffleVT = MVT::v16i8;
8412     }
8413     break;
8414   case MVT::v2f64:
8415   case MVT::v2i64:
8416     if (Subtarget.hasAVX()) {
8417       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
8418       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8419       Opcode = X86ISD::VPERMILPV;
8420       ShuffleVT = MVT::v2f64;
8421     } else if (Subtarget.hasSSE41()) {
8422       // SSE41 can compare v2i64 - select between indices 0 and 1.
8423       return DAG.getSelectCC(
8424           DL, IndicesVec,
8425           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
8426           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
8427           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
8428           ISD::CondCode::SETEQ);
8429     }
8430     break;
8431   case MVT::v32i8:
8432     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
8433       Opcode = X86ISD::VPERMV;
8434     else if (Subtarget.hasXOP()) {
8435       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
8436       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
8437       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
8438       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
8439       return DAG.getNode(
8440           ISD::CONCAT_VECTORS, DL, VT,
8441           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
8442           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
8443     } else if (Subtarget.hasAVX()) {
8444       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
8445       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
8446       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
8447       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
8448       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
8449                               ArrayRef<SDValue> Ops) {
8450         // Permute Lo and Hi and then select based on index range.
8451         // This works as SHUFB uses bits[3:0] to permute elements and we don't
8452         // care about the bit[7] as its just an index vector.
8453         SDValue Idx = Ops[2];
8454         EVT VT = Idx.getValueType();
8455         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
8456                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
8457                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
8458                                ISD::CondCode::SETGT);
8459       };
8460       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
8461       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
8462                               PSHUFBBuilder);
8463     }
8464     break;
8465   case MVT::v16i16:
8466     if (Subtarget.hasVLX() && Subtarget.hasBWI())
8467       Opcode = X86ISD::VPERMV;
8468     else if (Subtarget.hasAVX()) {
8469       // Scale to v32i8 and perform as v32i8.
8470       IndicesVec = ScaleIndices(IndicesVec, 2);
8471       return DAG.getBitcast(
8472           VT, createVariablePermute(
8473                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
8474                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
8475     }
8476     break;
8477   case MVT::v8f32:
8478   case MVT::v8i32:
8479     if (Subtarget.hasAVX2())
8480       Opcode = X86ISD::VPERMV;
8481     else if (Subtarget.hasAVX()) {
8482       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
8483       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8484                                           {0, 1, 2, 3, 0, 1, 2, 3});
8485       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8486                                           {4, 5, 6, 7, 4, 5, 6, 7});
8487       if (Subtarget.hasXOP())
8488         return DAG.getBitcast(
8489             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
8490                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
8491       // Permute Lo and Hi and then select based on index range.
8492       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
8493       SDValue Res = DAG.getSelectCC(
8494           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
8495           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
8496           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
8497           ISD::CondCode::SETGT);
8498       return DAG.getBitcast(VT, Res);
8499     }
8500     break;
8501   case MVT::v4i64:
8502   case MVT::v4f64:
8503     if (Subtarget.hasAVX512()) {
8504       if (!Subtarget.hasVLX()) {
8505         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
8506         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
8507                                 SDLoc(SrcVec));
8508         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
8509                                     DAG, SDLoc(IndicesVec));
8510         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
8511                                             DAG, Subtarget);
8512         return extract256BitVector(Res, 0, DAG, DL);
8513       }
8514       Opcode = X86ISD::VPERMV;
8515     } else if (Subtarget.hasAVX()) {
8516       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
8517       SDValue LoLo =
8518           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
8519       SDValue HiHi =
8520           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
8521       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
8522       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8523       if (Subtarget.hasXOP())
8524         return DAG.getBitcast(
8525             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
8526                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
8527       // Permute Lo and Hi and then select based on index range.
8528       // This works as VPERMILPD only uses index bit[1] to permute elements.
8529       SDValue Res = DAG.getSelectCC(
8530           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
8531           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
8532           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
8533           ISD::CondCode::SETGT);
8534       return DAG.getBitcast(VT, Res);
8535     }
8536     break;
8537   case MVT::v64i8:
8538     if (Subtarget.hasVBMI())
8539       Opcode = X86ISD::VPERMV;
8540     break;
8541   case MVT::v32i16:
8542     if (Subtarget.hasBWI())
8543       Opcode = X86ISD::VPERMV;
8544     break;
8545   case MVT::v16f32:
8546   case MVT::v16i32:
8547   case MVT::v8f64:
8548   case MVT::v8i64:
8549     if (Subtarget.hasAVX512())
8550       Opcode = X86ISD::VPERMV;
8551     break;
8552   }
8553   if (!Opcode)
8554     return SDValue();
8555 
8556   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
8557          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
8558          "Illegal variable permute shuffle type");
8559 
8560   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
8561   if (Scale > 1)
8562     IndicesVec = ScaleIndices(IndicesVec, Scale);
8563 
8564   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
8565   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
8566 
8567   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
8568   SDValue Res = Opcode == X86ISD::VPERMV
8569                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
8570                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
8571   return DAG.getBitcast(VT, Res);
8572 }
8573 
8574 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
8575 // reasoned to be a permutation of a vector by indices in a non-constant vector.
8576 // (build_vector (extract_elt V, (extract_elt I, 0)),
8577 //               (extract_elt V, (extract_elt I, 1)),
8578 //                    ...
8579 // ->
8580 // (vpermv I, V)
8581 //
8582 // TODO: Handle undefs
8583 // TODO: Utilize pshufb and zero mask blending to support more efficient
8584 // construction of vectors with constant-0 elements.
8585 static SDValue
LowerBUILD_VECTORAsVariablePermute(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)8586 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
8587                                    const X86Subtarget &Subtarget) {
8588   SDValue SrcVec, IndicesVec;
8589   // Check for a match of the permute source vector and permute index elements.
8590   // This is done by checking that the i-th build_vector operand is of the form:
8591   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
8592   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
8593     SDValue Op = V.getOperand(Idx);
8594     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8595       return SDValue();
8596 
8597     // If this is the first extract encountered in V, set the source vector,
8598     // otherwise verify the extract is from the previously defined source
8599     // vector.
8600     if (!SrcVec)
8601       SrcVec = Op.getOperand(0);
8602     else if (SrcVec != Op.getOperand(0))
8603       return SDValue();
8604     SDValue ExtractedIndex = Op->getOperand(1);
8605     // Peek through extends.
8606     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
8607         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
8608       ExtractedIndex = ExtractedIndex.getOperand(0);
8609     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8610       return SDValue();
8611 
8612     // If this is the first extract from the index vector candidate, set the
8613     // indices vector, otherwise verify the extract is from the previously
8614     // defined indices vector.
8615     if (!IndicesVec)
8616       IndicesVec = ExtractedIndex.getOperand(0);
8617     else if (IndicesVec != ExtractedIndex.getOperand(0))
8618       return SDValue();
8619 
8620     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
8621     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
8622       return SDValue();
8623   }
8624 
8625   SDLoc DL(V);
8626   MVT VT = V.getSimpleValueType();
8627   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
8628 }
8629 
8630 SDValue
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const8631 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
8632   SDLoc dl(Op);
8633 
8634   MVT VT = Op.getSimpleValueType();
8635   MVT EltVT = VT.getVectorElementType();
8636   MVT OpEltVT = Op.getOperand(0).getSimpleValueType();
8637   unsigned NumElems = Op.getNumOperands();
8638 
8639   // Generate vectors for predicate vectors.
8640   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
8641     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
8642 
8643   if (VT.getVectorElementType() == MVT::bf16 &&
8644       (Subtarget.hasAVXNECONVERT() || Subtarget.hasBF16()))
8645     return LowerBUILD_VECTORvXbf16(Op, DAG, Subtarget);
8646 
8647   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
8648     return VectorConstant;
8649 
8650   unsigned EVTBits = EltVT.getSizeInBits();
8651   APInt UndefMask = APInt::getZero(NumElems);
8652   APInt FrozenUndefMask = APInt::getZero(NumElems);
8653   APInt ZeroMask = APInt::getZero(NumElems);
8654   APInt NonZeroMask = APInt::getZero(NumElems);
8655   bool IsAllConstants = true;
8656   bool OneUseFrozenUndefs = true;
8657   SmallSet<SDValue, 8> Values;
8658   unsigned NumConstants = NumElems;
8659   for (unsigned i = 0; i < NumElems; ++i) {
8660     SDValue Elt = Op.getOperand(i);
8661     if (Elt.isUndef()) {
8662       UndefMask.setBit(i);
8663       continue;
8664     }
8665     if (ISD::isFreezeUndef(Elt.getNode())) {
8666       OneUseFrozenUndefs = OneUseFrozenUndefs && Elt->hasOneUse();
8667       FrozenUndefMask.setBit(i);
8668       continue;
8669     }
8670     Values.insert(Elt);
8671     if (!isIntOrFPConstant(Elt)) {
8672       IsAllConstants = false;
8673       NumConstants--;
8674     }
8675     if (X86::isZeroNode(Elt)) {
8676       ZeroMask.setBit(i);
8677     } else {
8678       NonZeroMask.setBit(i);
8679     }
8680   }
8681 
8682   // All undef vector. Return an UNDEF.
8683   if (UndefMask.isAllOnes())
8684     return DAG.getUNDEF(VT);
8685 
8686   // All undef/freeze(undef) vector. Return a FREEZE UNDEF.
8687   if (OneUseFrozenUndefs && (UndefMask | FrozenUndefMask).isAllOnes())
8688     return DAG.getFreeze(DAG.getUNDEF(VT));
8689 
8690   // All undef/freeze(undef)/zero vector. Return a zero vector.
8691   if ((UndefMask | FrozenUndefMask | ZeroMask).isAllOnes())
8692     return getZeroVector(VT, Subtarget, DAG, dl);
8693 
8694   // If we have multiple FREEZE-UNDEF operands, we are likely going to end up
8695   // lowering into a suboptimal insertion sequence. Instead, thaw the UNDEF in
8696   // our source BUILD_VECTOR, create another FREEZE-UNDEF splat BUILD_VECTOR,
8697   // and blend the FREEZE-UNDEF operands back in.
8698   // FIXME: is this worthwhile even for a single FREEZE-UNDEF operand?
8699   if (unsigned NumFrozenUndefElts = FrozenUndefMask.popcount();
8700       NumFrozenUndefElts >= 2 && NumFrozenUndefElts < NumElems) {
8701     SmallVector<int, 16> BlendMask(NumElems, -1);
8702     SmallVector<SDValue, 16> Elts(NumElems, DAG.getUNDEF(OpEltVT));
8703     for (unsigned i = 0; i < NumElems; ++i) {
8704       if (UndefMask[i]) {
8705         BlendMask[i] = -1;
8706         continue;
8707       }
8708       BlendMask[i] = i;
8709       if (!FrozenUndefMask[i])
8710         Elts[i] = Op.getOperand(i);
8711       else
8712         BlendMask[i] += NumElems;
8713     }
8714     SDValue EltsBV = DAG.getBuildVector(VT, dl, Elts);
8715     SDValue FrozenUndefElt = DAG.getFreeze(DAG.getUNDEF(OpEltVT));
8716     SDValue FrozenUndefBV = DAG.getSplatBuildVector(VT, dl, FrozenUndefElt);
8717     return DAG.getVectorShuffle(VT, dl, EltsBV, FrozenUndefBV, BlendMask);
8718   }
8719 
8720   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
8721 
8722   // If the upper elts of a ymm/zmm are undef/freeze(undef)/zero then we might
8723   // be better off lowering to a smaller build vector and padding with
8724   // undef/zero.
8725   if ((VT.is256BitVector() || VT.is512BitVector()) &&
8726       !isFoldableUseOfShuffle(BV)) {
8727     unsigned UpperElems = NumElems / 2;
8728     APInt UndefOrZeroMask = FrozenUndefMask | UndefMask | ZeroMask;
8729     unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countl_one();
8730     if (NumUpperUndefsOrZeros >= UpperElems) {
8731       if (VT.is512BitVector() &&
8732           NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
8733         UpperElems = NumElems - (NumElems / 4);
8734       // If freeze(undef) is in any upper elements, force to zero.
8735       bool UndefUpper = UndefMask.countl_one() >= UpperElems;
8736       MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
8737       SDValue NewBV =
8738           DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
8739       return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
8740     }
8741   }
8742 
8743   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
8744     return AddSub;
8745   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
8746     return HorizontalOp;
8747   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
8748     return Broadcast;
8749   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
8750     return BitOp;
8751 
8752   unsigned NumZero = ZeroMask.popcount();
8753   unsigned NumNonZero = NonZeroMask.popcount();
8754 
8755   // If we are inserting one variable into a vector of non-zero constants, try
8756   // to avoid loading each constant element as a scalar. Load the constants as a
8757   // vector and then insert the variable scalar element. If insertion is not
8758   // supported, fall back to a shuffle to get the scalar blended with the
8759   // constants. Insertion into a zero vector is handled as a special-case
8760   // somewhere below here.
8761   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
8762       FrozenUndefMask.isZero() &&
8763       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
8764        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
8765     // Create an all-constant vector. The variable element in the old
8766     // build vector is replaced by undef in the constant vector. Save the
8767     // variable scalar element and its index for use in the insertelement.
8768     LLVMContext &Context = *DAG.getContext();
8769     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
8770     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
8771     SDValue VarElt;
8772     SDValue InsIndex;
8773     for (unsigned i = 0; i != NumElems; ++i) {
8774       SDValue Elt = Op.getOperand(i);
8775       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
8776         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
8777       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
8778         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
8779       else if (!Elt.isUndef()) {
8780         assert(!VarElt.getNode() && !InsIndex.getNode() &&
8781                "Expected one variable element in this vector");
8782         VarElt = Elt;
8783         InsIndex = DAG.getVectorIdxConstant(i, dl);
8784       }
8785     }
8786     Constant *CV = ConstantVector::get(ConstVecOps);
8787     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
8788 
8789     // The constants we just created may not be legal (eg, floating point). We
8790     // must lower the vector right here because we can not guarantee that we'll
8791     // legalize it before loading it. This is also why we could not just create
8792     // a new build vector here. If the build vector contains illegal constants,
8793     // it could get split back up into a series of insert elements.
8794     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
8795     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
8796     MachineFunction &MF = DAG.getMachineFunction();
8797     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
8798     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
8799     unsigned InsertC = InsIndex->getAsZExtVal();
8800     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
8801     if (InsertC < NumEltsInLow128Bits)
8802       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
8803 
8804     // There's no good way to insert into the high elements of a >128-bit
8805     // vector, so use shuffles to avoid an extract/insert sequence.
8806     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
8807     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
8808     SmallVector<int, 8> ShuffleMask;
8809     unsigned NumElts = VT.getVectorNumElements();
8810     for (unsigned i = 0; i != NumElts; ++i)
8811       ShuffleMask.push_back(i == InsertC ? NumElts : i);
8812     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
8813     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
8814   }
8815 
8816   // Special case for single non-zero, non-undef, element.
8817   if (NumNonZero == 1) {
8818     unsigned Idx = NonZeroMask.countr_zero();
8819     SDValue Item = Op.getOperand(Idx);
8820 
8821     // If we have a constant or non-constant insertion into the low element of
8822     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
8823     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
8824     // depending on what the source datatype is.
8825     if (Idx == 0) {
8826       if (NumZero == 0)
8827         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
8828 
8829       if (EltVT == MVT::i32 || EltVT == MVT::f16 || EltVT == MVT::f32 ||
8830           EltVT == MVT::f64 || (EltVT == MVT::i64 && Subtarget.is64Bit()) ||
8831           (EltVT == MVT::i16 && Subtarget.hasFP16())) {
8832         assert((VT.is128BitVector() || VT.is256BitVector() ||
8833                 VT.is512BitVector()) &&
8834                "Expected an SSE value type!");
8835         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
8836         // Turn it into a MOVL (i.e. movsh, movss, movsd, movw or movd) to a
8837         // zero vector.
8838         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
8839       }
8840 
8841       // We can't directly insert an i8 or i16 into a vector, so zero extend
8842       // it to i32 first.
8843       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
8844         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
8845         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
8846         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
8847         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
8848         return DAG.getBitcast(VT, Item);
8849       }
8850     }
8851 
8852     // Is it a vector logical left shift?
8853     if (NumElems == 2 && Idx == 1 &&
8854         X86::isZeroNode(Op.getOperand(0)) &&
8855         !X86::isZeroNode(Op.getOperand(1))) {
8856       unsigned NumBits = VT.getSizeInBits();
8857       return getVShift(true, VT,
8858                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8859                                    VT, Op.getOperand(1)),
8860                        NumBits/2, DAG, *this, dl);
8861     }
8862 
8863     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
8864       return SDValue();
8865 
8866     // Otherwise, if this is a vector with i32 or f32 elements, and the element
8867     // is a non-constant being inserted into an element other than the low one,
8868     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
8869     // movd/movss) to move this into the low element, then shuffle it into
8870     // place.
8871     if (EVTBits == 32) {
8872       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
8873       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
8874     }
8875   }
8876 
8877   // Splat is obviously ok. Let legalizer expand it to a shuffle.
8878   if (Values.size() == 1) {
8879     if (EVTBits == 32) {
8880       // Instead of a shuffle like this:
8881       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
8882       // Check if it's possible to issue this instead.
8883       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
8884       unsigned Idx = NonZeroMask.countr_zero();
8885       SDValue Item = Op.getOperand(Idx);
8886       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
8887         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
8888     }
8889     return SDValue();
8890   }
8891 
8892   // A vector full of immediates; various special cases are already
8893   // handled, so this is best done with a single constant-pool load.
8894   if (IsAllConstants)
8895     return SDValue();
8896 
8897   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
8898       return V;
8899 
8900   // See if we can use a vector load to get all of the elements.
8901   {
8902     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
8903     if (SDValue LD =
8904             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
8905       return LD;
8906   }
8907 
8908   // If this is a splat of pairs of 32-bit elements, we can use a narrower
8909   // build_vector and broadcast it.
8910   // TODO: We could probably generalize this more.
8911   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
8912     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
8913                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
8914     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
8915       // Make sure all the even/odd operands match.
8916       for (unsigned i = 2; i != NumElems; ++i)
8917         if (Ops[i % 2] != Op.getOperand(i))
8918           return false;
8919       return true;
8920     };
8921     if (CanSplat(Op, NumElems, Ops)) {
8922       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
8923       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
8924       // Create a new build vector and cast to v2i64/v2f64.
8925       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
8926                                      DAG.getBuildVector(NarrowVT, dl, Ops));
8927       // Broadcast from v2i64/v2f64 and cast to final VT.
8928       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems / 2);
8929       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
8930                                             NewBV));
8931     }
8932   }
8933 
8934   // For AVX-length vectors, build the individual 128-bit pieces and use
8935   // shuffles to put them in place.
8936   if (VT.getSizeInBits() > 128) {
8937     MVT HVT = MVT::getVectorVT(EltVT, NumElems / 2);
8938 
8939     // Build both the lower and upper subvector.
8940     SDValue Lower =
8941         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
8942     SDValue Upper = DAG.getBuildVector(
8943         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
8944 
8945     // Recreate the wider vector with the lower and upper part.
8946     return concatSubVectors(Lower, Upper, DAG, dl);
8947   }
8948 
8949   // Let legalizer expand 2-wide build_vectors.
8950   if (EVTBits == 64) {
8951     if (NumNonZero == 1) {
8952       // One half is zero or undef.
8953       unsigned Idx = NonZeroMask.countr_zero();
8954       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
8955                                Op.getOperand(Idx));
8956       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
8957     }
8958     return SDValue();
8959   }
8960 
8961   // If element VT is < 32 bits, convert it to inserts into a zero vector.
8962   if (EVTBits == 8 && NumElems == 16)
8963     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeroMask, NumNonZero, NumZero,
8964                                           DAG, Subtarget))
8965       return V;
8966 
8967   if (EltVT == MVT::i16 && NumElems == 8)
8968     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeroMask, NumNonZero, NumZero,
8969                                           DAG, Subtarget))
8970       return V;
8971 
8972   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
8973   if (EVTBits == 32 && NumElems == 4)
8974     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
8975       return V;
8976 
8977   // If element VT is == 32 bits, turn it into a number of shuffles.
8978   if (NumElems == 4 && NumZero > 0) {
8979     SmallVector<SDValue, 8> Ops(NumElems);
8980     for (unsigned i = 0; i < 4; ++i) {
8981       bool isZero = !NonZeroMask[i];
8982       if (isZero)
8983         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
8984       else
8985         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
8986     }
8987 
8988     for (unsigned i = 0; i < 2; ++i) {
8989       switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
8990         default: llvm_unreachable("Unexpected NonZero count");
8991         case 0:
8992           Ops[i] = Ops[i*2];  // Must be a zero vector.
8993           break;
8994         case 1:
8995           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
8996           break;
8997         case 2:
8998           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
8999           break;
9000         case 3:
9001           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9002           break;
9003       }
9004     }
9005 
9006     bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
9007     bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
9008     int MaskVec[] = {
9009       Reverse1 ? 1 : 0,
9010       Reverse1 ? 0 : 1,
9011       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9012       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
9013     };
9014     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9015   }
9016 
9017   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
9018 
9019   // Check for a build vector from mostly shuffle plus few inserting.
9020   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
9021     return Sh;
9022 
9023   // For SSE 4.1, use insertps to put the high elements into the low element.
9024   if (Subtarget.hasSSE41() && EltVT != MVT::f16) {
9025     SDValue Result;
9026     if (!Op.getOperand(0).isUndef())
9027       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9028     else
9029       Result = DAG.getUNDEF(VT);
9030 
9031     for (unsigned i = 1; i < NumElems; ++i) {
9032       if (Op.getOperand(i).isUndef()) continue;
9033       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9034                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
9035     }
9036     return Result;
9037   }
9038 
9039   // Otherwise, expand into a number of unpckl*, start by extending each of
9040   // our (non-undef) elements to the full vector width with the element in the
9041   // bottom slot of the vector (which generates no code for SSE).
9042   SmallVector<SDValue, 8> Ops(NumElems);
9043   for (unsigned i = 0; i < NumElems; ++i) {
9044     if (!Op.getOperand(i).isUndef())
9045       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9046     else
9047       Ops[i] = DAG.getUNDEF(VT);
9048   }
9049 
9050   // Next, we iteratively mix elements, e.g. for v4f32:
9051   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9052   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9053   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
9054   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9055     // Generate scaled UNPCKL shuffle mask.
9056     SmallVector<int, 16> Mask;
9057     for(unsigned i = 0; i != Scale; ++i)
9058       Mask.push_back(i);
9059     for (unsigned i = 0; i != Scale; ++i)
9060       Mask.push_back(NumElems+i);
9061     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9062 
9063     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9064       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9065   }
9066   return Ops[0];
9067 }
9068 
9069 // 256-bit AVX can use the vinsertf128 instruction
9070 // to create 256-bit vectors from two other 128-bit ones.
9071 // TODO: Detect subvector broadcast here instead of DAG combine?
LowerAVXCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)9072 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9073                                       const X86Subtarget &Subtarget) {
9074   SDLoc dl(Op);
9075   MVT ResVT = Op.getSimpleValueType();
9076 
9077   assert((ResVT.is256BitVector() ||
9078           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
9079 
9080   unsigned NumOperands = Op.getNumOperands();
9081   unsigned NumFreezeUndef = 0;
9082   unsigned NumZero = 0;
9083   unsigned NumNonZero = 0;
9084   unsigned NonZeros = 0;
9085   for (unsigned i = 0; i != NumOperands; ++i) {
9086     SDValue SubVec = Op.getOperand(i);
9087     if (SubVec.isUndef())
9088       continue;
9089     if (ISD::isFreezeUndef(SubVec.getNode())) {
9090         // If the freeze(undef) has multiple uses then we must fold to zero.
9091         if (SubVec.hasOneUse())
9092           ++NumFreezeUndef;
9093         else
9094           ++NumZero;
9095     }
9096     else if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9097       ++NumZero;
9098     else {
9099       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9100       NonZeros |= 1 << i;
9101       ++NumNonZero;
9102     }
9103   }
9104 
9105   // If we have more than 2 non-zeros, build each half separately.
9106   if (NumNonZero > 2) {
9107     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9108     ArrayRef<SDUse> Ops = Op->ops();
9109     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9110                              Ops.slice(0, NumOperands/2));
9111     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9112                              Ops.slice(NumOperands/2));
9113     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9114   }
9115 
9116   // Otherwise, build it up through insert_subvectors.
9117   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9118                         : (NumFreezeUndef ? DAG.getFreeze(DAG.getUNDEF(ResVT))
9119                                           : DAG.getUNDEF(ResVT));
9120 
9121   MVT SubVT = Op.getOperand(0).getSimpleValueType();
9122   unsigned NumSubElems = SubVT.getVectorNumElements();
9123   for (unsigned i = 0; i != NumOperands; ++i) {
9124     if ((NonZeros & (1 << i)) == 0)
9125       continue;
9126 
9127     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
9128                       Op.getOperand(i),
9129                       DAG.getIntPtrConstant(i * NumSubElems, dl));
9130   }
9131 
9132   return Vec;
9133 }
9134 
9135 // Returns true if the given node is a type promotion (by concatenating i1
9136 // zeros) of the result of a node that already zeros all upper bits of
9137 // k-register.
9138 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
LowerCONCAT_VECTORSvXi1(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)9139 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
9140                                        const X86Subtarget &Subtarget,
9141                                        SelectionDAG & DAG) {
9142   SDLoc dl(Op);
9143   MVT ResVT = Op.getSimpleValueType();
9144   unsigned NumOperands = Op.getNumOperands();
9145 
9146   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
9147          "Unexpected number of operands in CONCAT_VECTORS");
9148 
9149   uint64_t Zeros = 0;
9150   uint64_t NonZeros = 0;
9151   for (unsigned i = 0; i != NumOperands; ++i) {
9152     SDValue SubVec = Op.getOperand(i);
9153     if (SubVec.isUndef())
9154       continue;
9155     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
9156     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9157       Zeros |= (uint64_t)1 << i;
9158     else
9159       NonZeros |= (uint64_t)1 << i;
9160   }
9161 
9162   unsigned NumElems = ResVT.getVectorNumElements();
9163 
9164   // If we are inserting non-zero vector and there are zeros in LSBs and undef
9165   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
9166   // insert_subvector will give us two kshifts.
9167   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
9168       Log2_64(NonZeros) != NumOperands - 1) {
9169     unsigned Idx = Log2_64(NonZeros);
9170     SDValue SubVec = Op.getOperand(Idx);
9171     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
9172     MVT ShiftVT = widenMaskVectorType(ResVT, Subtarget);
9173     Op = widenSubVector(ShiftVT, SubVec, false, Subtarget, DAG, dl);
9174     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, Op,
9175                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
9176     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
9177                        DAG.getIntPtrConstant(0, dl));
9178   }
9179 
9180   // If there are zero or one non-zeros we can handle this very simply.
9181   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
9182     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
9183     if (!NonZeros)
9184       return Vec;
9185     unsigned Idx = Log2_64(NonZeros);
9186     SDValue SubVec = Op.getOperand(Idx);
9187     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
9188     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
9189                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
9190   }
9191 
9192   if (NumOperands > 2) {
9193     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
9194     ArrayRef<SDUse> Ops = Op->ops();
9195     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9196                              Ops.slice(0, NumOperands/2));
9197     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9198                              Ops.slice(NumOperands/2));
9199     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9200   }
9201 
9202   assert(llvm::popcount(NonZeros) == 2 && "Simple cases not handled?");
9203 
9204   if (ResVT.getVectorNumElements() >= 16)
9205     return Op; // The operation is legal with KUNPCK
9206 
9207   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
9208                             DAG.getUNDEF(ResVT), Op.getOperand(0),
9209                             DAG.getIntPtrConstant(0, dl));
9210   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
9211                      DAG.getIntPtrConstant(NumElems/2, dl));
9212 }
9213 
LowerCONCAT_VECTORS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)9214 static SDValue LowerCONCAT_VECTORS(SDValue Op,
9215                                    const X86Subtarget &Subtarget,
9216                                    SelectionDAG &DAG) {
9217   MVT VT = Op.getSimpleValueType();
9218   if (VT.getVectorElementType() == MVT::i1)
9219     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
9220 
9221   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
9222          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
9223           Op.getNumOperands() == 4)));
9224 
9225   // AVX can use the vinsertf128 instruction to create 256-bit vectors
9226   // from two other 128-bit ones.
9227 
9228   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
9229   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
9230 }
9231 
9232 //===----------------------------------------------------------------------===//
9233 // Vector shuffle lowering
9234 //
9235 // This is an experimental code path for lowering vector shuffles on x86. It is
9236 // designed to handle arbitrary vector shuffles and blends, gracefully
9237 // degrading performance as necessary. It works hard to recognize idiomatic
9238 // shuffles and lower them to optimal instruction patterns without leaving
9239 // a framework that allows reasonably efficient handling of all vector shuffle
9240 // patterns.
9241 //===----------------------------------------------------------------------===//
9242 
9243 /// Tiny helper function to identify a no-op mask.
9244 ///
9245 /// This is a somewhat boring predicate function. It checks whether the mask
9246 /// array input, which is assumed to be a single-input shuffle mask of the kind
9247 /// used by the X86 shuffle instructions (not a fully general
9248 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
9249 /// in-place shuffle are 'no-op's.
isNoopShuffleMask(ArrayRef<int> Mask)9250 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
9251   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9252     assert(Mask[i] >= -1 && "Out of bound mask element!");
9253     if (Mask[i] >= 0 && Mask[i] != i)
9254       return false;
9255   }
9256   return true;
9257 }
9258 
9259 /// Test whether there are elements crossing LaneSizeInBits lanes in this
9260 /// shuffle mask.
9261 ///
9262 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
9263 /// and we routinely test for these.
isLaneCrossingShuffleMask(unsigned LaneSizeInBits,unsigned ScalarSizeInBits,ArrayRef<int> Mask)9264 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
9265                                       unsigned ScalarSizeInBits,
9266                                       ArrayRef<int> Mask) {
9267   assert(LaneSizeInBits && ScalarSizeInBits &&
9268          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
9269          "Illegal shuffle lane size");
9270   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
9271   int Size = Mask.size();
9272   for (int i = 0; i < Size; ++i)
9273     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9274       return true;
9275   return false;
9276 }
9277 
9278 /// Test whether there are elements crossing 128-bit lanes in this
9279 /// shuffle mask.
is128BitLaneCrossingShuffleMask(MVT VT,ArrayRef<int> Mask)9280 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
9281   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
9282 }
9283 
9284 /// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
9285 /// from multiple lanes - this is different to isLaneCrossingShuffleMask to
9286 /// better support 'repeated mask + lane permute' style shuffles.
isMultiLaneShuffleMask(unsigned LaneSizeInBits,unsigned ScalarSizeInBits,ArrayRef<int> Mask)9287 static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
9288                                    unsigned ScalarSizeInBits,
9289                                    ArrayRef<int> Mask) {
9290   assert(LaneSizeInBits && ScalarSizeInBits &&
9291          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
9292          "Illegal shuffle lane size");
9293   int NumElts = Mask.size();
9294   int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
9295   int NumLanes = NumElts / NumEltsPerLane;
9296   if (NumLanes > 1) {
9297     for (int i = 0; i != NumLanes; ++i) {
9298       int SrcLane = -1;
9299       for (int j = 0; j != NumEltsPerLane; ++j) {
9300         int M = Mask[(i * NumEltsPerLane) + j];
9301         if (M < 0)
9302           continue;
9303         int Lane = (M % NumElts) / NumEltsPerLane;
9304         if (SrcLane >= 0 && SrcLane != Lane)
9305           return true;
9306         SrcLane = Lane;
9307       }
9308     }
9309   }
9310   return false;
9311 }
9312 
9313 /// Test whether a shuffle mask is equivalent within each sub-lane.
9314 ///
9315 /// This checks a shuffle mask to see if it is performing the same
9316 /// lane-relative shuffle in each sub-lane. This trivially implies
9317 /// that it is also not lane-crossing. It may however involve a blend from the
9318 /// same lane of a second vector.
9319 ///
9320 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
9321 /// non-trivial to compute in the face of undef lanes. The representation is
9322 /// suitable for use with existing 128-bit shuffles as entries from the second
9323 /// vector have been remapped to [LaneSize, 2*LaneSize).
isRepeatedShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9324 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
9325                                   ArrayRef<int> Mask,
9326                                   SmallVectorImpl<int> &RepeatedMask) {
9327   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
9328   RepeatedMask.assign(LaneSize, -1);
9329   int Size = Mask.size();
9330   for (int i = 0; i < Size; ++i) {
9331     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
9332     if (Mask[i] < 0)
9333       continue;
9334     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9335       // This entry crosses lanes, so there is no way to model this shuffle.
9336       return false;
9337 
9338     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9339     // Adjust second vector indices to start at LaneSize instead of Size.
9340     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
9341                                 : Mask[i] % LaneSize + LaneSize;
9342     if (RepeatedMask[i % LaneSize] < 0)
9343       // This is the first non-undef entry in this slot of a 128-bit lane.
9344       RepeatedMask[i % LaneSize] = LocalM;
9345     else if (RepeatedMask[i % LaneSize] != LocalM)
9346       // Found a mismatch with the repeated mask.
9347       return false;
9348   }
9349   return true;
9350 }
9351 
9352 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
9353 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9354 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9355                                 SmallVectorImpl<int> &RepeatedMask) {
9356   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9357 }
9358 
9359 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask)9360 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
9361   SmallVector<int, 32> RepeatedMask;
9362   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9363 }
9364 
9365 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
9366 static bool
is256BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9367 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9368                                 SmallVectorImpl<int> &RepeatedMask) {
9369   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
9370 }
9371 
9372 /// Test whether a target shuffle mask is equivalent within each sub-lane.
9373 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,unsigned EltSizeInBits,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9374 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
9375                                         unsigned EltSizeInBits,
9376                                         ArrayRef<int> Mask,
9377                                         SmallVectorImpl<int> &RepeatedMask) {
9378   int LaneSize = LaneSizeInBits / EltSizeInBits;
9379   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
9380   int Size = Mask.size();
9381   for (int i = 0; i < Size; ++i) {
9382     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
9383     if (Mask[i] == SM_SentinelUndef)
9384       continue;
9385     if (Mask[i] == SM_SentinelZero) {
9386       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
9387         return false;
9388       RepeatedMask[i % LaneSize] = SM_SentinelZero;
9389       continue;
9390     }
9391     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9392       // This entry crosses lanes, so there is no way to model this shuffle.
9393       return false;
9394 
9395     // Handle the in-lane shuffles by detecting if and when they repeat. Adjust
9396     // later vector indices to start at multiples of LaneSize instead of Size.
9397     int LaneM = Mask[i] / Size;
9398     int LocalM = (Mask[i] % LaneSize) + (LaneM * LaneSize);
9399     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
9400       // This is the first non-undef entry in this slot of a 128-bit lane.
9401       RepeatedMask[i % LaneSize] = LocalM;
9402     else if (RepeatedMask[i % LaneSize] != LocalM)
9403       // Found a mismatch with the repeated mask.
9404       return false;
9405   }
9406   return true;
9407 }
9408 
9409 /// Test whether a target shuffle mask is equivalent within each sub-lane.
9410 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)9411 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
9412                                         ArrayRef<int> Mask,
9413                                         SmallVectorImpl<int> &RepeatedMask) {
9414   return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
9415                                      Mask, RepeatedMask);
9416 }
9417 
9418 /// Checks whether the vector elements referenced by two shuffle masks are
9419 /// equivalent.
IsElementEquivalent(int MaskSize,SDValue Op,SDValue ExpectedOp,int Idx,int ExpectedIdx)9420 static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
9421                                 int Idx, int ExpectedIdx) {
9422   assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
9423          ExpectedIdx < MaskSize && "Out of range element index");
9424   if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
9425     return false;
9426 
9427   switch (Op.getOpcode()) {
9428   case ISD::BUILD_VECTOR:
9429     // If the values are build vectors, we can look through them to find
9430     // equivalent inputs that make the shuffles equivalent.
9431     // TODO: Handle MaskSize != Op.getNumOperands()?
9432     if (MaskSize == (int)Op.getNumOperands() &&
9433         MaskSize == (int)ExpectedOp.getNumOperands())
9434       return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
9435     break;
9436   case X86ISD::VBROADCAST:
9437   case X86ISD::VBROADCAST_LOAD:
9438     // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
9439     return (Op == ExpectedOp &&
9440             (int)Op.getValueType().getVectorNumElements() == MaskSize);
9441   case X86ISD::HADD:
9442   case X86ISD::HSUB:
9443   case X86ISD::FHADD:
9444   case X86ISD::FHSUB:
9445   case X86ISD::PACKSS:
9446   case X86ISD::PACKUS:
9447     // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
9448     // TODO: Handle MaskSize != NumElts?
9449     // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
9450     if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
9451       MVT VT = Op.getSimpleValueType();
9452       int NumElts = VT.getVectorNumElements();
9453       if (MaskSize == NumElts) {
9454         int NumLanes = VT.getSizeInBits() / 128;
9455         int NumEltsPerLane = NumElts / NumLanes;
9456         int NumHalfEltsPerLane = NumEltsPerLane / 2;
9457         bool SameLane =
9458             (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
9459         bool SameElt =
9460             (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
9461         return SameLane && SameElt;
9462       }
9463     }
9464     break;
9465   }
9466 
9467   return false;
9468 }
9469 
9470 /// Checks whether a shuffle mask is equivalent to an explicit list of
9471 /// arguments.
9472 ///
9473 /// This is a fast way to test a shuffle mask against a fixed pattern:
9474 ///
9475 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
9476 ///
9477 /// It returns true if the mask is exactly as wide as the argument list, and
9478 /// each element of the mask is either -1 (signifying undef) or the value given
9479 /// in the argument.
isShuffleEquivalent(ArrayRef<int> Mask,ArrayRef<int> ExpectedMask,SDValue V1=SDValue (),SDValue V2=SDValue ())9480 static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
9481                                 SDValue V1 = SDValue(),
9482                                 SDValue V2 = SDValue()) {
9483   int Size = Mask.size();
9484   if (Size != (int)ExpectedMask.size())
9485     return false;
9486 
9487   for (int i = 0; i < Size; ++i) {
9488     assert(Mask[i] >= -1 && "Out of bound mask element!");
9489     int MaskIdx = Mask[i];
9490     int ExpectedIdx = ExpectedMask[i];
9491     if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
9492       SDValue MaskV = MaskIdx < Size ? V1 : V2;
9493       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
9494       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
9495       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
9496       if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
9497         return false;
9498     }
9499   }
9500   return true;
9501 }
9502 
9503 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
9504 ///
9505 /// The masks must be exactly the same width.
9506 ///
9507 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
9508 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
9509 ///
9510 /// SM_SentinelZero is accepted as a valid negative index but must match in
9511 /// both, or via a known bits test.
isTargetShuffleEquivalent(MVT VT,ArrayRef<int> Mask,ArrayRef<int> ExpectedMask,const SelectionDAG & DAG,SDValue V1=SDValue (),SDValue V2=SDValue ())9512 static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
9513                                       ArrayRef<int> ExpectedMask,
9514                                       const SelectionDAG &DAG,
9515                                       SDValue V1 = SDValue(),
9516                                       SDValue V2 = SDValue()) {
9517   int Size = Mask.size();
9518   if (Size != (int)ExpectedMask.size())
9519     return false;
9520   assert(llvm::all_of(ExpectedMask,
9521                       [Size](int M) { return isInRange(M, 0, 2 * Size); }) &&
9522          "Illegal target shuffle mask");
9523 
9524   // Check for out-of-range target shuffle mask indices.
9525   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
9526     return false;
9527 
9528   // Don't use V1/V2 if they're not the same size as the shuffle mask type.
9529   if (V1 && (V1.getValueSizeInBits() != VT.getSizeInBits() ||
9530              !V1.getValueType().isVector()))
9531     V1 = SDValue();
9532   if (V2 && (V2.getValueSizeInBits() != VT.getSizeInBits() ||
9533              !V2.getValueType().isVector()))
9534     V2 = SDValue();
9535 
9536   APInt ZeroV1 = APInt::getZero(Size);
9537   APInt ZeroV2 = APInt::getZero(Size);
9538 
9539   for (int i = 0; i < Size; ++i) {
9540     int MaskIdx = Mask[i];
9541     int ExpectedIdx = ExpectedMask[i];
9542     if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
9543       continue;
9544     if (MaskIdx == SM_SentinelZero) {
9545       // If we need this expected index to be a zero element, then update the
9546       // relevant zero mask and perform the known bits at the end to minimize
9547       // repeated computes.
9548       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
9549       if (ExpectedV &&
9550           Size == (int)ExpectedV.getValueType().getVectorNumElements()) {
9551         int BitIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
9552         APInt &ZeroMask = ExpectedIdx < Size ? ZeroV1 : ZeroV2;
9553         ZeroMask.setBit(BitIdx);
9554         continue;
9555       }
9556     }
9557     if (MaskIdx >= 0) {
9558       SDValue MaskV = MaskIdx < Size ? V1 : V2;
9559       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
9560       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
9561       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
9562       if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
9563         continue;
9564     }
9565     return false;
9566   }
9567   return (ZeroV1.isZero() || DAG.MaskedVectorIsZero(V1, ZeroV1)) &&
9568          (ZeroV2.isZero() || DAG.MaskedVectorIsZero(V2, ZeroV2));
9569 }
9570 
9571 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
9572 // instructions.
isUnpackWdShuffleMask(ArrayRef<int> Mask,MVT VT,const SelectionDAG & DAG)9573 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT,
9574                                   const SelectionDAG &DAG) {
9575   if (VT != MVT::v8i32 && VT != MVT::v8f32)
9576     return false;
9577 
9578   SmallVector<int, 8> Unpcklwd;
9579   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
9580                           /* Unary = */ false);
9581   SmallVector<int, 8> Unpckhwd;
9582   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
9583                           /* Unary = */ false);
9584   bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd, DAG) ||
9585                          isTargetShuffleEquivalent(VT, Mask, Unpckhwd, DAG));
9586   return IsUnpackwdMask;
9587 }
9588 
is128BitUnpackShuffleMask(ArrayRef<int> Mask,const SelectionDAG & DAG)9589 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask,
9590                                       const SelectionDAG &DAG) {
9591   // Create 128-bit vector type based on mask size.
9592   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
9593   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
9594 
9595   // We can't assume a canonical shuffle mask, so try the commuted version too.
9596   SmallVector<int, 4> CommutedMask(Mask);
9597   ShuffleVectorSDNode::commuteMask(CommutedMask);
9598 
9599   // Match any of unary/binary or low/high.
9600   for (unsigned i = 0; i != 4; ++i) {
9601     SmallVector<int, 16> UnpackMask;
9602     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
9603     if (isTargetShuffleEquivalent(VT, Mask, UnpackMask, DAG) ||
9604         isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask, DAG))
9605       return true;
9606   }
9607   return false;
9608 }
9609 
9610 /// Return true if a shuffle mask chooses elements identically in its top and
9611 /// bottom halves. For example, any splat mask has the same top and bottom
9612 /// halves. If an element is undefined in only one half of the mask, the halves
9613 /// are not considered identical.
hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask)9614 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
9615   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
9616   unsigned HalfSize = Mask.size() / 2;
9617   for (unsigned i = 0; i != HalfSize; ++i) {
9618     if (Mask[i] != Mask[i + HalfSize])
9619       return false;
9620   }
9621   return true;
9622 }
9623 
9624 /// Get a 4-lane 8-bit shuffle immediate for a mask.
9625 ///
9626 /// This helper function produces an 8-bit shuffle immediate corresponding to
9627 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
9628 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
9629 /// example.
9630 ///
9631 /// NB: We rely heavily on "undef" masks preserving the input lane.
getV4X86ShuffleImm(ArrayRef<int> Mask)9632 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
9633   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
9634   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
9635   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
9636   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
9637   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
9638 
9639   // If the mask only uses one non-undef element, then fully 'splat' it to
9640   // improve later broadcast matching.
9641   int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
9642   assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
9643 
9644   int FirstElt = Mask[FirstIndex];
9645   if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
9646     return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
9647 
9648   unsigned Imm = 0;
9649   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
9650   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
9651   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
9652   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
9653   return Imm;
9654 }
9655 
getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,const SDLoc & DL,SelectionDAG & DAG)9656 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
9657                                           SelectionDAG &DAG) {
9658   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
9659 }
9660 
9661 // The Shuffle result is as follow:
9662 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
9663 // Each Zeroable's element correspond to a particular Mask's element.
9664 // As described in computeZeroableShuffleElements function.
9665 //
9666 // The function looks for a sub-mask that the nonzero elements are in
9667 // increasing order. If such sub-mask exist. The function returns true.
isNonZeroElementsInOrder(const APInt & Zeroable,ArrayRef<int> Mask,const EVT & VectorType,bool & IsZeroSideLeft)9668 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
9669                                      ArrayRef<int> Mask, const EVT &VectorType,
9670                                      bool &IsZeroSideLeft) {
9671   int NextElement = -1;
9672   // Check if the Mask's nonzero elements are in increasing order.
9673   for (int i = 0, e = Mask.size(); i < e; i++) {
9674     // Checks if the mask's zeros elements are built from only zeros.
9675     assert(Mask[i] >= -1 && "Out of bound mask element!");
9676     if (Mask[i] < 0)
9677       return false;
9678     if (Zeroable[i])
9679       continue;
9680     // Find the lowest non zero element
9681     if (NextElement < 0) {
9682       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
9683       IsZeroSideLeft = NextElement != 0;
9684     }
9685     // Exit if the mask's non zero elements are not in increasing order.
9686     if (NextElement != Mask[i])
9687       return false;
9688     NextElement++;
9689   }
9690   return true;
9691 }
9692 
9693 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
lowerShuffleWithPSHUFB(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)9694 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
9695                                       ArrayRef<int> Mask, SDValue V1,
9696                                       SDValue V2, const APInt &Zeroable,
9697                                       const X86Subtarget &Subtarget,
9698                                       SelectionDAG &DAG) {
9699   int Size = Mask.size();
9700   int LaneSize = 128 / VT.getScalarSizeInBits();
9701   const int NumBytes = VT.getSizeInBits() / 8;
9702   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
9703 
9704   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
9705          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
9706          (Subtarget.hasBWI() && VT.is512BitVector()));
9707 
9708   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
9709   // Sign bit set in i8 mask means zero element.
9710   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
9711 
9712   SDValue V;
9713   for (int i = 0; i < NumBytes; ++i) {
9714     int M = Mask[i / NumEltBytes];
9715     if (M < 0) {
9716       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
9717       continue;
9718     }
9719     if (Zeroable[i / NumEltBytes]) {
9720       PSHUFBMask[i] = ZeroMask;
9721       continue;
9722     }
9723 
9724     // We can only use a single input of V1 or V2.
9725     SDValue SrcV = (M >= Size ? V2 : V1);
9726     if (V && V != SrcV)
9727       return SDValue();
9728     V = SrcV;
9729     M %= Size;
9730 
9731     // PSHUFB can't cross lanes, ensure this doesn't happen.
9732     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
9733       return SDValue();
9734 
9735     M = M % LaneSize;
9736     M = M * NumEltBytes + (i % NumEltBytes);
9737     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
9738   }
9739   assert(V && "Failed to find a source input");
9740 
9741   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
9742   return DAG.getBitcast(
9743       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
9744                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
9745 }
9746 
9747 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
9748                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
9749                            const SDLoc &dl);
9750 
9751 // X86 has dedicated shuffle that can be lowered to VEXPAND
lowerShuffleToEXPAND(const SDLoc & DL,MVT VT,const APInt & Zeroable,ArrayRef<int> Mask,SDValue & V1,SDValue & V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)9752 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
9753                                     const APInt &Zeroable,
9754                                     ArrayRef<int> Mask, SDValue &V1,
9755                                     SDValue &V2, SelectionDAG &DAG,
9756                                     const X86Subtarget &Subtarget) {
9757   bool IsLeftZeroSide = true;
9758   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
9759                                 IsLeftZeroSide))
9760     return SDValue();
9761   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
9762   MVT IntegerType =
9763       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
9764   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
9765   unsigned NumElts = VT.getVectorNumElements();
9766   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
9767          "Unexpected number of vector elements");
9768   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
9769                               Subtarget, DAG, DL);
9770   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
9771   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
9772   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
9773 }
9774 
matchShuffleWithUNPCK(MVT VT,SDValue & V1,SDValue & V2,unsigned & UnpackOpcode,bool IsUnary,ArrayRef<int> TargetMask,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)9775 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
9776                                   unsigned &UnpackOpcode, bool IsUnary,
9777                                   ArrayRef<int> TargetMask, const SDLoc &DL,
9778                                   SelectionDAG &DAG,
9779                                   const X86Subtarget &Subtarget) {
9780   int NumElts = VT.getVectorNumElements();
9781 
9782   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
9783   for (int i = 0; i != NumElts; i += 2) {
9784     int M1 = TargetMask[i + 0];
9785     int M2 = TargetMask[i + 1];
9786     Undef1 &= (SM_SentinelUndef == M1);
9787     Undef2 &= (SM_SentinelUndef == M2);
9788     Zero1 &= isUndefOrZero(M1);
9789     Zero2 &= isUndefOrZero(M2);
9790   }
9791   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
9792          "Zeroable shuffle detected");
9793 
9794   // Attempt to match the target mask against the unpack lo/hi mask patterns.
9795   SmallVector<int, 64> Unpckl, Unpckh;
9796   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
9797   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG, V1,
9798                                 (IsUnary ? V1 : V2))) {
9799     UnpackOpcode = X86ISD::UNPCKL;
9800     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
9801     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
9802     return true;
9803   }
9804 
9805   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
9806   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG, V1,
9807                                 (IsUnary ? V1 : V2))) {
9808     UnpackOpcode = X86ISD::UNPCKH;
9809     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
9810     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
9811     return true;
9812   }
9813 
9814   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
9815   if (IsUnary && (Zero1 || Zero2)) {
9816     // Don't bother if we can blend instead.
9817     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
9818         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
9819       return false;
9820 
9821     bool MatchLo = true, MatchHi = true;
9822     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
9823       int M = TargetMask[i];
9824 
9825       // Ignore if the input is known to be zero or the index is undef.
9826       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
9827           (M == SM_SentinelUndef))
9828         continue;
9829 
9830       MatchLo &= (M == Unpckl[i]);
9831       MatchHi &= (M == Unpckh[i]);
9832     }
9833 
9834     if (MatchLo || MatchHi) {
9835       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
9836       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
9837       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
9838       return true;
9839     }
9840   }
9841 
9842   // If a binary shuffle, commute and try again.
9843   if (!IsUnary) {
9844     ShuffleVectorSDNode::commuteMask(Unpckl);
9845     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, DAG)) {
9846       UnpackOpcode = X86ISD::UNPCKL;
9847       std::swap(V1, V2);
9848       return true;
9849     }
9850 
9851     ShuffleVectorSDNode::commuteMask(Unpckh);
9852     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, DAG)) {
9853       UnpackOpcode = X86ISD::UNPCKH;
9854       std::swap(V1, V2);
9855       return true;
9856     }
9857   }
9858 
9859   return false;
9860 }
9861 
9862 // X86 has dedicated unpack instructions that can handle specific blend
9863 // operations: UNPCKH and UNPCKL.
lowerShuffleWithUNPCK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)9864 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
9865                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
9866                                      SelectionDAG &DAG) {
9867   SmallVector<int, 8> Unpckl;
9868   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
9869   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
9870     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
9871 
9872   SmallVector<int, 8> Unpckh;
9873   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
9874   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
9875     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
9876 
9877   // Commute and try again.
9878   ShuffleVectorSDNode::commuteMask(Unpckl);
9879   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
9880     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
9881 
9882   ShuffleVectorSDNode::commuteMask(Unpckh);
9883   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
9884     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
9885 
9886   return SDValue();
9887 }
9888 
9889 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
9890 /// followed by unpack 256-bit.
lowerShuffleWithUNPCK256(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)9891 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
9892                                         ArrayRef<int> Mask, SDValue V1,
9893                                         SDValue V2, SelectionDAG &DAG) {
9894   SmallVector<int, 32> Unpckl, Unpckh;
9895   createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
9896   createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
9897 
9898   unsigned UnpackOpcode;
9899   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
9900     UnpackOpcode = X86ISD::UNPCKL;
9901   else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
9902     UnpackOpcode = X86ISD::UNPCKH;
9903   else
9904     return SDValue();
9905 
9906   // This is a "natural" unpack operation (rather than the 128-bit sectored
9907   // operation implemented by AVX). We need to rearrange 64-bit chunks of the
9908   // input in order to use the x86 instruction.
9909   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
9910                             DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
9911   V1 = DAG.getBitcast(VT, V1);
9912   return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
9913 }
9914 
9915 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
9916 // source into the lower elements and zeroing the upper elements.
matchShuffleAsVTRUNC(MVT & SrcVT,MVT & DstVT,MVT VT,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget)9917 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
9918                                  ArrayRef<int> Mask, const APInt &Zeroable,
9919                                  const X86Subtarget &Subtarget) {
9920   if (!VT.is512BitVector() && !Subtarget.hasVLX())
9921     return false;
9922 
9923   unsigned NumElts = Mask.size();
9924   unsigned EltSizeInBits = VT.getScalarSizeInBits();
9925   unsigned MaxScale = 64 / EltSizeInBits;
9926 
9927   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
9928     unsigned SrcEltBits = EltSizeInBits * Scale;
9929     if (SrcEltBits < 32 && !Subtarget.hasBWI())
9930       continue;
9931     unsigned NumSrcElts = NumElts / Scale;
9932     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
9933       continue;
9934     unsigned UpperElts = NumElts - NumSrcElts;
9935     if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
9936       continue;
9937     SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
9938     SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
9939     DstVT = MVT::getIntegerVT(EltSizeInBits);
9940     if ((NumSrcElts * EltSizeInBits) >= 128) {
9941       // ISD::TRUNCATE
9942       DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
9943     } else {
9944       // X86ISD::VTRUNC
9945       DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
9946     }
9947     return true;
9948   }
9949 
9950   return false;
9951 }
9952 
9953 // Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
9954 // element padding to the final DstVT.
getAVX512TruncNode(const SDLoc & DL,MVT DstVT,SDValue Src,const X86Subtarget & Subtarget,SelectionDAG & DAG,bool ZeroUppers)9955 static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
9956                                   const X86Subtarget &Subtarget,
9957                                   SelectionDAG &DAG, bool ZeroUppers) {
9958   MVT SrcVT = Src.getSimpleValueType();
9959   MVT DstSVT = DstVT.getScalarType();
9960   unsigned NumDstElts = DstVT.getVectorNumElements();
9961   unsigned NumSrcElts = SrcVT.getVectorNumElements();
9962   unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
9963 
9964   if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
9965     return SDValue();
9966 
9967   // Perform a direct ISD::TRUNCATE if possible.
9968   if (NumSrcElts == NumDstElts)
9969     return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
9970 
9971   if (NumSrcElts > NumDstElts) {
9972     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
9973     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
9974     return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
9975   }
9976 
9977   if ((NumSrcElts * DstEltSizeInBits) >= 128) {
9978     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
9979     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
9980     return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
9981                           DstVT.getSizeInBits());
9982   }
9983 
9984   // Non-VLX targets must truncate from a 512-bit type, so we need to
9985   // widen, truncate and then possibly extract the original subvector.
9986   if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
9987     SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
9988     return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
9989   }
9990 
9991   // Fallback to a X86ISD::VTRUNC, padding if necessary.
9992   MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
9993   SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
9994   if (DstVT != TruncVT)
9995     Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
9996                            DstVT.getSizeInBits());
9997   return Trunc;
9998 }
9999 
10000 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10001 //
10002 // An example is the following:
10003 //
10004 // t0: ch = EntryToken
10005 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10006 //         t25: v4i32 = truncate t2
10007 //       t41: v8i16 = bitcast t25
10008 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10009 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10010 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10011 //   t18: v2i64 = bitcast t51
10012 //
10013 // One can just use a single vpmovdw instruction, without avx512vl we need to
10014 // use the zmm variant and extract the lower subvector, padding with zeroes.
10015 // TODO: Merge with lowerShuffleAsVTRUNC.
lowerShuffleWithVPMOV(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10016 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
10017                                      SDValue V2, ArrayRef<int> Mask,
10018                                      const APInt &Zeroable,
10019                                      const X86Subtarget &Subtarget,
10020                                      SelectionDAG &DAG) {
10021   assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
10022   if (!Subtarget.hasAVX512())
10023     return SDValue();
10024 
10025   unsigned NumElts = VT.getVectorNumElements();
10026   unsigned EltSizeInBits = VT.getScalarSizeInBits();
10027   unsigned MaxScale = 64 / EltSizeInBits;
10028   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10029     unsigned SrcEltBits = EltSizeInBits * Scale;
10030     unsigned NumSrcElts = NumElts / Scale;
10031     unsigned UpperElts = NumElts - NumSrcElts;
10032     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
10033         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10034       continue;
10035 
10036     // Attempt to find a matching source truncation, but as a fall back VLX
10037     // cases can use the VPMOV directly.
10038     SDValue Src = peekThroughBitcasts(V1);
10039     if (Src.getOpcode() == ISD::TRUNCATE &&
10040         Src.getScalarValueSizeInBits() == SrcEltBits) {
10041       Src = Src.getOperand(0);
10042     } else if (Subtarget.hasVLX()) {
10043       MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
10044       MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
10045       Src = DAG.getBitcast(SrcVT, Src);
10046       // Don't do this if PACKSS/PACKUS could perform it cheaper.
10047       if (Scale == 2 &&
10048           ((DAG.ComputeNumSignBits(Src) > EltSizeInBits) ||
10049            (DAG.computeKnownBits(Src).countMinLeadingZeros() >= EltSizeInBits)))
10050         return SDValue();
10051     } else
10052       return SDValue();
10053 
10054     // VPMOVWB is only available with avx512bw.
10055     if (!Subtarget.hasBWI() && Src.getScalarValueSizeInBits() < 32)
10056       return SDValue();
10057 
10058     bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
10059     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
10060   }
10061 
10062   return SDValue();
10063 }
10064 
10065 // Attempt to match binary shuffle patterns as a truncate.
lowerShuffleAsVTRUNC(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10066 static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
10067                                     SDValue V2, ArrayRef<int> Mask,
10068                                     const APInt &Zeroable,
10069                                     const X86Subtarget &Subtarget,
10070                                     SelectionDAG &DAG) {
10071   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10072          "Unexpected VTRUNC type");
10073   if (!Subtarget.hasAVX512())
10074     return SDValue();
10075 
10076   unsigned NumElts = VT.getVectorNumElements();
10077   unsigned EltSizeInBits = VT.getScalarSizeInBits();
10078   unsigned MaxScale = 64 / EltSizeInBits;
10079   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
10080     // TODO: Support non-BWI VPMOVWB truncations?
10081     unsigned SrcEltBits = EltSizeInBits * Scale;
10082     if (SrcEltBits < 32 && !Subtarget.hasBWI())
10083       continue;
10084 
10085     // Match shuffle <Ofs,Ofs+Scale,Ofs+2*Scale,..,undef_or_zero,undef_or_zero>
10086     // Bail if the V2 elements are undef.
10087     unsigned NumHalfSrcElts = NumElts / Scale;
10088     unsigned NumSrcElts = 2 * NumHalfSrcElts;
10089     for (unsigned Offset = 0; Offset != Scale; ++Offset) {
10090       if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, Offset, Scale) ||
10091           isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
10092         continue;
10093 
10094       // The elements beyond the truncation must be undef/zero.
10095       unsigned UpperElts = NumElts - NumSrcElts;
10096       if (UpperElts > 0 &&
10097           !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnes())
10098         continue;
10099       bool UndefUppers =
10100           UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
10101 
10102       // For offset truncations, ensure that the concat is cheap.
10103       if (Offset) {
10104         auto IsCheapConcat = [&](SDValue Lo, SDValue Hi) {
10105           if (Lo.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
10106               Hi.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10107             return Lo.getOperand(0) == Hi.getOperand(0);
10108           if (ISD::isNormalLoad(Lo.getNode()) &&
10109               ISD::isNormalLoad(Hi.getNode())) {
10110             auto *LDLo = cast<LoadSDNode>(Lo);
10111             auto *LDHi = cast<LoadSDNode>(Hi);
10112             return DAG.areNonVolatileConsecutiveLoads(
10113                 LDHi, LDLo, Lo.getValueType().getStoreSize(), 1);
10114           }
10115           return false;
10116         };
10117         if (!IsCheapConcat(V1, V2))
10118           continue;
10119       }
10120 
10121       // As we're using both sources then we need to concat them together
10122       // and truncate from the double-sized src.
10123       MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
10124       SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
10125 
10126       MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
10127       MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
10128       Src = DAG.getBitcast(SrcVT, Src);
10129 
10130       // Shift the offset'd elements into place for the truncation.
10131       // TODO: Use getTargetVShiftByConstNode.
10132       if (Offset)
10133         Src = DAG.getNode(
10134             X86ISD::VSRLI, DL, SrcVT, Src,
10135             DAG.getTargetConstant(Offset * EltSizeInBits, DL, MVT::i8));
10136 
10137       return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
10138     }
10139   }
10140 
10141   return SDValue();
10142 }
10143 
10144 /// Check whether a compaction lowering can be done by dropping even/odd
10145 /// elements and compute how many times even/odd elements must be dropped.
10146 ///
10147 /// This handles shuffles which take every Nth element where N is a power of
10148 /// two. Example shuffle masks:
10149 ///
10150 /// (even)
10151 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
10152 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
10153 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
10154 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
10155 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
10156 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
10157 ///
10158 /// (odd)
10159 ///  N = 1:  1,  3,  5,  7,  9, 11, 13, 15,  0,  2,  4,  6,  8, 10, 12, 14
10160 ///  N = 1:  1,  3,  5,  7,  9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31
10161 ///
10162 /// Any of these lanes can of course be undef.
10163 ///
10164 /// This routine only supports N <= 3.
10165 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
10166 /// for larger N.
10167 ///
10168 /// \returns N above, or the number of times even/odd elements must be dropped
10169 /// if there is such a number. Otherwise returns zero.
canLowerByDroppingElements(ArrayRef<int> Mask,bool MatchEven,bool IsSingleInput)10170 static int canLowerByDroppingElements(ArrayRef<int> Mask, bool MatchEven,
10171                                       bool IsSingleInput) {
10172   // The modulus for the shuffle vector entries is based on whether this is
10173   // a single input or not.
10174   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
10175   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
10176          "We should only be called with masks with a power-of-2 size!");
10177 
10178   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
10179   int Offset = MatchEven ? 0 : 1;
10180 
10181   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
10182   // and 2^3 simultaneously. This is because we may have ambiguity with
10183   // partially undef inputs.
10184   bool ViableForN[3] = {true, true, true};
10185 
10186   for (int i = 0, e = Mask.size(); i < e; ++i) {
10187     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
10188     // want.
10189     if (Mask[i] < 0)
10190       continue;
10191 
10192     bool IsAnyViable = false;
10193     for (unsigned j = 0; j != std::size(ViableForN); ++j)
10194       if (ViableForN[j]) {
10195         uint64_t N = j + 1;
10196 
10197         // The shuffle mask must be equal to (i * 2^N) % M.
10198         if ((uint64_t)(Mask[i] - Offset) == (((uint64_t)i << N) & ModMask))
10199           IsAnyViable = true;
10200         else
10201           ViableForN[j] = false;
10202       }
10203     // Early exit if we exhaust the possible powers of two.
10204     if (!IsAnyViable)
10205       break;
10206   }
10207 
10208   for (unsigned j = 0; j != std::size(ViableForN); ++j)
10209     if (ViableForN[j])
10210       return j + 1;
10211 
10212   // Return 0 as there is no viable power of two.
10213   return 0;
10214 }
10215 
10216 // X86 has dedicated pack instructions that can handle specific truncation
10217 // operations: PACKSS and PACKUS.
10218 // Checks for compaction shuffle masks if MaxStages > 1.
10219 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
matchShuffleWithPACK(MVT VT,MVT & SrcVT,SDValue & V1,SDValue & V2,unsigned & PackOpcode,ArrayRef<int> TargetMask,const SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned MaxStages=1)10220 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
10221                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
10222                                  const SelectionDAG &DAG,
10223                                  const X86Subtarget &Subtarget,
10224                                  unsigned MaxStages = 1) {
10225   unsigned NumElts = VT.getVectorNumElements();
10226   unsigned BitSize = VT.getScalarSizeInBits();
10227   assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
10228          "Illegal maximum compaction");
10229 
10230   auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
10231     unsigned NumSrcBits = PackVT.getScalarSizeInBits();
10232     unsigned NumPackedBits = NumSrcBits - BitSize;
10233     N1 = peekThroughBitcasts(N1);
10234     N2 = peekThroughBitcasts(N2);
10235     unsigned NumBits1 = N1.getScalarValueSizeInBits();
10236     unsigned NumBits2 = N2.getScalarValueSizeInBits();
10237     bool IsZero1 = llvm::isNullOrNullSplat(N1, /*AllowUndefs*/ false);
10238     bool IsZero2 = llvm::isNullOrNullSplat(N2, /*AllowUndefs*/ false);
10239     if ((!N1.isUndef() && !IsZero1 && NumBits1 != NumSrcBits) ||
10240         (!N2.isUndef() && !IsZero2 && NumBits2 != NumSrcBits))
10241       return false;
10242     if (Subtarget.hasSSE41() || BitSize == 8) {
10243       APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
10244       if ((N1.isUndef() || IsZero1 || DAG.MaskedValueIsZero(N1, ZeroMask)) &&
10245           (N2.isUndef() || IsZero2 || DAG.MaskedValueIsZero(N2, ZeroMask))) {
10246         V1 = N1;
10247         V2 = N2;
10248         SrcVT = PackVT;
10249         PackOpcode = X86ISD::PACKUS;
10250         return true;
10251       }
10252     }
10253     bool IsAllOnes1 = llvm::isAllOnesOrAllOnesSplat(N1, /*AllowUndefs*/ false);
10254     bool IsAllOnes2 = llvm::isAllOnesOrAllOnesSplat(N2, /*AllowUndefs*/ false);
10255     if ((N1.isUndef() || IsZero1 || IsAllOnes1 ||
10256          DAG.ComputeNumSignBits(N1) > NumPackedBits) &&
10257         (N2.isUndef() || IsZero2 || IsAllOnes2 ||
10258          DAG.ComputeNumSignBits(N2) > NumPackedBits)) {
10259       V1 = N1;
10260       V2 = N2;
10261       SrcVT = PackVT;
10262       PackOpcode = X86ISD::PACKSS;
10263       return true;
10264     }
10265     return false;
10266   };
10267 
10268   // Attempt to match against wider and wider compaction patterns.
10269   for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
10270     MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
10271     MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
10272 
10273     // Try binary shuffle.
10274     SmallVector<int, 32> BinaryMask;
10275     createPackShuffleMask(VT, BinaryMask, false, NumStages);
10276     if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, DAG, V1, V2))
10277       if (MatchPACK(V1, V2, PackVT))
10278         return true;
10279 
10280     // Try unary shuffle.
10281     SmallVector<int, 32> UnaryMask;
10282     createPackShuffleMask(VT, UnaryMask, true, NumStages);
10283     if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, DAG, V1))
10284       if (MatchPACK(V1, V1, PackVT))
10285         return true;
10286   }
10287 
10288   return false;
10289 }
10290 
lowerShuffleWithPACK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)10291 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
10292                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
10293                                     const X86Subtarget &Subtarget) {
10294   MVT PackVT;
10295   unsigned PackOpcode;
10296   unsigned SizeBits = VT.getSizeInBits();
10297   unsigned EltBits = VT.getScalarSizeInBits();
10298   unsigned MaxStages = Log2_32(64 / EltBits);
10299   if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
10300                             Subtarget, MaxStages))
10301     return SDValue();
10302 
10303   unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
10304   unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
10305 
10306   // Don't lower multi-stage packs on AVX512, truncation is better.
10307   if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
10308     return SDValue();
10309 
10310   // Pack to the largest type possible:
10311   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
10312   unsigned MaxPackBits = 16;
10313   if (CurrentEltBits > 16 &&
10314       (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
10315     MaxPackBits = 32;
10316 
10317   // Repeatedly pack down to the target size.
10318   SDValue Res;
10319   for (unsigned i = 0; i != NumStages; ++i) {
10320     unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
10321     unsigned NumSrcElts = SizeBits / SrcEltBits;
10322     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
10323     MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
10324     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
10325     MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
10326     Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
10327                       DAG.getBitcast(SrcVT, V2));
10328     V1 = V2 = Res;
10329     CurrentEltBits /= 2;
10330   }
10331   assert(Res && Res.getValueType() == VT &&
10332          "Failed to lower compaction shuffle");
10333   return Res;
10334 }
10335 
10336 /// Try to emit a bitmask instruction for a shuffle.
10337 ///
10338 /// This handles cases where we can model a blend exactly as a bitmask due to
10339 /// one of the inputs being zeroable.
lowerShuffleAsBitMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10340 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
10341                                      SDValue V2, ArrayRef<int> Mask,
10342                                      const APInt &Zeroable,
10343                                      const X86Subtarget &Subtarget,
10344                                      SelectionDAG &DAG) {
10345   MVT MaskVT = VT;
10346   MVT EltVT = VT.getVectorElementType();
10347   SDValue Zero, AllOnes;
10348   // Use f64 if i64 isn't legal.
10349   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
10350     EltVT = MVT::f64;
10351     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
10352   }
10353 
10354   MVT LogicVT = VT;
10355   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
10356     Zero = DAG.getConstantFP(0.0, DL, EltVT);
10357     APFloat AllOnesValue =
10358         APFloat::getAllOnesValue(SelectionDAG::EVTToAPFloatSemantics(EltVT));
10359     AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
10360     LogicVT =
10361         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
10362   } else {
10363     Zero = DAG.getConstant(0, DL, EltVT);
10364     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10365   }
10366 
10367   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
10368   SDValue V;
10369   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10370     if (Zeroable[i])
10371       continue;
10372     if (Mask[i] % Size != i)
10373       return SDValue(); // Not a blend.
10374     if (!V)
10375       V = Mask[i] < Size ? V1 : V2;
10376     else if (V != (Mask[i] < Size ? V1 : V2))
10377       return SDValue(); // Can only let one input through the mask.
10378 
10379     VMaskOps[i] = AllOnes;
10380   }
10381   if (!V)
10382     return SDValue(); // No non-zeroable elements!
10383 
10384   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
10385   VMask = DAG.getBitcast(LogicVT, VMask);
10386   V = DAG.getBitcast(LogicVT, V);
10387   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
10388   return DAG.getBitcast(VT, And);
10389 }
10390 
10391 /// Try to emit a blend instruction for a shuffle using bit math.
10392 ///
10393 /// This is used as a fallback approach when first class blend instructions are
10394 /// unavailable. Currently it is only suitable for integer vectors, but could
10395 /// be generalized for floating point vectors if desirable.
lowerShuffleAsBitBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)10396 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
10397                                       SDValue V2, ArrayRef<int> Mask,
10398                                       SelectionDAG &DAG) {
10399   assert(VT.isInteger() && "Only supports integer vector types!");
10400   MVT EltVT = VT.getVectorElementType();
10401   SDValue Zero = DAG.getConstant(0, DL, EltVT);
10402   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10403   SmallVector<SDValue, 16> MaskOps;
10404   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10405     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
10406       return SDValue(); // Shuffled input!
10407     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
10408   }
10409 
10410   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
10411   return getBitSelect(DL, VT, V1, V2, V1Mask, DAG);
10412 }
10413 
10414 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
10415                                     SDValue PreservedSrc,
10416                                     const X86Subtarget &Subtarget,
10417                                     SelectionDAG &DAG);
10418 
matchShuffleAsBlend(MVT VT,SDValue V1,SDValue V2,MutableArrayRef<int> Mask,const APInt & Zeroable,bool & ForceV1Zero,bool & ForceV2Zero,uint64_t & BlendMask)10419 static bool matchShuffleAsBlend(MVT VT, SDValue V1, SDValue V2,
10420                                 MutableArrayRef<int> Mask,
10421                                 const APInt &Zeroable, bool &ForceV1Zero,
10422                                 bool &ForceV2Zero, uint64_t &BlendMask) {
10423   bool V1IsZeroOrUndef =
10424       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
10425   bool V2IsZeroOrUndef =
10426       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
10427 
10428   BlendMask = 0;
10429   ForceV1Zero = false, ForceV2Zero = false;
10430   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
10431 
10432   int NumElts = Mask.size();
10433   int NumLanes = VT.getSizeInBits() / 128;
10434   int NumEltsPerLane = NumElts / NumLanes;
10435   assert((NumLanes * NumEltsPerLane) == NumElts && "Value type mismatch");
10436 
10437   // For 32/64-bit elements, if we only reference one input (plus any undefs),
10438   // then ensure the blend mask part for that lane just references that input.
10439   bool ForceWholeLaneMasks =
10440       VT.is256BitVector() && VT.getScalarSizeInBits() >= 32;
10441 
10442   // Attempt to generate the binary blend mask. If an input is zero then
10443   // we can use any lane.
10444   for (int Lane = 0; Lane != NumLanes; ++Lane) {
10445     // Keep track of the inputs used per lane.
10446     bool LaneV1InUse = false;
10447     bool LaneV2InUse = false;
10448     uint64_t LaneBlendMask = 0;
10449     for (int LaneElt = 0; LaneElt != NumEltsPerLane; ++LaneElt) {
10450       int Elt = (Lane * NumEltsPerLane) + LaneElt;
10451       int M = Mask[Elt];
10452       if (M == SM_SentinelUndef)
10453         continue;
10454       if (M == Elt || (0 <= M && M < NumElts &&
10455                      IsElementEquivalent(NumElts, V1, V1, M, Elt))) {
10456         Mask[Elt] = Elt;
10457         LaneV1InUse = true;
10458         continue;
10459       }
10460       if (M == (Elt + NumElts) ||
10461           (NumElts <= M &&
10462            IsElementEquivalent(NumElts, V2, V2, M - NumElts, Elt))) {
10463         LaneBlendMask |= 1ull << LaneElt;
10464         Mask[Elt] = Elt + NumElts;
10465         LaneV2InUse = true;
10466         continue;
10467       }
10468       if (Zeroable[Elt]) {
10469         if (V1IsZeroOrUndef) {
10470           ForceV1Zero = true;
10471           Mask[Elt] = Elt;
10472           LaneV1InUse = true;
10473           continue;
10474         }
10475         if (V2IsZeroOrUndef) {
10476           ForceV2Zero = true;
10477           LaneBlendMask |= 1ull << LaneElt;
10478           Mask[Elt] = Elt + NumElts;
10479           LaneV2InUse = true;
10480           continue;
10481         }
10482       }
10483       return false;
10484     }
10485 
10486     // If we only used V2 then splat the lane blend mask to avoid any demanded
10487     // elts from V1 in this lane (the V1 equivalent is implicit with a zero
10488     // blend mask bit).
10489     if (ForceWholeLaneMasks && LaneV2InUse && !LaneV1InUse)
10490       LaneBlendMask = (1ull << NumEltsPerLane) - 1;
10491 
10492     BlendMask |= LaneBlendMask << (Lane * NumEltsPerLane);
10493   }
10494   return true;
10495 }
10496 
scaleVectorShuffleBlendMask(uint64_t BlendMask,int Size,int Scale)10497 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
10498                                             int Scale) {
10499   uint64_t ScaledMask = 0;
10500   for (int i = 0; i != Size; ++i)
10501     if (BlendMask & (1ull << i))
10502       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
10503   return ScaledMask;
10504 }
10505 
10506 /// Try to emit a blend instruction for a shuffle.
10507 ///
10508 /// This doesn't do any checks for the availability of instructions for blending
10509 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
10510 /// be matched in the backend with the type given. What it does check for is
10511 /// that the shuffle mask is a blend, or convertible into a blend with zero.
lowerShuffleAsBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Original,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)10512 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
10513                                    SDValue V2, ArrayRef<int> Original,
10514                                    const APInt &Zeroable,
10515                                    const X86Subtarget &Subtarget,
10516                                    SelectionDAG &DAG) {
10517   uint64_t BlendMask = 0;
10518   bool ForceV1Zero = false, ForceV2Zero = false;
10519   SmallVector<int, 64> Mask(Original);
10520   if (!matchShuffleAsBlend(VT, V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
10521                            BlendMask))
10522     return SDValue();
10523 
10524   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
10525   if (ForceV1Zero)
10526     V1 = getZeroVector(VT, Subtarget, DAG, DL);
10527   if (ForceV2Zero)
10528     V2 = getZeroVector(VT, Subtarget, DAG, DL);
10529 
10530   unsigned NumElts = VT.getVectorNumElements();
10531 
10532   switch (VT.SimpleTy) {
10533   case MVT::v4i64:
10534   case MVT::v8i32:
10535     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
10536     [[fallthrough]];
10537   case MVT::v4f64:
10538   case MVT::v8f32:
10539     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
10540     [[fallthrough]];
10541   case MVT::v2f64:
10542   case MVT::v2i64:
10543   case MVT::v4f32:
10544   case MVT::v4i32:
10545   case MVT::v8i16:
10546     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
10547     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
10548                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
10549   case MVT::v16i16: {
10550     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
10551     SmallVector<int, 8> RepeatedMask;
10552     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10553       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
10554       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
10555       BlendMask = 0;
10556       for (int i = 0; i < 8; ++i)
10557         if (RepeatedMask[i] >= 8)
10558           BlendMask |= 1ull << i;
10559       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10560                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
10561     }
10562     // Use PBLENDW for lower/upper lanes and then blend lanes.
10563     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
10564     // merge to VSELECT where useful.
10565     uint64_t LoMask = BlendMask & 0xFF;
10566     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
10567     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
10568       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10569                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
10570       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10571                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
10572       return DAG.getVectorShuffle(
10573           MVT::v16i16, DL, Lo, Hi,
10574           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
10575     }
10576     [[fallthrough]];
10577   }
10578   case MVT::v32i8:
10579     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
10580     [[fallthrough]];
10581   case MVT::v16i8: {
10582     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
10583 
10584     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
10585     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
10586                                                Subtarget, DAG))
10587       return Masked;
10588 
10589     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
10590       MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
10591       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10592       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10593     }
10594 
10595     // If we have VPTERNLOG, we can use that as a bit blend.
10596     if (Subtarget.hasVLX())
10597       if (SDValue BitBlend =
10598               lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
10599         return BitBlend;
10600 
10601     // Scale the blend by the number of bytes per element.
10602     int Scale = VT.getScalarSizeInBits() / 8;
10603 
10604     // This form of blend is always done on bytes. Compute the byte vector
10605     // type.
10606     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10607 
10608     // x86 allows load folding with blendvb from the 2nd source operand. But
10609     // we are still using LLVM select here (see comment below), so that's V1.
10610     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
10611     // allow that load-folding possibility.
10612     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
10613       ShuffleVectorSDNode::commuteMask(Mask);
10614       std::swap(V1, V2);
10615     }
10616 
10617     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
10618     // mix of LLVM's code generator and the x86 backend. We tell the code
10619     // generator that boolean values in the elements of an x86 vector register
10620     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
10621     // mapping a select to operand #1, and 'false' mapping to operand #2. The
10622     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
10623     // of the element (the remaining are ignored) and 0 in that high bit would
10624     // mean operand #1 while 1 in the high bit would mean operand #2. So while
10625     // the LLVM model for boolean values in vector elements gets the relevant
10626     // bit set, it is set backwards and over constrained relative to x86's
10627     // actual model.
10628     SmallVector<SDValue, 32> VSELECTMask;
10629     for (int i = 0, Size = Mask.size(); i < Size; ++i)
10630       for (int j = 0; j < Scale; ++j)
10631         VSELECTMask.push_back(
10632             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
10633                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
10634                                           MVT::i8));
10635 
10636     V1 = DAG.getBitcast(BlendVT, V1);
10637     V2 = DAG.getBitcast(BlendVT, V2);
10638     return DAG.getBitcast(
10639         VT,
10640         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
10641                       V1, V2));
10642   }
10643   case MVT::v16f32:
10644   case MVT::v8f64:
10645   case MVT::v8i64:
10646   case MVT::v16i32:
10647   case MVT::v32i16:
10648   case MVT::v64i8: {
10649     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
10650     bool OptForSize = DAG.shouldOptForSize();
10651     if (!OptForSize) {
10652       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
10653                                                  Subtarget, DAG))
10654         return Masked;
10655     }
10656 
10657     // Otherwise load an immediate into a GPR, cast to k-register, and use a
10658     // masked move.
10659     MVT IntegerType = MVT::getIntegerVT(std::max<unsigned>(NumElts, 8));
10660     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10661     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10662   }
10663   default:
10664     llvm_unreachable("Not a supported integer vector type!");
10665   }
10666 }
10667 
10668 /// Try to lower as a blend of elements from two inputs followed by
10669 /// a single-input permutation.
10670 ///
10671 /// This matches the pattern where we can blend elements from two inputs and
10672 /// then reduce the shuffle to a single-input permutation.
lowerShuffleAsBlendAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,bool ImmBlends=false)10673 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
10674                                              SDValue V1, SDValue V2,
10675                                              ArrayRef<int> Mask,
10676                                              SelectionDAG &DAG,
10677                                              bool ImmBlends = false) {
10678   // We build up the blend mask while checking whether a blend is a viable way
10679   // to reduce the shuffle.
10680   SmallVector<int, 32> BlendMask(Mask.size(), -1);
10681   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
10682 
10683   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10684     if (Mask[i] < 0)
10685       continue;
10686 
10687     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
10688 
10689     if (BlendMask[Mask[i] % Size] < 0)
10690       BlendMask[Mask[i] % Size] = Mask[i];
10691     else if (BlendMask[Mask[i] % Size] != Mask[i])
10692       return SDValue(); // Can't blend in the needed input!
10693 
10694     PermuteMask[i] = Mask[i] % Size;
10695   }
10696 
10697   // If only immediate blends, then bail if the blend mask can't be widened to
10698   // i16.
10699   unsigned EltSize = VT.getScalarSizeInBits();
10700   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
10701     return SDValue();
10702 
10703   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
10704   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
10705 }
10706 
10707 /// Try to lower as an unpack of elements from two inputs followed by
10708 /// a single-input permutation.
10709 ///
10710 /// This matches the pattern where we can unpack elements from two inputs and
10711 /// then reduce the shuffle to a single-input (wider) permutation.
lowerShuffleAsUNPCKAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)10712 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
10713                                              SDValue V1, SDValue V2,
10714                                              ArrayRef<int> Mask,
10715                                              SelectionDAG &DAG) {
10716   int NumElts = Mask.size();
10717   int NumLanes = VT.getSizeInBits() / 128;
10718   int NumLaneElts = NumElts / NumLanes;
10719   int NumHalfLaneElts = NumLaneElts / 2;
10720 
10721   bool MatchLo = true, MatchHi = true;
10722   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
10723 
10724   // Determine UNPCKL/UNPCKH type and operand order.
10725   for (int Elt = 0; Elt != NumElts; ++Elt) {
10726     int M = Mask[Elt];
10727     if (M < 0)
10728       continue;
10729 
10730     // Normalize the mask value depending on whether it's V1 or V2.
10731     int NormM = M;
10732     SDValue &Op = Ops[Elt & 1];
10733     if (M < NumElts && (Op.isUndef() || Op == V1))
10734       Op = V1;
10735     else if (NumElts <= M && (Op.isUndef() || Op == V2)) {
10736       Op = V2;
10737       NormM -= NumElts;
10738     } else
10739       return SDValue();
10740 
10741     bool MatchLoAnyLane = false, MatchHiAnyLane = false;
10742     for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
10743       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
10744       MatchLoAnyLane |= isUndefOrInRange(NormM, Lo, Mid);
10745       MatchHiAnyLane |= isUndefOrInRange(NormM, Mid, Hi);
10746       if (MatchLoAnyLane || MatchHiAnyLane) {
10747         assert((MatchLoAnyLane ^ MatchHiAnyLane) &&
10748                "Failed to match UNPCKLO/UNPCKHI");
10749         break;
10750       }
10751     }
10752     MatchLo &= MatchLoAnyLane;
10753     MatchHi &= MatchHiAnyLane;
10754     if (!MatchLo && !MatchHi)
10755       return SDValue();
10756   }
10757   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
10758 
10759   // Element indices have changed after unpacking. Calculate permute mask
10760   // so that they will be put back to the position as dictated by the
10761   // original shuffle mask indices.
10762   SmallVector<int, 32> PermuteMask(NumElts, -1);
10763   for (int Elt = 0; Elt != NumElts; ++Elt) {
10764     int M = Mask[Elt];
10765     if (M < 0)
10766       continue;
10767     int NormM = M;
10768     if (NumElts <= M)
10769       NormM -= NumElts;
10770     bool IsFirstOp = M < NumElts;
10771     int BaseMaskElt =
10772         NumLaneElts * (NormM / NumLaneElts) + (2 * (NormM % NumHalfLaneElts));
10773     if ((IsFirstOp && V1 == Ops[0]) || (!IsFirstOp && V2 == Ops[0]))
10774       PermuteMask[Elt] = BaseMaskElt;
10775     else if ((IsFirstOp && V1 == Ops[1]) || (!IsFirstOp && V2 == Ops[1]))
10776       PermuteMask[Elt] = BaseMaskElt + 1;
10777     assert(PermuteMask[Elt] != -1 &&
10778            "Input mask element is defined but failed to assign permute mask");
10779   }
10780 
10781   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10782   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
10783   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
10784 }
10785 
10786 /// Try to lower a shuffle as a permute of the inputs followed by an
10787 /// UNPCK instruction.
10788 ///
10789 /// This specifically targets cases where we end up with alternating between
10790 /// the two inputs, and so can permute them into something that feeds a single
10791 /// UNPCK instruction. Note that this routine only targets integer vectors
10792 /// because for floating point vectors we have a generalized SHUFPS lowering
10793 /// strategy that handles everything that doesn't *exactly* match an unpack,
10794 /// making this clever lowering unnecessary.
lowerShuffleAsPermuteAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)10795 static SDValue lowerShuffleAsPermuteAndUnpack(const SDLoc &DL, MVT VT,
10796                                               SDValue V1, SDValue V2,
10797                                               ArrayRef<int> Mask,
10798                                               const X86Subtarget &Subtarget,
10799                                               SelectionDAG &DAG) {
10800   int Size = Mask.size();
10801   assert(Mask.size() >= 2 && "Single element masks are invalid.");
10802 
10803   // This routine only supports 128-bit integer dual input vectors.
10804   if (VT.isFloatingPoint() || !VT.is128BitVector() || V2.isUndef())
10805     return SDValue();
10806 
10807   int NumLoInputs =
10808       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
10809   int NumHiInputs =
10810       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
10811 
10812   bool UnpackLo = NumLoInputs >= NumHiInputs;
10813 
10814   auto TryUnpack = [&](int ScalarSize, int Scale) {
10815     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
10816     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
10817 
10818     for (int i = 0; i < Size; ++i) {
10819       if (Mask[i] < 0)
10820         continue;
10821 
10822       // Each element of the unpack contains Scale elements from this mask.
10823       int UnpackIdx = i / Scale;
10824 
10825       // We only handle the case where V1 feeds the first slots of the unpack.
10826       // We rely on canonicalization to ensure this is the case.
10827       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
10828         return SDValue();
10829 
10830       // Setup the mask for this input. The indexing is tricky as we have to
10831       // handle the unpack stride.
10832       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
10833       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
10834           Mask[i] % Size;
10835     }
10836 
10837     // If we will have to shuffle both inputs to use the unpack, check whether
10838     // we can just unpack first and shuffle the result. If so, skip this unpack.
10839     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
10840         !isNoopShuffleMask(V2Mask))
10841       return SDValue();
10842 
10843     // Shuffle the inputs into place.
10844     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
10845     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
10846 
10847     // Cast the inputs to the type we will use to unpack them.
10848     MVT UnpackVT =
10849         MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
10850     V1 = DAG.getBitcast(UnpackVT, V1);
10851     V2 = DAG.getBitcast(UnpackVT, V2);
10852 
10853     // Unpack the inputs and cast the result back to the desired type.
10854     return DAG.getBitcast(
10855         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
10856                         UnpackVT, V1, V2));
10857   };
10858 
10859   // We try each unpack from the largest to the smallest to try and find one
10860   // that fits this mask.
10861   int OrigScalarSize = VT.getScalarSizeInBits();
10862   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
10863     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
10864       return Unpack;
10865 
10866   // If we're shuffling with a zero vector then we're better off not doing
10867   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
10868   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
10869       ISD::isBuildVectorAllZeros(V2.getNode()))
10870     return SDValue();
10871 
10872   // If none of the unpack-rooted lowerings worked (or were profitable) try an
10873   // initial unpack.
10874   if (NumLoInputs == 0 || NumHiInputs == 0) {
10875     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
10876            "We have to have *some* inputs!");
10877     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
10878 
10879     // FIXME: We could consider the total complexity of the permute of each
10880     // possible unpacking. Or at the least we should consider how many
10881     // half-crossings are created.
10882     // FIXME: We could consider commuting the unpacks.
10883 
10884     SmallVector<int, 32> PermMask((unsigned)Size, -1);
10885     for (int i = 0; i < Size; ++i) {
10886       if (Mask[i] < 0)
10887         continue;
10888 
10889       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
10890 
10891       PermMask[i] =
10892           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
10893     }
10894     return DAG.getVectorShuffle(
10895         VT, DL,
10896         DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL, DL, VT,
10897                     V1, V2),
10898         DAG.getUNDEF(VT), PermMask);
10899   }
10900 
10901   return SDValue();
10902 }
10903 
10904 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
10905 /// permuting the elements of the result in place.
lowerShuffleAsByteRotateAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)10906 static SDValue lowerShuffleAsByteRotateAndPermute(
10907     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10908     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
10909   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
10910       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
10911       (VT.is512BitVector() && !Subtarget.hasBWI()))
10912     return SDValue();
10913 
10914   // We don't currently support lane crossing permutes.
10915   if (is128BitLaneCrossingShuffleMask(VT, Mask))
10916     return SDValue();
10917 
10918   int Scale = VT.getScalarSizeInBits() / 8;
10919   int NumLanes = VT.getSizeInBits() / 128;
10920   int NumElts = VT.getVectorNumElements();
10921   int NumEltsPerLane = NumElts / NumLanes;
10922 
10923   // Determine range of mask elts.
10924   bool Blend1 = true;
10925   bool Blend2 = true;
10926   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
10927   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
10928   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
10929     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
10930       int M = Mask[Lane + Elt];
10931       if (M < 0)
10932         continue;
10933       if (M < NumElts) {
10934         Blend1 &= (M == (Lane + Elt));
10935         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
10936         M = M % NumEltsPerLane;
10937         Range1.first = std::min(Range1.first, M);
10938         Range1.second = std::max(Range1.second, M);
10939       } else {
10940         M -= NumElts;
10941         Blend2 &= (M == (Lane + Elt));
10942         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
10943         M = M % NumEltsPerLane;
10944         Range2.first = std::min(Range2.first, M);
10945         Range2.second = std::max(Range2.second, M);
10946       }
10947     }
10948   }
10949 
10950   // Bail if we don't need both elements.
10951   // TODO - it might be worth doing this for unary shuffles if the permute
10952   // can be widened.
10953   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
10954       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
10955     return SDValue();
10956 
10957   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
10958     return SDValue();
10959 
10960   // Rotate the 2 ops so we can access both ranges, then permute the result.
10961   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
10962     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10963     SDValue Rotate = DAG.getBitcast(
10964         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
10965                         DAG.getBitcast(ByteVT, Lo),
10966                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
10967     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
10968     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
10969       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
10970         int M = Mask[Lane + Elt];
10971         if (M < 0)
10972           continue;
10973         if (M < NumElts)
10974           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
10975         else
10976           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
10977       }
10978     }
10979     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
10980   };
10981 
10982   // Check if the ranges are small enough to rotate from either direction.
10983   if (Range2.second < Range1.first)
10984     return RotateAndPermute(V1, V2, Range1.first, 0);
10985   if (Range1.second < Range2.first)
10986     return RotateAndPermute(V2, V1, Range2.first, NumElts);
10987   return SDValue();
10988 }
10989 
isBroadcastShuffleMask(ArrayRef<int> Mask)10990 static bool isBroadcastShuffleMask(ArrayRef<int> Mask) {
10991   return isUndefOrEqual(Mask, 0);
10992 }
10993 
isNoopOrBroadcastShuffleMask(ArrayRef<int> Mask)10994 static bool isNoopOrBroadcastShuffleMask(ArrayRef<int> Mask) {
10995   return isNoopShuffleMask(Mask) || isBroadcastShuffleMask(Mask);
10996 }
10997 
10998 /// Check if the Mask consists of the same element repeated multiple times.
isSingleElementRepeatedMask(ArrayRef<int> Mask)10999 static bool isSingleElementRepeatedMask(ArrayRef<int> Mask) {
11000   size_t NumUndefs = 0;
11001   std::optional<int> UniqueElt;
11002   for (int Elt : Mask) {
11003     if (Elt == SM_SentinelUndef) {
11004       NumUndefs++;
11005       continue;
11006     }
11007     if (UniqueElt.has_value() && UniqueElt.value() != Elt)
11008       return false;
11009     UniqueElt = Elt;
11010   }
11011   // Make sure the element is repeated enough times by checking the number of
11012   // undefs is small.
11013   return NumUndefs <= Mask.size() / 2 && UniqueElt.has_value();
11014 }
11015 
11016 /// Generic routine to decompose a shuffle and blend into independent
11017 /// blends and permutes.
11018 ///
11019 /// This matches the extremely common pattern for handling combined
11020 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
11021 /// operations. It will try to pick the best arrangement of shuffles and
11022 /// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
lowerShuffleAsDecomposedShuffleMerge(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11023 static SDValue lowerShuffleAsDecomposedShuffleMerge(
11024     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11025     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11026   int NumElts = Mask.size();
11027   int NumLanes = VT.getSizeInBits() / 128;
11028   int NumEltsPerLane = NumElts / NumLanes;
11029 
11030   // Shuffle the input elements into the desired positions in V1 and V2 and
11031   // unpack/blend them together.
11032   bool IsAlternating = true;
11033   SmallVector<int, 32> V1Mask(NumElts, -1);
11034   SmallVector<int, 32> V2Mask(NumElts, -1);
11035   SmallVector<int, 32> FinalMask(NumElts, -1);
11036   for (int i = 0; i < NumElts; ++i) {
11037     int M = Mask[i];
11038     if (M >= 0 && M < NumElts) {
11039       V1Mask[i] = M;
11040       FinalMask[i] = i;
11041       IsAlternating &= (i & 1) == 0;
11042     } else if (M >= NumElts) {
11043       V2Mask[i] = M - NumElts;
11044       FinalMask[i] = i + NumElts;
11045       IsAlternating &= (i & 1) == 1;
11046     }
11047   }
11048 
11049   // If we effectively only demand the 0'th element of \p Input, and not only
11050   // as 0'th element, then broadcast said input,
11051   // and change \p InputMask to be a no-op (identity) mask.
11052   auto canonicalizeBroadcastableInput = [DL, VT, &Subtarget,
11053                                          &DAG](SDValue &Input,
11054                                                MutableArrayRef<int> InputMask) {
11055     unsigned EltSizeInBits = Input.getScalarValueSizeInBits();
11056     if (!Subtarget.hasAVX2() && (!Subtarget.hasAVX() || EltSizeInBits < 32 ||
11057                                  !X86::mayFoldLoad(Input, Subtarget)))
11058       return;
11059     if (isNoopShuffleMask(InputMask))
11060       return;
11061     assert(isBroadcastShuffleMask(InputMask) &&
11062            "Expected to demand only the 0'th element.");
11063     Input = DAG.getNode(X86ISD::VBROADCAST, DL, VT, Input);
11064     for (auto I : enumerate(InputMask)) {
11065       int &InputMaskElt = I.value();
11066       if (InputMaskElt >= 0)
11067         InputMaskElt = I.index();
11068     }
11069   };
11070 
11071   // Currently, we may need to produce one shuffle per input, and blend results.
11072   // It is possible that the shuffle for one of the inputs is already a no-op.
11073   // See if we can simplify non-no-op shuffles into broadcasts,
11074   // which we consider to be strictly better than an arbitrary shuffle.
11075   if (isNoopOrBroadcastShuffleMask(V1Mask) &&
11076       isNoopOrBroadcastShuffleMask(V2Mask)) {
11077     canonicalizeBroadcastableInput(V1, V1Mask);
11078     canonicalizeBroadcastableInput(V2, V2Mask);
11079   }
11080 
11081   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
11082   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
11083   // the shuffle may be able to fold with a load or other benefit. However, when
11084   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
11085   // pre-shuffle first is a better strategy.
11086   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
11087     // Only prefer immediate blends to unpack/rotate.
11088     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11089                                                           DAG, true))
11090       return BlendPerm;
11091     // If either input vector provides only a single element which is repeated
11092     // multiple times, unpacking from both input vectors would generate worse
11093     // code. e.g. for
11094     // t5: v16i8 = vector_shuffle<16,0,16,1,16,2,16,3,16,4,16,5,16,6,16,7> t2, t4
11095     // it is better to process t4 first to create a vector of t4[0], then unpack
11096     // that vector with t2.
11097     if (!isSingleElementRepeatedMask(V1Mask) &&
11098         !isSingleElementRepeatedMask(V2Mask))
11099       if (SDValue UnpackPerm =
11100               lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask, DAG))
11101         return UnpackPerm;
11102     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
11103             DL, VT, V1, V2, Mask, Subtarget, DAG))
11104       return RotatePerm;
11105     // Unpack/rotate failed - try again with variable blends.
11106     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11107                                                           DAG))
11108       return BlendPerm;
11109     if (VT.getScalarSizeInBits() >= 32)
11110       if (SDValue PermUnpack = lowerShuffleAsPermuteAndUnpack(
11111               DL, VT, V1, V2, Mask, Subtarget, DAG))
11112         return PermUnpack;
11113   }
11114 
11115   // If the final mask is an alternating blend of vXi8/vXi16, convert to an
11116   // UNPCKL(SHUFFLE, SHUFFLE) pattern.
11117   // TODO: It doesn't have to be alternating - but each lane mustn't have more
11118   // than half the elements coming from each source.
11119   if (IsAlternating && VT.getScalarSizeInBits() < 32) {
11120     V1Mask.assign(NumElts, -1);
11121     V2Mask.assign(NumElts, -1);
11122     FinalMask.assign(NumElts, -1);
11123     for (int i = 0; i != NumElts; i += NumEltsPerLane)
11124       for (int j = 0; j != NumEltsPerLane; ++j) {
11125         int M = Mask[i + j];
11126         if (M >= 0 && M < NumElts) {
11127           V1Mask[i + (j / 2)] = M;
11128           FinalMask[i + j] = i + (j / 2);
11129         } else if (M >= NumElts) {
11130           V2Mask[i + (j / 2)] = M - NumElts;
11131           FinalMask[i + j] = i + (j / 2) + NumElts;
11132         }
11133       }
11134   }
11135 
11136   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11137   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11138   return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
11139 }
11140 
matchShuffleAsBitRotate(MVT & RotateVT,int EltSizeInBits,const X86Subtarget & Subtarget,ArrayRef<int> Mask)11141 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
11142                                    const X86Subtarget &Subtarget,
11143                                    ArrayRef<int> Mask) {
11144   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11145   assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
11146 
11147   // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
11148   int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
11149   int MaxSubElts = 64 / EltSizeInBits;
11150   unsigned RotateAmt, NumSubElts;
11151   if (!ShuffleVectorInst::isBitRotateMask(Mask, EltSizeInBits, MinSubElts,
11152                                           MaxSubElts, NumSubElts, RotateAmt))
11153     return -1;
11154   unsigned NumElts = Mask.size();
11155   MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
11156   RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
11157   return RotateAmt;
11158 }
11159 
11160 /// Lower shuffle using X86ISD::VROTLI rotations.
lowerShuffleAsBitRotate(const SDLoc & DL,MVT VT,SDValue V1,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11161 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
11162                                        ArrayRef<int> Mask,
11163                                        const X86Subtarget &Subtarget,
11164                                        SelectionDAG &DAG) {
11165   // Only XOP + AVX512 targets have bit rotation instructions.
11166   // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
11167   bool IsLegal =
11168       (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
11169   if (!IsLegal && Subtarget.hasSSE3())
11170     return SDValue();
11171 
11172   MVT RotateVT;
11173   int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
11174                                           Subtarget, Mask);
11175   if (RotateAmt < 0)
11176     return SDValue();
11177 
11178   // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
11179   // expanded to OR(SRL,SHL), will be more efficient, but if they can
11180   // widen to vXi16 or more then existing lowering should will be better.
11181   if (!IsLegal) {
11182     if ((RotateAmt % 16) == 0)
11183       return SDValue();
11184     // TODO: Use getTargetVShiftByConstNode.
11185     unsigned ShlAmt = RotateAmt;
11186     unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
11187     V1 = DAG.getBitcast(RotateVT, V1);
11188     SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
11189                               DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
11190     SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
11191                               DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
11192     SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
11193     return DAG.getBitcast(VT, Rot);
11194   }
11195 
11196   SDValue Rot =
11197       DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
11198                   DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
11199   return DAG.getBitcast(VT, Rot);
11200 }
11201 
11202 /// Try to match a vector shuffle as an element rotation.
11203 ///
11204 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
matchShuffleAsElementRotate(SDValue & V1,SDValue & V2,ArrayRef<int> Mask)11205 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
11206                                        ArrayRef<int> Mask) {
11207   int NumElts = Mask.size();
11208 
11209   // We need to detect various ways of spelling a rotation:
11210   //   [11, 12, 13, 14, 15,  0,  1,  2]
11211   //   [-1, 12, 13, 14, -1, -1,  1, -1]
11212   //   [-1, -1, -1, -1, -1, -1,  1,  2]
11213   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
11214   //   [-1,  4,  5,  6, -1, -1,  9, -1]
11215   //   [-1,  4,  5,  6, -1, -1, -1, -1]
11216   int Rotation = 0;
11217   SDValue Lo, Hi;
11218   for (int i = 0; i < NumElts; ++i) {
11219     int M = Mask[i];
11220     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
11221            "Unexpected mask index.");
11222     if (M < 0)
11223       continue;
11224 
11225     // Determine where a rotated vector would have started.
11226     int StartIdx = i - (M % NumElts);
11227     if (StartIdx == 0)
11228       // The identity rotation isn't interesting, stop.
11229       return -1;
11230 
11231     // If we found the tail of a vector the rotation must be the missing
11232     // front. If we found the head of a vector, it must be how much of the
11233     // head.
11234     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
11235 
11236     if (Rotation == 0)
11237       Rotation = CandidateRotation;
11238     else if (Rotation != CandidateRotation)
11239       // The rotations don't match, so we can't match this mask.
11240       return -1;
11241 
11242     // Compute which value this mask is pointing at.
11243     SDValue MaskV = M < NumElts ? V1 : V2;
11244 
11245     // Compute which of the two target values this index should be assigned
11246     // to. This reflects whether the high elements are remaining or the low
11247     // elements are remaining.
11248     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
11249 
11250     // Either set up this value if we've not encountered it before, or check
11251     // that it remains consistent.
11252     if (!TargetV)
11253       TargetV = MaskV;
11254     else if (TargetV != MaskV)
11255       // This may be a rotation, but it pulls from the inputs in some
11256       // unsupported interleaving.
11257       return -1;
11258   }
11259 
11260   // Check that we successfully analyzed the mask, and normalize the results.
11261   assert(Rotation != 0 && "Failed to locate a viable rotation!");
11262   assert((Lo || Hi) && "Failed to find a rotated input vector!");
11263   if (!Lo)
11264     Lo = Hi;
11265   else if (!Hi)
11266     Hi = Lo;
11267 
11268   V1 = Lo;
11269   V2 = Hi;
11270 
11271   return Rotation;
11272 }
11273 
11274 /// Try to lower a vector shuffle as a byte rotation.
11275 ///
11276 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
11277 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
11278 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
11279 /// try to generically lower a vector shuffle through such an pattern. It
11280 /// does not check for the profitability of lowering either as PALIGNR or
11281 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
11282 /// This matches shuffle vectors that look like:
11283 ///
11284 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
11285 ///
11286 /// Essentially it concatenates V1 and V2, shifts right by some number of
11287 /// elements, and takes the low elements as the result. Note that while this is
11288 /// specified as a *right shift* because x86 is little-endian, it is a *left
11289 /// rotate* of the vector lanes.
matchShuffleAsByteRotate(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask)11290 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
11291                                     ArrayRef<int> Mask) {
11292   // Don't accept any shuffles with zero elements.
11293   if (isAnyZero(Mask))
11294     return -1;
11295 
11296   // PALIGNR works on 128-bit lanes.
11297   SmallVector<int, 16> RepeatedMask;
11298   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
11299     return -1;
11300 
11301   int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
11302   if (Rotation <= 0)
11303     return -1;
11304 
11305   // PALIGNR rotates bytes, so we need to scale the
11306   // rotation based on how many bytes are in the vector lane.
11307   int NumElts = RepeatedMask.size();
11308   int Scale = 16 / NumElts;
11309   return Rotation * Scale;
11310 }
11311 
lowerShuffleAsByteRotate(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11312 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
11313                                         SDValue V2, ArrayRef<int> Mask,
11314                                         const X86Subtarget &Subtarget,
11315                                         SelectionDAG &DAG) {
11316   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11317 
11318   SDValue Lo = V1, Hi = V2;
11319   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
11320   if (ByteRotation <= 0)
11321     return SDValue();
11322 
11323   // Cast the inputs to i8 vector of correct length to match PALIGNR or
11324   // PSLLDQ/PSRLDQ.
11325   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11326   Lo = DAG.getBitcast(ByteVT, Lo);
11327   Hi = DAG.getBitcast(ByteVT, Hi);
11328 
11329   // SSSE3 targets can use the palignr instruction.
11330   if (Subtarget.hasSSSE3()) {
11331     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
11332            "512-bit PALIGNR requires BWI instructions");
11333     return DAG.getBitcast(
11334         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
11335                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
11336   }
11337 
11338   assert(VT.is128BitVector() &&
11339          "Rotate-based lowering only supports 128-bit lowering!");
11340   assert(Mask.size() <= 16 &&
11341          "Can shuffle at most 16 bytes in a 128-bit vector!");
11342   assert(ByteVT == MVT::v16i8 &&
11343          "SSE2 rotate lowering only needed for v16i8!");
11344 
11345   // Default SSE2 implementation
11346   int LoByteShift = 16 - ByteRotation;
11347   int HiByteShift = ByteRotation;
11348 
11349   SDValue LoShift =
11350       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
11351                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
11352   SDValue HiShift =
11353       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
11354                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
11355   return DAG.getBitcast(VT,
11356                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
11357 }
11358 
11359 /// Try to lower a vector shuffle as a dword/qword rotation.
11360 ///
11361 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
11362 /// rotation of the concatenation of two vectors; This routine will
11363 /// try to generically lower a vector shuffle through such an pattern.
11364 ///
11365 /// Essentially it concatenates V1 and V2, shifts right by some number of
11366 /// elements, and takes the low elements as the result. Note that while this is
11367 /// specified as a *right shift* because x86 is little-endian, it is a *left
11368 /// rotate* of the vector lanes.
lowerShuffleAsVALIGN(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11369 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
11370                                     SDValue V2, ArrayRef<int> Mask,
11371                                     const APInt &Zeroable,
11372                                     const X86Subtarget &Subtarget,
11373                                     SelectionDAG &DAG) {
11374   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
11375          "Only 32-bit and 64-bit elements are supported!");
11376 
11377   // 128/256-bit vectors are only supported with VLX.
11378   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
11379          && "VLX required for 128/256-bit vectors");
11380 
11381   SDValue Lo = V1, Hi = V2;
11382   int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
11383   if (0 < Rotation)
11384     return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
11385                        DAG.getTargetConstant(Rotation, DL, MVT::i8));
11386 
11387   // See if we can use VALIGN as a cross-lane version of VSHLDQ/VSRLDQ.
11388   // TODO: Pull this out as a matchShuffleAsElementShift helper?
11389   // TODO: We can probably make this more aggressive and use shift-pairs like
11390   // lowerShuffleAsByteShiftMask.
11391   unsigned NumElts = Mask.size();
11392   unsigned ZeroLo = Zeroable.countr_one();
11393   unsigned ZeroHi = Zeroable.countl_one();
11394   assert((ZeroLo + ZeroHi) < NumElts && "Zeroable shuffle detected");
11395   if (!ZeroLo && !ZeroHi)
11396     return SDValue();
11397 
11398   if (ZeroLo) {
11399     SDValue Src = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
11400     int Low = Mask[ZeroLo] < (int)NumElts ? 0 : NumElts;
11401     if (isSequentialOrUndefInRange(Mask, ZeroLo, NumElts - ZeroLo, Low))
11402       return DAG.getNode(X86ISD::VALIGN, DL, VT, Src,
11403                          getZeroVector(VT, Subtarget, DAG, DL),
11404                          DAG.getTargetConstant(NumElts - ZeroLo, DL, MVT::i8));
11405   }
11406 
11407   if (ZeroHi) {
11408     SDValue Src = Mask[0] < (int)NumElts ? V1 : V2;
11409     int Low = Mask[0] < (int)NumElts ? 0 : NumElts;
11410     if (isSequentialOrUndefInRange(Mask, 0, NumElts - ZeroHi, Low + ZeroHi))
11411       return DAG.getNode(X86ISD::VALIGN, DL, VT,
11412                          getZeroVector(VT, Subtarget, DAG, DL), Src,
11413                          DAG.getTargetConstant(ZeroHi, DL, MVT::i8));
11414   }
11415 
11416   return SDValue();
11417 }
11418 
11419 /// Try to lower a vector shuffle as a byte shift sequence.
lowerShuffleAsByteShiftMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11420 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
11421                                            SDValue V2, ArrayRef<int> Mask,
11422                                            const APInt &Zeroable,
11423                                            const X86Subtarget &Subtarget,
11424                                            SelectionDAG &DAG) {
11425   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
11426   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
11427 
11428   // We need a shuffle that has zeros at one/both ends and a sequential
11429   // shuffle from one source within.
11430   unsigned ZeroLo = Zeroable.countr_one();
11431   unsigned ZeroHi = Zeroable.countl_one();
11432   if (!ZeroLo && !ZeroHi)
11433     return SDValue();
11434 
11435   unsigned NumElts = Mask.size();
11436   unsigned Len = NumElts - (ZeroLo + ZeroHi);
11437   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
11438     return SDValue();
11439 
11440   unsigned Scale = VT.getScalarSizeInBits() / 8;
11441   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
11442   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
11443       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
11444     return SDValue();
11445 
11446   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
11447   Res = DAG.getBitcast(MVT::v16i8, Res);
11448 
11449   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
11450   // inner sequential set of elements, possibly offset:
11451   // 01234567 --> zzzzzz01 --> 1zzzzzzz
11452   // 01234567 --> 4567zzzz --> zzzzz456
11453   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
11454   if (ZeroLo == 0) {
11455     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11456     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11457                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11458     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11459                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
11460   } else if (ZeroHi == 0) {
11461     unsigned Shift = Mask[ZeroLo] % NumElts;
11462     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11463                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11464     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11465                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
11466   } else if (!Subtarget.hasSSSE3()) {
11467     // If we don't have PSHUFB then its worth avoiding an AND constant mask
11468     // by performing 3 byte shifts. Shuffle combining can kick in above that.
11469     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
11470     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11471     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11472                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11473     Shift += Mask[ZeroLo] % NumElts;
11474     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11475                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
11476     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11477                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
11478   } else
11479     return SDValue();
11480 
11481   return DAG.getBitcast(VT, Res);
11482 }
11483 
11484 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
11485 ///
11486 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
11487 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
11488 /// matches elements from one of the input vectors shuffled to the left or
11489 /// right with zeroable elements 'shifted in'. It handles both the strictly
11490 /// bit-wise element shifts and the byte shift across an entire 128-bit double
11491 /// quad word lane.
11492 ///
11493 /// PSHL : (little-endian) left bit shift.
11494 /// [ zz, 0, zz,  2 ]
11495 /// [ -1, 4, zz, -1 ]
11496 /// PSRL : (little-endian) right bit shift.
11497 /// [  1, zz,  3, zz]
11498 /// [ -1, -1,  7, zz]
11499 /// PSLLDQ : (little-endian) left byte shift
11500 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
11501 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
11502 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
11503 /// PSRLDQ : (little-endian) right byte shift
11504 /// [  5, 6,  7, zz, zz, zz, zz, zz]
11505 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
11506 /// [  1, 2, -1, -1, -1, -1, zz, zz]
matchShuffleAsShift(MVT & ShiftVT,unsigned & Opcode,unsigned ScalarSizeInBits,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable,const X86Subtarget & Subtarget)11507 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
11508                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
11509                                int MaskOffset, const APInt &Zeroable,
11510                                const X86Subtarget &Subtarget) {
11511   int Size = Mask.size();
11512   unsigned SizeInBits = Size * ScalarSizeInBits;
11513 
11514   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
11515     for (int i = 0; i < Size; i += Scale)
11516       for (int j = 0; j < Shift; ++j)
11517         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
11518           return false;
11519 
11520     return true;
11521   };
11522 
11523   auto MatchShift = [&](int Shift, int Scale, bool Left) {
11524     for (int i = 0; i != Size; i += Scale) {
11525       unsigned Pos = Left ? i + Shift : i;
11526       unsigned Low = Left ? i : i + Shift;
11527       unsigned Len = Scale - Shift;
11528       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
11529         return -1;
11530     }
11531 
11532     int ShiftEltBits = ScalarSizeInBits * Scale;
11533     bool ByteShift = ShiftEltBits > 64;
11534     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
11535                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
11536     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
11537 
11538     // Normalize the scale for byte shifts to still produce an i64 element
11539     // type.
11540     Scale = ByteShift ? Scale / 2 : Scale;
11541 
11542     // We need to round trip through the appropriate type for the shift.
11543     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
11544     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
11545                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
11546     return (int)ShiftAmt;
11547   };
11548 
11549   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
11550   // keep doubling the size of the integer elements up to that. We can
11551   // then shift the elements of the integer vector by whole multiples of
11552   // their width within the elements of the larger integer vector. Test each
11553   // multiple to see if we can find a match with the moved element indices
11554   // and that the shifted in elements are all zeroable.
11555   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
11556   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
11557     for (int Shift = 1; Shift != Scale; ++Shift)
11558       for (bool Left : {true, false})
11559         if (CheckZeros(Shift, Scale, Left)) {
11560           int ShiftAmt = MatchShift(Shift, Scale, Left);
11561           if (0 < ShiftAmt)
11562             return ShiftAmt;
11563         }
11564 
11565   // no match
11566   return -1;
11567 }
11568 
lowerShuffleAsShift(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG,bool BitwiseOnly)11569 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
11570                                    SDValue V2, ArrayRef<int> Mask,
11571                                    const APInt &Zeroable,
11572                                    const X86Subtarget &Subtarget,
11573                                    SelectionDAG &DAG, bool BitwiseOnly) {
11574   int Size = Mask.size();
11575   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11576 
11577   MVT ShiftVT;
11578   SDValue V = V1;
11579   unsigned Opcode;
11580 
11581   // Try to match shuffle against V1 shift.
11582   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11583                                      Mask, 0, Zeroable, Subtarget);
11584 
11585   // If V1 failed, try to match shuffle against V2 shift.
11586   if (ShiftAmt < 0) {
11587     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11588                                    Mask, Size, Zeroable, Subtarget);
11589     V = V2;
11590   }
11591 
11592   if (ShiftAmt < 0)
11593     return SDValue();
11594 
11595   if (BitwiseOnly && (Opcode == X86ISD::VSHLDQ || Opcode == X86ISD::VSRLDQ))
11596     return SDValue();
11597 
11598   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
11599          "Illegal integer vector type");
11600   V = DAG.getBitcast(ShiftVT, V);
11601   V = DAG.getNode(Opcode, DL, ShiftVT, V,
11602                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
11603   return DAG.getBitcast(VT, V);
11604 }
11605 
11606 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
11607 // Remainder of lower half result is zero and upper half is all undef.
matchShuffleAsEXTRQ(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask,uint64_t & BitLen,uint64_t & BitIdx,const APInt & Zeroable)11608 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
11609                                 ArrayRef<int> Mask, uint64_t &BitLen,
11610                                 uint64_t &BitIdx, const APInt &Zeroable) {
11611   int Size = Mask.size();
11612   int HalfSize = Size / 2;
11613   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11614   assert(!Zeroable.isAllOnes() && "Fully zeroable shuffle mask");
11615 
11616   // Upper half must be undefined.
11617   if (!isUndefUpperHalf(Mask))
11618     return false;
11619 
11620   // Determine the extraction length from the part of the
11621   // lower half that isn't zeroable.
11622   int Len = HalfSize;
11623   for (; Len > 0; --Len)
11624     if (!Zeroable[Len - 1])
11625       break;
11626   assert(Len > 0 && "Zeroable shuffle mask");
11627 
11628   // Attempt to match first Len sequential elements from the lower half.
11629   SDValue Src;
11630   int Idx = -1;
11631   for (int i = 0; i != Len; ++i) {
11632     int M = Mask[i];
11633     if (M == SM_SentinelUndef)
11634       continue;
11635     SDValue &V = (M < Size ? V1 : V2);
11636     M = M % Size;
11637 
11638     // The extracted elements must start at a valid index and all mask
11639     // elements must be in the lower half.
11640     if (i > M || M >= HalfSize)
11641       return false;
11642 
11643     if (Idx < 0 || (Src == V && Idx == (M - i))) {
11644       Src = V;
11645       Idx = M - i;
11646       continue;
11647     }
11648     return false;
11649   }
11650 
11651   if (!Src || Idx < 0)
11652     return false;
11653 
11654   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
11655   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11656   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11657   V1 = Src;
11658   return true;
11659 }
11660 
11661 // INSERTQ: Extract lowest Len elements from lower half of second source and
11662 // insert over first source, starting at Idx.
11663 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
matchShuffleAsINSERTQ(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask,uint64_t & BitLen,uint64_t & BitIdx)11664 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
11665                                   ArrayRef<int> Mask, uint64_t &BitLen,
11666                                   uint64_t &BitIdx) {
11667   int Size = Mask.size();
11668   int HalfSize = Size / 2;
11669   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
11670 
11671   // Upper half must be undefined.
11672   if (!isUndefUpperHalf(Mask))
11673     return false;
11674 
11675   for (int Idx = 0; Idx != HalfSize; ++Idx) {
11676     SDValue Base;
11677 
11678     // Attempt to match first source from mask before insertion point.
11679     if (isUndefInRange(Mask, 0, Idx)) {
11680       /* EMPTY */
11681     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
11682       Base = V1;
11683     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
11684       Base = V2;
11685     } else {
11686       continue;
11687     }
11688 
11689     // Extend the extraction length looking to match both the insertion of
11690     // the second source and the remaining elements of the first.
11691     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
11692       SDValue Insert;
11693       int Len = Hi - Idx;
11694 
11695       // Match insertion.
11696       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
11697         Insert = V1;
11698       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
11699         Insert = V2;
11700       } else {
11701         continue;
11702       }
11703 
11704       // Match the remaining elements of the lower half.
11705       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
11706         /* EMPTY */
11707       } else if ((!Base || (Base == V1)) &&
11708                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
11709         Base = V1;
11710       } else if ((!Base || (Base == V2)) &&
11711                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
11712                                             Size + Hi)) {
11713         Base = V2;
11714       } else {
11715         continue;
11716       }
11717 
11718       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11719       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11720       V1 = Base;
11721       V2 = Insert;
11722       return true;
11723     }
11724   }
11725 
11726   return false;
11727 }
11728 
11729 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
lowerShuffleWithSSE4A(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)11730 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
11731                                      SDValue V2, ArrayRef<int> Mask,
11732                                      const APInt &Zeroable, SelectionDAG &DAG) {
11733   uint64_t BitLen, BitIdx;
11734   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
11735     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
11736                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
11737                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
11738 
11739   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
11740     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
11741                        V2 ? V2 : DAG.getUNDEF(VT),
11742                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
11743                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
11744 
11745   return SDValue();
11746 }
11747 
11748 /// Lower a vector shuffle as a zero or any extension.
11749 ///
11750 /// Given a specific number of elements, element bit width, and extension
11751 /// stride, produce either a zero or any extension based on the available
11752 /// features of the subtarget. The extended elements are consecutive and
11753 /// begin and can start from an offsetted element index in the input; to
11754 /// avoid excess shuffling the offset must either being in the bottom lane
11755 /// or at the start of a higher lane. All extended elements must be from
11756 /// the same lane.
lowerShuffleAsSpecificZeroOrAnyExtend(const SDLoc & DL,MVT VT,int Scale,int Offset,bool AnyExt,SDValue InputV,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)11757 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
11758     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
11759     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11760   assert(Scale > 1 && "Need a scale to extend.");
11761   int EltBits = VT.getScalarSizeInBits();
11762   int NumElements = VT.getVectorNumElements();
11763   int NumEltsPerLane = 128 / EltBits;
11764   int OffsetLane = Offset / NumEltsPerLane;
11765   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
11766          "Only 8, 16, and 32 bit elements can be extended.");
11767   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
11768   assert(0 <= Offset && "Extension offset must be positive.");
11769   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
11770          "Extension offset must be in the first lane or start an upper lane.");
11771 
11772   // Check that an index is in same lane as the base offset.
11773   auto SafeOffset = [&](int Idx) {
11774     return OffsetLane == (Idx / NumEltsPerLane);
11775   };
11776 
11777   // Shift along an input so that the offset base moves to the first element.
11778   auto ShuffleOffset = [&](SDValue V) {
11779     if (!Offset)
11780       return V;
11781 
11782     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
11783     for (int i = 0; i * Scale < NumElements; ++i) {
11784       int SrcIdx = i + Offset;
11785       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
11786     }
11787     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
11788   };
11789 
11790   // Found a valid a/zext mask! Try various lowering strategies based on the
11791   // input type and available ISA extensions.
11792   if (Subtarget.hasSSE41()) {
11793     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
11794     // PUNPCK will catch this in a later shuffle match.
11795     if (Offset && Scale == 2 && VT.is128BitVector())
11796       return SDValue();
11797     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
11798                                  NumElements / Scale);
11799     InputV = DAG.getBitcast(VT, InputV);
11800     InputV = ShuffleOffset(InputV);
11801     InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
11802                                     DL, ExtVT, InputV, DAG);
11803     return DAG.getBitcast(VT, InputV);
11804   }
11805 
11806   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
11807   InputV = DAG.getBitcast(VT, InputV);
11808 
11809   // For any extends we can cheat for larger element sizes and use shuffle
11810   // instructions that can fold with a load and/or copy.
11811   if (AnyExt && EltBits == 32) {
11812     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
11813                          -1};
11814     return DAG.getBitcast(
11815         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
11816                         DAG.getBitcast(MVT::v4i32, InputV),
11817                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
11818   }
11819   if (AnyExt && EltBits == 16 && Scale > 2) {
11820     int PSHUFDMask[4] = {Offset / 2, -1,
11821                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
11822     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
11823                          DAG.getBitcast(MVT::v4i32, InputV),
11824                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
11825     int PSHUFWMask[4] = {1, -1, -1, -1};
11826     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
11827     return DAG.getBitcast(
11828         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
11829                         DAG.getBitcast(MVT::v8i16, InputV),
11830                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
11831   }
11832 
11833   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
11834   // to 64-bits.
11835   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
11836     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
11837     assert(VT.is128BitVector() && "Unexpected vector width!");
11838 
11839     int LoIdx = Offset * EltBits;
11840     SDValue Lo = DAG.getBitcast(
11841         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
11842                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
11843                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
11844 
11845     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
11846       return DAG.getBitcast(VT, Lo);
11847 
11848     int HiIdx = (Offset + 1) * EltBits;
11849     SDValue Hi = DAG.getBitcast(
11850         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
11851                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
11852                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
11853     return DAG.getBitcast(VT,
11854                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
11855   }
11856 
11857   // If this would require more than 2 unpack instructions to expand, use
11858   // pshufb when available. We can only use more than 2 unpack instructions
11859   // when zero extending i8 elements which also makes it easier to use pshufb.
11860   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
11861     assert(NumElements == 16 && "Unexpected byte vector width!");
11862     SDValue PSHUFBMask[16];
11863     for (int i = 0; i < 16; ++i) {
11864       int Idx = Offset + (i / Scale);
11865       if ((i % Scale == 0 && SafeOffset(Idx))) {
11866         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
11867         continue;
11868       }
11869       PSHUFBMask[i] =
11870           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
11871     }
11872     InputV = DAG.getBitcast(MVT::v16i8, InputV);
11873     return DAG.getBitcast(
11874         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
11875                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
11876   }
11877 
11878   // If we are extending from an offset, ensure we start on a boundary that
11879   // we can unpack from.
11880   int AlignToUnpack = Offset % (NumElements / Scale);
11881   if (AlignToUnpack) {
11882     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
11883     for (int i = AlignToUnpack; i < NumElements; ++i)
11884       ShMask[i - AlignToUnpack] = i;
11885     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
11886     Offset -= AlignToUnpack;
11887   }
11888 
11889   // Otherwise emit a sequence of unpacks.
11890   do {
11891     unsigned UnpackLoHi = X86ISD::UNPCKL;
11892     if (Offset >= (NumElements / 2)) {
11893       UnpackLoHi = X86ISD::UNPCKH;
11894       Offset -= (NumElements / 2);
11895     }
11896 
11897     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
11898     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
11899                          : getZeroVector(InputVT, Subtarget, DAG, DL);
11900     InputV = DAG.getBitcast(InputVT, InputV);
11901     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
11902     Scale /= 2;
11903     EltBits *= 2;
11904     NumElements /= 2;
11905   } while (Scale > 1);
11906   return DAG.getBitcast(VT, InputV);
11907 }
11908 
11909 /// Try to lower a vector shuffle as a zero extension on any microarch.
11910 ///
11911 /// This routine will try to do everything in its power to cleverly lower
11912 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
11913 /// check for the profitability of this lowering,  it tries to aggressively
11914 /// match this pattern. It will use all of the micro-architectural details it
11915 /// can to emit an efficient lowering. It handles both blends with all-zero
11916 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
11917 /// masking out later).
11918 ///
11919 /// The reason we have dedicated lowering for zext-style shuffles is that they
11920 /// are both incredibly common and often quite performance sensitive.
lowerShuffleAsZeroOrAnyExtend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)11921 static SDValue lowerShuffleAsZeroOrAnyExtend(
11922     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11923     const APInt &Zeroable, const X86Subtarget &Subtarget,
11924     SelectionDAG &DAG) {
11925   int Bits = VT.getSizeInBits();
11926   int NumLanes = Bits / 128;
11927   int NumElements = VT.getVectorNumElements();
11928   int NumEltsPerLane = NumElements / NumLanes;
11929   assert(VT.getScalarSizeInBits() <= 32 &&
11930          "Exceeds 32-bit integer zero extension limit");
11931   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
11932 
11933   // Define a helper function to check a particular ext-scale and lower to it if
11934   // valid.
11935   auto Lower = [&](int Scale) -> SDValue {
11936     SDValue InputV;
11937     bool AnyExt = true;
11938     int Offset = 0;
11939     int Matches = 0;
11940     for (int i = 0; i < NumElements; ++i) {
11941       int M = Mask[i];
11942       if (M < 0)
11943         continue; // Valid anywhere but doesn't tell us anything.
11944       if (i % Scale != 0) {
11945         // Each of the extended elements need to be zeroable.
11946         if (!Zeroable[i])
11947           return SDValue();
11948 
11949         // We no longer are in the anyext case.
11950         AnyExt = false;
11951         continue;
11952       }
11953 
11954       // Each of the base elements needs to be consecutive indices into the
11955       // same input vector.
11956       SDValue V = M < NumElements ? V1 : V2;
11957       M = M % NumElements;
11958       if (!InputV) {
11959         InputV = V;
11960         Offset = M - (i / Scale);
11961       } else if (InputV != V)
11962         return SDValue(); // Flip-flopping inputs.
11963 
11964       // Offset must start in the lowest 128-bit lane or at the start of an
11965       // upper lane.
11966       // FIXME: Is it ever worth allowing a negative base offset?
11967       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
11968             (Offset % NumEltsPerLane) == 0))
11969         return SDValue();
11970 
11971       // If we are offsetting, all referenced entries must come from the same
11972       // lane.
11973       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
11974         return SDValue();
11975 
11976       if ((M % NumElements) != (Offset + (i / Scale)))
11977         return SDValue(); // Non-consecutive strided elements.
11978       Matches++;
11979     }
11980 
11981     // If we fail to find an input, we have a zero-shuffle which should always
11982     // have already been handled.
11983     // FIXME: Maybe handle this here in case during blending we end up with one?
11984     if (!InputV)
11985       return SDValue();
11986 
11987     // If we are offsetting, don't extend if we only match a single input, we
11988     // can always do better by using a basic PSHUF or PUNPCK.
11989     if (Offset != 0 && Matches < 2)
11990       return SDValue();
11991 
11992     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
11993                                                  InputV, Mask, Subtarget, DAG);
11994   };
11995 
11996   // The widest scale possible for extending is to a 64-bit integer.
11997   assert(Bits % 64 == 0 &&
11998          "The number of bits in a vector must be divisible by 64 on x86!");
11999   int NumExtElements = Bits / 64;
12000 
12001   // Each iteration, try extending the elements half as much, but into twice as
12002   // many elements.
12003   for (; NumExtElements < NumElements; NumExtElements *= 2) {
12004     assert(NumElements % NumExtElements == 0 &&
12005            "The input vector size must be divisible by the extended size.");
12006     if (SDValue V = Lower(NumElements / NumExtElements))
12007       return V;
12008   }
12009 
12010   // General extends failed, but 128-bit vectors may be able to use MOVQ.
12011   if (Bits != 128)
12012     return SDValue();
12013 
12014   // Returns one of the source operands if the shuffle can be reduced to a
12015   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
12016   auto CanZExtLowHalf = [&]() {
12017     for (int i = NumElements / 2; i != NumElements; ++i)
12018       if (!Zeroable[i])
12019         return SDValue();
12020     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
12021       return V1;
12022     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
12023       return V2;
12024     return SDValue();
12025   };
12026 
12027   if (SDValue V = CanZExtLowHalf()) {
12028     V = DAG.getBitcast(MVT::v2i64, V);
12029     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
12030     return DAG.getBitcast(VT, V);
12031   }
12032 
12033   // No viable ext lowering found.
12034   return SDValue();
12035 }
12036 
12037 /// Try to get a scalar value for a specific element of a vector.
12038 ///
12039 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
getScalarValueForVectorElement(SDValue V,int Idx,SelectionDAG & DAG)12040 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
12041                                               SelectionDAG &DAG) {
12042   MVT VT = V.getSimpleValueType();
12043   MVT EltVT = VT.getVectorElementType();
12044   V = peekThroughBitcasts(V);
12045 
12046   // If the bitcasts shift the element size, we can't extract an equivalent
12047   // element from it.
12048   MVT NewVT = V.getSimpleValueType();
12049   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
12050     return SDValue();
12051 
12052   if (V.getOpcode() == ISD::BUILD_VECTOR ||
12053       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
12054     // Ensure the scalar operand is the same size as the destination.
12055     // FIXME: Add support for scalar truncation where possible.
12056     SDValue S = V.getOperand(Idx);
12057     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
12058       return DAG.getBitcast(EltVT, S);
12059   }
12060 
12061   return SDValue();
12062 }
12063 
12064 /// Helper to test for a load that can be folded with x86 shuffles.
12065 ///
12066 /// This is particularly important because the set of instructions varies
12067 /// significantly based on whether the operand is a load or not.
isShuffleFoldableLoad(SDValue V)12068 static bool isShuffleFoldableLoad(SDValue V) {
12069   return V->hasOneUse() &&
12070          ISD::isNON_EXTLoad(peekThroughOneUseBitcasts(V).getNode());
12071 }
12072 
12073 template<typename T>
isSoftF16(T VT,const X86Subtarget & Subtarget)12074 static bool isSoftF16(T VT, const X86Subtarget &Subtarget) {
12075   T EltVT = VT.getScalarType();
12076   return EltVT == MVT::bf16 || (EltVT == MVT::f16 && !Subtarget.hasFP16());
12077 }
12078 
12079 /// Try to lower insertion of a single element into a zero vector.
12080 ///
12081 /// This is a common pattern that we have especially efficient patterns to lower
12082 /// across all subtarget feature sets.
lowerShuffleAsElementInsertion(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)12083 static SDValue lowerShuffleAsElementInsertion(
12084     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12085     const APInt &Zeroable, const X86Subtarget &Subtarget,
12086     SelectionDAG &DAG) {
12087   MVT ExtVT = VT;
12088   MVT EltVT = VT.getVectorElementType();
12089   unsigned NumElts = VT.getVectorNumElements();
12090   unsigned EltBits = VT.getScalarSizeInBits();
12091 
12092   if (isSoftF16(EltVT, Subtarget))
12093     return SDValue();
12094 
12095   int V2Index =
12096       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
12097       Mask.begin();
12098   bool IsV1Constant = getTargetConstantFromNode(V1) != nullptr;
12099   bool IsV1Zeroable = true;
12100   for (int i = 0, Size = Mask.size(); i < Size; ++i)
12101     if (i != V2Index && !Zeroable[i]) {
12102       IsV1Zeroable = false;
12103       break;
12104     }
12105 
12106   // Bail if a non-zero V1 isn't used in place.
12107   if (!IsV1Zeroable) {
12108     SmallVector<int, 8> V1Mask(Mask);
12109     V1Mask[V2Index] = -1;
12110     if (!isNoopShuffleMask(V1Mask))
12111       return SDValue();
12112   }
12113 
12114   // Check for a single input from a SCALAR_TO_VECTOR node.
12115   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
12116   // all the smarts here sunk into that routine. However, the current
12117   // lowering of BUILD_VECTOR makes that nearly impossible until the old
12118   // vector shuffle lowering is dead.
12119   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
12120                                                DAG);
12121   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
12122     // We need to zext the scalar if it is smaller than an i32.
12123     V2S = DAG.getBitcast(EltVT, V2S);
12124     if (EltVT == MVT::i8 || (EltVT == MVT::i16 && !Subtarget.hasFP16())) {
12125       // Using zext to expand a narrow element won't work for non-zero
12126       // insertions. But we can use a masked constant vector if we're
12127       // inserting V2 into the bottom of V1.
12128       if (!IsV1Zeroable && !(IsV1Constant && V2Index == 0))
12129         return SDValue();
12130 
12131       // Zero-extend directly to i32.
12132       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
12133       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
12134 
12135       // If we're inserting into a constant, mask off the inserted index
12136       // and OR with the zero-extended scalar.
12137       if (!IsV1Zeroable) {
12138         SmallVector<APInt> Bits(NumElts, APInt::getAllOnes(EltBits));
12139         Bits[V2Index] = APInt::getZero(EltBits);
12140         SDValue BitMask = getConstVector(Bits, VT, DAG, DL);
12141         V1 = DAG.getNode(ISD::AND, DL, VT, V1, BitMask);
12142         V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
12143         V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2));
12144         return DAG.getNode(ISD::OR, DL, VT, V1, V2);
12145       }
12146     }
12147     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
12148   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
12149              EltVT == MVT::i16) {
12150     // Either not inserting from the low element of the input or the input
12151     // element size is too small to use VZEXT_MOVL to clear the high bits.
12152     return SDValue();
12153   }
12154 
12155   if (!IsV1Zeroable) {
12156     // If V1 can't be treated as a zero vector we have fewer options to lower
12157     // this. We can't support integer vectors or non-zero targets cheaply.
12158     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
12159     if (!VT.isFloatingPoint() || V2Index != 0)
12160       return SDValue();
12161     if (!VT.is128BitVector())
12162       return SDValue();
12163 
12164     // Otherwise, use MOVSD, MOVSS or MOVSH.
12165     unsigned MovOpc = 0;
12166     if (EltVT == MVT::f16)
12167       MovOpc = X86ISD::MOVSH;
12168     else if (EltVT == MVT::f32)
12169       MovOpc = X86ISD::MOVSS;
12170     else if (EltVT == MVT::f64)
12171       MovOpc = X86ISD::MOVSD;
12172     else
12173       llvm_unreachable("Unsupported floating point element type to handle!");
12174     return DAG.getNode(MovOpc, DL, ExtVT, V1, V2);
12175   }
12176 
12177   // This lowering only works for the low element with floating point vectors.
12178   if (VT.isFloatingPoint() && V2Index != 0)
12179     return SDValue();
12180 
12181   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
12182   if (ExtVT != VT)
12183     V2 = DAG.getBitcast(VT, V2);
12184 
12185   if (V2Index != 0) {
12186     // If we have 4 or fewer lanes we can cheaply shuffle the element into
12187     // the desired position. Otherwise it is more efficient to do a vector
12188     // shift left. We know that we can do a vector shift left because all
12189     // the inputs are zero.
12190     if (VT.isFloatingPoint() || NumElts <= 4) {
12191       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
12192       V2Shuffle[V2Index] = 0;
12193       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
12194     } else {
12195       V2 = DAG.getBitcast(MVT::v16i8, V2);
12196       V2 = DAG.getNode(
12197           X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
12198           DAG.getTargetConstant(V2Index * EltBits / 8, DL, MVT::i8));
12199       V2 = DAG.getBitcast(VT, V2);
12200     }
12201   }
12202   return V2;
12203 }
12204 
12205 /// Try to lower broadcast of a single - truncated - integer element,
12206 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
12207 ///
12208 /// This assumes we have AVX2.
lowerShuffleAsTruncBroadcast(const SDLoc & DL,MVT VT,SDValue V0,int BroadcastIdx,const X86Subtarget & Subtarget,SelectionDAG & DAG)12209 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
12210                                             int BroadcastIdx,
12211                                             const X86Subtarget &Subtarget,
12212                                             SelectionDAG &DAG) {
12213   assert(Subtarget.hasAVX2() &&
12214          "We can only lower integer broadcasts with AVX2!");
12215 
12216   MVT EltVT = VT.getVectorElementType();
12217   MVT V0VT = V0.getSimpleValueType();
12218 
12219   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
12220   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
12221 
12222   MVT V0EltVT = V0VT.getVectorElementType();
12223   if (!V0EltVT.isInteger())
12224     return SDValue();
12225 
12226   const unsigned EltSize = EltVT.getSizeInBits();
12227   const unsigned V0EltSize = V0EltVT.getSizeInBits();
12228 
12229   // This is only a truncation if the original element type is larger.
12230   if (V0EltSize <= EltSize)
12231     return SDValue();
12232 
12233   assert(((V0EltSize % EltSize) == 0) &&
12234          "Scalar type sizes must all be powers of 2 on x86!");
12235 
12236   const unsigned V0Opc = V0.getOpcode();
12237   const unsigned Scale = V0EltSize / EltSize;
12238   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
12239 
12240   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
12241       V0Opc != ISD::BUILD_VECTOR)
12242     return SDValue();
12243 
12244   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
12245 
12246   // If we're extracting non-least-significant bits, shift so we can truncate.
12247   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
12248   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
12249   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
12250   if (const int OffsetIdx = BroadcastIdx % Scale)
12251     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
12252                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
12253 
12254   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
12255                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
12256 }
12257 
12258 /// Test whether this can be lowered with a single SHUFPS instruction.
12259 ///
12260 /// This is used to disable more specialized lowerings when the shufps lowering
12261 /// will happen to be efficient.
isSingleSHUFPSMask(ArrayRef<int> Mask)12262 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
12263   // This routine only handles 128-bit shufps.
12264   assert(Mask.size() == 4 && "Unsupported mask size!");
12265   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
12266   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
12267   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
12268   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
12269 
12270   // To lower with a single SHUFPS we need to have the low half and high half
12271   // each requiring a single input.
12272   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
12273     return false;
12274   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
12275     return false;
12276 
12277   return true;
12278 }
12279 
12280 /// Test whether the specified input (0 or 1) is in-place blended by the
12281 /// given mask.
12282 ///
12283 /// This returns true if the elements from a particular input are already in the
12284 /// slot required by the given mask and require no permutation.
isShuffleMaskInputInPlace(int Input,ArrayRef<int> Mask)12285 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
12286   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
12287   int Size = Mask.size();
12288   for (int i = 0; i < Size; ++i)
12289     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
12290       return false;
12291 
12292   return true;
12293 }
12294 
12295 /// If we are extracting two 128-bit halves of a vector and shuffling the
12296 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
12297 /// multi-shuffle lowering.
lowerShuffleOfExtractsAsVperm(const SDLoc & DL,SDValue N0,SDValue N1,ArrayRef<int> Mask,SelectionDAG & DAG)12298 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
12299                                              SDValue N1, ArrayRef<int> Mask,
12300                                              SelectionDAG &DAG) {
12301   MVT VT = N0.getSimpleValueType();
12302   assert((VT.is128BitVector() &&
12303           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
12304          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
12305 
12306   // Check that both sources are extracts of the same source vector.
12307   if (N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12308       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12309       N0.getOperand(0) != N1.getOperand(0) ||
12310       !N0.hasOneUse() || !N1.hasOneUse())
12311     return SDValue();
12312 
12313   SDValue WideVec = N0.getOperand(0);
12314   MVT WideVT = WideVec.getSimpleValueType();
12315   if (!WideVT.is256BitVector())
12316     return SDValue();
12317 
12318   // Match extracts of each half of the wide source vector. Commute the shuffle
12319   // if the extract of the low half is N1.
12320   unsigned NumElts = VT.getVectorNumElements();
12321   SmallVector<int, 4> NewMask(Mask);
12322   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
12323   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
12324   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
12325     ShuffleVectorSDNode::commuteMask(NewMask);
12326   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
12327     return SDValue();
12328 
12329   // Final bailout: if the mask is simple, we are better off using an extract
12330   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
12331   // because that avoids a constant load from memory.
12332   if (NumElts == 4 &&
12333       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask, DAG)))
12334     return SDValue();
12335 
12336   // Extend the shuffle mask with undef elements.
12337   NewMask.append(NumElts, -1);
12338 
12339   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
12340   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
12341                                       NewMask);
12342   // This is free: ymm -> xmm.
12343   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
12344                      DAG.getIntPtrConstant(0, DL));
12345 }
12346 
12347 /// Try to lower broadcast of a single element.
12348 ///
12349 /// For convenience, this code also bundles all of the subtarget feature set
12350 /// filtering. While a little annoying to re-dispatch on type here, there isn't
12351 /// a convenient way to factor it out.
lowerShuffleAsBroadcast(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12352 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
12353                                        SDValue V2, ArrayRef<int> Mask,
12354                                        const X86Subtarget &Subtarget,
12355                                        SelectionDAG &DAG) {
12356   MVT EltVT = VT.getVectorElementType();
12357   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
12358         (Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
12359         (Subtarget.hasAVX2() && (VT.isInteger() || EltVT == MVT::f16))))
12360     return SDValue();
12361 
12362   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
12363   // we can only broadcast from a register with AVX2.
12364   unsigned NumEltBits = VT.getScalarSizeInBits();
12365   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
12366                         ? X86ISD::MOVDDUP
12367                         : X86ISD::VBROADCAST;
12368   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
12369 
12370   // Check that the mask is a broadcast.
12371   int BroadcastIdx = getSplatIndex(Mask);
12372   if (BroadcastIdx < 0)
12373     return SDValue();
12374   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
12375                                             "a sorted mask where the broadcast "
12376                                             "comes from V1.");
12377 
12378   // Go up the chain of (vector) values to find a scalar load that we can
12379   // combine with the broadcast.
12380   // TODO: Combine this logic with findEltLoadSrc() used by
12381   //       EltsFromConsecutiveLoads().
12382   int BitOffset = BroadcastIdx * NumEltBits;
12383   SDValue V = V1;
12384   for (;;) {
12385     switch (V.getOpcode()) {
12386     case ISD::BITCAST: {
12387       V = V.getOperand(0);
12388       continue;
12389     }
12390     case ISD::CONCAT_VECTORS: {
12391       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
12392       int OpIdx = BitOffset / OpBitWidth;
12393       V = V.getOperand(OpIdx);
12394       BitOffset %= OpBitWidth;
12395       continue;
12396     }
12397     case ISD::EXTRACT_SUBVECTOR: {
12398       // The extraction index adds to the existing offset.
12399       unsigned EltBitWidth = V.getScalarValueSizeInBits();
12400       unsigned Idx = V.getConstantOperandVal(1);
12401       unsigned BeginOffset = Idx * EltBitWidth;
12402       BitOffset += BeginOffset;
12403       V = V.getOperand(0);
12404       continue;
12405     }
12406     case ISD::INSERT_SUBVECTOR: {
12407       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
12408       int EltBitWidth = VOuter.getScalarValueSizeInBits();
12409       int Idx = (int)V.getConstantOperandVal(2);
12410       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
12411       int BeginOffset = Idx * EltBitWidth;
12412       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
12413       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
12414         BitOffset -= BeginOffset;
12415         V = VInner;
12416       } else {
12417         V = VOuter;
12418       }
12419       continue;
12420     }
12421     }
12422     break;
12423   }
12424   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
12425   BroadcastIdx = BitOffset / NumEltBits;
12426 
12427   // Do we need to bitcast the source to retrieve the original broadcast index?
12428   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
12429 
12430   // Check if this is a broadcast of a scalar. We special case lowering
12431   // for scalars so that we can more effectively fold with loads.
12432   // If the original value has a larger element type than the shuffle, the
12433   // broadcast element is in essence truncated. Make that explicit to ease
12434   // folding.
12435   if (BitCastSrc && VT.isInteger())
12436     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
12437             DL, VT, V, BroadcastIdx, Subtarget, DAG))
12438       return TruncBroadcast;
12439 
12440   // Also check the simpler case, where we can directly reuse the scalar.
12441   if (!BitCastSrc &&
12442       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
12443        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
12444     V = V.getOperand(BroadcastIdx);
12445 
12446     // If we can't broadcast from a register, check that the input is a load.
12447     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
12448       return SDValue();
12449   } else if (ISD::isNormalLoad(V.getNode()) &&
12450              cast<LoadSDNode>(V)->isSimple()) {
12451     // We do not check for one-use of the vector load because a broadcast load
12452     // is expected to be a win for code size, register pressure, and possibly
12453     // uops even if the original vector load is not eliminated.
12454 
12455     // Reduce the vector load and shuffle to a broadcasted scalar load.
12456     LoadSDNode *Ld = cast<LoadSDNode>(V);
12457     SDValue BaseAddr = Ld->getOperand(1);
12458     MVT SVT = VT.getScalarType();
12459     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
12460     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
12461     SDValue NewAddr =
12462         DAG.getMemBasePlusOffset(BaseAddr, TypeSize::getFixed(Offset), DL);
12463 
12464     // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
12465     // than MOVDDUP.
12466     // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
12467     if (Opcode == X86ISD::VBROADCAST) {
12468       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
12469       SDValue Ops[] = {Ld->getChain(), NewAddr};
12470       V = DAG.getMemIntrinsicNode(
12471           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
12472           DAG.getMachineFunction().getMachineMemOperand(
12473               Ld->getMemOperand(), Offset, SVT.getStoreSize()));
12474       DAG.makeEquivalentMemoryOrdering(Ld, V);
12475       return DAG.getBitcast(VT, V);
12476     }
12477     assert(SVT == MVT::f64 && "Unexpected VT!");
12478     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
12479                     DAG.getMachineFunction().getMachineMemOperand(
12480                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
12481     DAG.makeEquivalentMemoryOrdering(Ld, V);
12482   } else if (!BroadcastFromReg) {
12483     // We can't broadcast from a vector register.
12484     return SDValue();
12485   } else if (BitOffset != 0) {
12486     // We can only broadcast from the zero-element of a vector register,
12487     // but it can be advantageous to broadcast from the zero-element of a
12488     // subvector.
12489     if (!VT.is256BitVector() && !VT.is512BitVector())
12490       return SDValue();
12491 
12492     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
12493     if (VT == MVT::v4f64 || VT == MVT::v4i64)
12494       return SDValue();
12495 
12496     // Only broadcast the zero-element of a 128-bit subvector.
12497     if ((BitOffset % 128) != 0)
12498       return SDValue();
12499 
12500     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
12501            "Unexpected bit-offset");
12502     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
12503            "Unexpected vector size");
12504     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
12505     V = extract128BitVector(V, ExtractIdx, DAG, DL);
12506   }
12507 
12508   // On AVX we can use VBROADCAST directly for scalar sources.
12509   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector()) {
12510     V = DAG.getBitcast(MVT::f64, V);
12511     if (Subtarget.hasAVX()) {
12512       V = DAG.getNode(X86ISD::VBROADCAST, DL, MVT::v2f64, V);
12513       return DAG.getBitcast(VT, V);
12514     }
12515     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V);
12516   }
12517 
12518   // If this is a scalar, do the broadcast on this type and bitcast.
12519   if (!V.getValueType().isVector()) {
12520     assert(V.getScalarValueSizeInBits() == NumEltBits &&
12521            "Unexpected scalar size");
12522     MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
12523                                        VT.getVectorNumElements());
12524     return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
12525   }
12526 
12527   // We only support broadcasting from 128-bit vectors to minimize the
12528   // number of patterns we need to deal with in isel. So extract down to
12529   // 128-bits, removing as many bitcasts as possible.
12530   if (V.getValueSizeInBits() > 128)
12531     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
12532 
12533   // Otherwise cast V to a vector with the same element type as VT, but
12534   // possibly narrower than VT. Then perform the broadcast.
12535   unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
12536   MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
12537   return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
12538 }
12539 
12540 // Check for whether we can use INSERTPS to perform the shuffle. We only use
12541 // INSERTPS when the V1 elements are already in the correct locations
12542 // because otherwise we can just always use two SHUFPS instructions which
12543 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
12544 // perform INSERTPS if a single V1 element is out of place and all V2
12545 // elements are zeroable.
matchShuffleAsInsertPS(SDValue & V1,SDValue & V2,unsigned & InsertPSMask,const APInt & Zeroable,ArrayRef<int> Mask,SelectionDAG & DAG)12546 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
12547                                    unsigned &InsertPSMask,
12548                                    const APInt &Zeroable,
12549                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
12550   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
12551   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
12552   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
12553 
12554   // Attempt to match INSERTPS with one element from VA or VB being
12555   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
12556   // are updated.
12557   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
12558                              ArrayRef<int> CandidateMask) {
12559     unsigned ZMask = 0;
12560     int VADstIndex = -1;
12561     int VBDstIndex = -1;
12562     bool VAUsedInPlace = false;
12563 
12564     for (int i = 0; i < 4; ++i) {
12565       // Synthesize a zero mask from the zeroable elements (includes undefs).
12566       if (Zeroable[i]) {
12567         ZMask |= 1 << i;
12568         continue;
12569       }
12570 
12571       // Flag if we use any VA inputs in place.
12572       if (i == CandidateMask[i]) {
12573         VAUsedInPlace = true;
12574         continue;
12575       }
12576 
12577       // We can only insert a single non-zeroable element.
12578       if (VADstIndex >= 0 || VBDstIndex >= 0)
12579         return false;
12580 
12581       if (CandidateMask[i] < 4) {
12582         // VA input out of place for insertion.
12583         VADstIndex = i;
12584       } else {
12585         // VB input for insertion.
12586         VBDstIndex = i;
12587       }
12588     }
12589 
12590     // Don't bother if we have no (non-zeroable) element for insertion.
12591     if (VADstIndex < 0 && VBDstIndex < 0)
12592       return false;
12593 
12594     // Determine element insertion src/dst indices. The src index is from the
12595     // start of the inserted vector, not the start of the concatenated vector.
12596     unsigned VBSrcIndex = 0;
12597     if (VADstIndex >= 0) {
12598       // If we have a VA input out of place, we use VA as the V2 element
12599       // insertion and don't use the original V2 at all.
12600       VBSrcIndex = CandidateMask[VADstIndex];
12601       VBDstIndex = VADstIndex;
12602       VB = VA;
12603     } else {
12604       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
12605     }
12606 
12607     // If no V1 inputs are used in place, then the result is created only from
12608     // the zero mask and the V2 insertion - so remove V1 dependency.
12609     if (!VAUsedInPlace)
12610       VA = DAG.getUNDEF(MVT::v4f32);
12611 
12612     // Update V1, V2 and InsertPSMask accordingly.
12613     V1 = VA;
12614     V2 = VB;
12615 
12616     // Insert the V2 element into the desired position.
12617     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
12618     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
12619     return true;
12620   };
12621 
12622   if (matchAsInsertPS(V1, V2, Mask))
12623     return true;
12624 
12625   // Commute and try again.
12626   SmallVector<int, 4> CommutedMask(Mask);
12627   ShuffleVectorSDNode::commuteMask(CommutedMask);
12628   if (matchAsInsertPS(V2, V1, CommutedMask))
12629     return true;
12630 
12631   return false;
12632 }
12633 
lowerShuffleAsInsertPS(const SDLoc & DL,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)12634 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
12635                                       ArrayRef<int> Mask, const APInt &Zeroable,
12636                                       SelectionDAG &DAG) {
12637   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12638   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12639 
12640   // Attempt to match the insertps pattern.
12641   unsigned InsertPSMask = 0;
12642   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
12643     return SDValue();
12644 
12645   // Insert the V2 element into the desired position.
12646   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
12647                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
12648 }
12649 
12650 /// Handle lowering of 2-lane 64-bit floating point shuffles.
12651 ///
12652 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
12653 /// support for floating point shuffles but not integer shuffles. These
12654 /// instructions will incur a domain crossing penalty on some chips though so
12655 /// it is better to avoid lowering through this for integer vectors where
12656 /// possible.
lowerV2F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12657 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12658                                  const APInt &Zeroable, SDValue V1, SDValue V2,
12659                                  const X86Subtarget &Subtarget,
12660                                  SelectionDAG &DAG) {
12661   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
12662   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
12663   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
12664 
12665   if (V2.isUndef()) {
12666     // Check for being able to broadcast a single element.
12667     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
12668                                                     Mask, Subtarget, DAG))
12669       return Broadcast;
12670 
12671     // Straight shuffle of a single input vector. Simulate this by using the
12672     // single input as both of the "inputs" to this instruction..
12673     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
12674 
12675     if (Subtarget.hasAVX()) {
12676       // If we have AVX, we can use VPERMILPS which will allow folding a load
12677       // into the shuffle.
12678       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
12679                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
12680     }
12681 
12682     return DAG.getNode(
12683         X86ISD::SHUFP, DL, MVT::v2f64,
12684         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
12685         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
12686         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
12687   }
12688   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
12689   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
12690   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
12691   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
12692 
12693   if (Subtarget.hasAVX2())
12694     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12695       return Extract;
12696 
12697   // When loading a scalar and then shuffling it into a vector we can often do
12698   // the insertion cheaply.
12699   if (SDValue Insertion = lowerShuffleAsElementInsertion(
12700           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
12701     return Insertion;
12702   // Try inverting the insertion since for v2 masks it is easy to do and we
12703   // can't reliably sort the mask one way or the other.
12704   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
12705                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
12706   if (SDValue Insertion = lowerShuffleAsElementInsertion(
12707           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
12708     return Insertion;
12709 
12710   // Try to use one of the special instruction patterns to handle two common
12711   // blend patterns if a zero-blend above didn't work.
12712   if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
12713       isShuffleEquivalent(Mask, {1, 3}, V1, V2))
12714     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
12715       // We can either use a special instruction to load over the low double or
12716       // to move just the low double.
12717       return DAG.getNode(
12718           X86ISD::MOVSD, DL, MVT::v2f64, V2,
12719           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
12720 
12721   if (Subtarget.hasSSE41())
12722     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
12723                                             Zeroable, Subtarget, DAG))
12724       return Blend;
12725 
12726   // Use dedicated unpack instructions for masks that match their pattern.
12727   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
12728     return V;
12729 
12730   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
12731   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
12732                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
12733 }
12734 
12735 /// Handle lowering of 2-lane 64-bit integer shuffles.
12736 ///
12737 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
12738 /// the integer unit to minimize domain crossing penalties. However, for blends
12739 /// it falls back to the floating point shuffle operation with appropriate bit
12740 /// casting.
lowerV2I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12741 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12742                                  const APInt &Zeroable, SDValue V1, SDValue V2,
12743                                  const X86Subtarget &Subtarget,
12744                                  SelectionDAG &DAG) {
12745   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
12746   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
12747   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
12748 
12749   if (V2.isUndef()) {
12750     // Check for being able to broadcast a single element.
12751     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
12752                                                     Mask, Subtarget, DAG))
12753       return Broadcast;
12754 
12755     // Straight shuffle of a single input vector. For everything from SSE2
12756     // onward this has a single fast instruction with no scary immediates.
12757     // We have to map the mask as it is actually a v4i32 shuffle instruction.
12758     V1 = DAG.getBitcast(MVT::v4i32, V1);
12759     int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
12760                           Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
12761                           Mask[1] < 0 ? -1 : (Mask[1] * 2),
12762                           Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
12763     return DAG.getBitcast(
12764         MVT::v2i64,
12765         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
12766                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
12767   }
12768   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
12769   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
12770   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
12771   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
12772 
12773   if (Subtarget.hasAVX2())
12774     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12775       return Extract;
12776 
12777   // Try to use shift instructions.
12778   if (SDValue Shift =
12779           lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget,
12780                               DAG, /*BitwiseOnly*/ false))
12781     return Shift;
12782 
12783   // When loading a scalar and then shuffling it into a vector we can often do
12784   // the insertion cheaply.
12785   if (SDValue Insertion = lowerShuffleAsElementInsertion(
12786           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
12787     return Insertion;
12788   // Try inverting the insertion since for v2 masks it is easy to do and we
12789   // can't reliably sort the mask one way or the other.
12790   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
12791   if (SDValue Insertion = lowerShuffleAsElementInsertion(
12792           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
12793     return Insertion;
12794 
12795   // We have different paths for blend lowering, but they all must use the
12796   // *exact* same predicate.
12797   bool IsBlendSupported = Subtarget.hasSSE41();
12798   if (IsBlendSupported)
12799     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
12800                                             Zeroable, Subtarget, DAG))
12801       return Blend;
12802 
12803   // Use dedicated unpack instructions for masks that match their pattern.
12804   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
12805     return V;
12806 
12807   // Try to use byte rotation instructions.
12808   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
12809   if (Subtarget.hasSSSE3()) {
12810     if (Subtarget.hasVLX())
12811       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
12812                                                 Zeroable, Subtarget, DAG))
12813         return Rotate;
12814 
12815     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
12816                                                   Subtarget, DAG))
12817       return Rotate;
12818   }
12819 
12820   // If we have direct support for blends, we should lower by decomposing into
12821   // a permute. That will be faster than the domain cross.
12822   if (IsBlendSupported)
12823     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
12824                                                 Subtarget, DAG);
12825 
12826   // We implement this with SHUFPD which is pretty lame because it will likely
12827   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
12828   // However, all the alternatives are still more cycles and newer chips don't
12829   // have this problem. It would be really nice if x86 had better shuffles here.
12830   V1 = DAG.getBitcast(MVT::v2f64, V1);
12831   V2 = DAG.getBitcast(MVT::v2f64, V2);
12832   return DAG.getBitcast(MVT::v2i64,
12833                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
12834 }
12835 
12836 /// Lower a vector shuffle using the SHUFPS instruction.
12837 ///
12838 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
12839 /// It makes no assumptions about whether this is the *best* lowering, it simply
12840 /// uses it.
lowerShuffleWithSHUFPS(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)12841 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
12842                                       ArrayRef<int> Mask, SDValue V1,
12843                                       SDValue V2, SelectionDAG &DAG) {
12844   SDValue LowV = V1, HighV = V2;
12845   SmallVector<int, 4> NewMask(Mask);
12846   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12847 
12848   if (NumV2Elements == 1) {
12849     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
12850 
12851     // Compute the index adjacent to V2Index and in the same half by toggling
12852     // the low bit.
12853     int V2AdjIndex = V2Index ^ 1;
12854 
12855     if (Mask[V2AdjIndex] < 0) {
12856       // Handles all the cases where we have a single V2 element and an undef.
12857       // This will only ever happen in the high lanes because we commute the
12858       // vector otherwise.
12859       if (V2Index < 2)
12860         std::swap(LowV, HighV);
12861       NewMask[V2Index] -= 4;
12862     } else {
12863       // Handle the case where the V2 element ends up adjacent to a V1 element.
12864       // To make this work, blend them together as the first step.
12865       int V1Index = V2AdjIndex;
12866       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
12867       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
12868                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
12869 
12870       // Now proceed to reconstruct the final blend as we have the necessary
12871       // high or low half formed.
12872       if (V2Index < 2) {
12873         LowV = V2;
12874         HighV = V1;
12875       } else {
12876         HighV = V2;
12877       }
12878       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
12879       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
12880     }
12881   } else if (NumV2Elements == 2) {
12882     if (Mask[0] < 4 && Mask[1] < 4) {
12883       // Handle the easy case where we have V1 in the low lanes and V2 in the
12884       // high lanes.
12885       NewMask[2] -= 4;
12886       NewMask[3] -= 4;
12887     } else if (Mask[2] < 4 && Mask[3] < 4) {
12888       // We also handle the reversed case because this utility may get called
12889       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
12890       // arrange things in the right direction.
12891       NewMask[0] -= 4;
12892       NewMask[1] -= 4;
12893       HighV = V1;
12894       LowV = V2;
12895     } else {
12896       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
12897       // trying to place elements directly, just blend them and set up the final
12898       // shuffle to place them.
12899 
12900       // The first two blend mask elements are for V1, the second two are for
12901       // V2.
12902       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
12903                           Mask[2] < 4 ? Mask[2] : Mask[3],
12904                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
12905                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
12906       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
12907                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
12908 
12909       // Now we do a normal shuffle of V1 by giving V1 as both operands to
12910       // a blend.
12911       LowV = HighV = V1;
12912       NewMask[0] = Mask[0] < 4 ? 0 : 2;
12913       NewMask[1] = Mask[0] < 4 ? 2 : 0;
12914       NewMask[2] = Mask[2] < 4 ? 1 : 3;
12915       NewMask[3] = Mask[2] < 4 ? 3 : 1;
12916     }
12917   } else if (NumV2Elements == 3) {
12918     // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
12919     // we can get here due to other paths (e.g repeated mask matching) that we
12920     // don't want to do another round of lowerVECTOR_SHUFFLE.
12921     ShuffleVectorSDNode::commuteMask(NewMask);
12922     return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
12923   }
12924   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
12925                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
12926 }
12927 
12928 /// Lower 4-lane 32-bit floating point shuffles.
12929 ///
12930 /// Uses instructions exclusively from the floating point unit to minimize
12931 /// domain crossing penalties, as these are sufficient to implement all v4f32
12932 /// shuffles.
lowerV4F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)12933 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12934                                  const APInt &Zeroable, SDValue V1, SDValue V2,
12935                                  const X86Subtarget &Subtarget,
12936                                  SelectionDAG &DAG) {
12937   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12938   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
12939   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
12940 
12941   if (Subtarget.hasSSE41())
12942     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
12943                                             Zeroable, Subtarget, DAG))
12944       return Blend;
12945 
12946   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12947 
12948   if (NumV2Elements == 0) {
12949     // Check for being able to broadcast a single element.
12950     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
12951                                                     Mask, Subtarget, DAG))
12952       return Broadcast;
12953 
12954     // Use even/odd duplicate instructions for masks that match their pattern.
12955     if (Subtarget.hasSSE3()) {
12956       if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
12957         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
12958       if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
12959         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
12960     }
12961 
12962     if (Subtarget.hasAVX()) {
12963       // If we have AVX, we can use VPERMILPS which will allow folding a load
12964       // into the shuffle.
12965       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
12966                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12967     }
12968 
12969     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
12970     // in SSE1 because otherwise they are widened to v2f64 and never get here.
12971     if (!Subtarget.hasSSE2()) {
12972       if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
12973         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
12974       if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
12975         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
12976     }
12977 
12978     // Otherwise, use a straight shuffle of a single input vector. We pass the
12979     // input vector to both operands to simulate this with a SHUFPS.
12980     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
12981                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12982   }
12983 
12984   if (Subtarget.hasSSE2())
12985     if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
12986             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG)) {
12987       ZExt = DAG.getBitcast(MVT::v4f32, ZExt);
12988       return ZExt;
12989     }
12990 
12991   if (Subtarget.hasAVX2())
12992     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12993       return Extract;
12994 
12995   // There are special ways we can lower some single-element blends. However, we
12996   // have custom ways we can lower more complex single-element blends below that
12997   // we defer to if both this and BLENDPS fail to match, so restrict this to
12998   // when the V2 input is targeting element 0 of the mask -- that is the fast
12999   // case here.
13000   if (NumV2Elements == 1 && Mask[0] >= 4)
13001     if (SDValue V = lowerShuffleAsElementInsertion(
13002             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13003       return V;
13004 
13005   if (Subtarget.hasSSE41()) {
13006     // Use INSERTPS if we can complete the shuffle efficiently.
13007     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
13008       return V;
13009 
13010     if (!isSingleSHUFPSMask(Mask))
13011       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
13012                                                             V2, Mask, DAG))
13013         return BlendPerm;
13014   }
13015 
13016   // Use low/high mov instructions. These are only valid in SSE1 because
13017   // otherwise they are widened to v2f64 and never get here.
13018   if (!Subtarget.hasSSE2()) {
13019     if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
13020       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
13021     if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
13022       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
13023   }
13024 
13025   // Use dedicated unpack instructions for masks that match their pattern.
13026   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
13027     return V;
13028 
13029   // Otherwise fall back to a SHUFPS lowering strategy.
13030   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
13031 }
13032 
13033 /// Lower 4-lane i32 vector shuffles.
13034 ///
13035 /// We try to handle these with integer-domain shuffles where we can, but for
13036 /// blends we use the floating point domain blend instructions.
lowerV4I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13037 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13038                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13039                                  const X86Subtarget &Subtarget,
13040                                  SelectionDAG &DAG) {
13041   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
13042   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
13043   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13044 
13045   // Whenever we can lower this as a zext, that instruction is strictly faster
13046   // than any alternative. It also allows us to fold memory operands into the
13047   // shuffle in many cases.
13048   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
13049                                                    Zeroable, Subtarget, DAG))
13050     return ZExt;
13051 
13052   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13053 
13054   // Try to use shift instructions if fast.
13055   if (Subtarget.preferLowerShuffleAsShift()) {
13056     if (SDValue Shift =
13057             lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable,
13058                                 Subtarget, DAG, /*BitwiseOnly*/ true))
13059       return Shift;
13060     if (NumV2Elements == 0)
13061       if (SDValue Rotate =
13062               lowerShuffleAsBitRotate(DL, MVT::v4i32, V1, Mask, Subtarget, DAG))
13063         return Rotate;
13064   }
13065 
13066   if (NumV2Elements == 0) {
13067     // Try to use broadcast unless the mask only has one non-undef element.
13068     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
13069       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
13070                                                       Mask, Subtarget, DAG))
13071         return Broadcast;
13072     }
13073 
13074     // Straight shuffle of a single input vector. For everything from SSE2
13075     // onward this has a single fast instruction with no scary immediates.
13076     // We coerce the shuffle pattern to be compatible with UNPCK instructions
13077     // but we aren't actually going to use the UNPCK instruction because doing
13078     // so prevents folding a load into this instruction or making a copy.
13079     const int UnpackLoMask[] = {0, 0, 1, 1};
13080     const int UnpackHiMask[] = {2, 2, 3, 3};
13081     if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
13082       Mask = UnpackLoMask;
13083     else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
13084       Mask = UnpackHiMask;
13085 
13086     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13087                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13088   }
13089 
13090   if (Subtarget.hasAVX2())
13091     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13092       return Extract;
13093 
13094   // Try to use shift instructions.
13095   if (SDValue Shift =
13096           lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget,
13097                               DAG, /*BitwiseOnly*/ false))
13098     return Shift;
13099 
13100   // There are special ways we can lower some single-element blends.
13101   if (NumV2Elements == 1)
13102     if (SDValue V = lowerShuffleAsElementInsertion(
13103             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13104       return V;
13105 
13106   // We have different paths for blend lowering, but they all must use the
13107   // *exact* same predicate.
13108   bool IsBlendSupported = Subtarget.hasSSE41();
13109   if (IsBlendSupported)
13110     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
13111                                             Zeroable, Subtarget, DAG))
13112       return Blend;
13113 
13114   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
13115                                              Zeroable, Subtarget, DAG))
13116     return Masked;
13117 
13118   // Use dedicated unpack instructions for masks that match their pattern.
13119   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
13120     return V;
13121 
13122   // Try to use byte rotation instructions.
13123   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13124   if (Subtarget.hasSSSE3()) {
13125     if (Subtarget.hasVLX())
13126       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
13127                                                 Zeroable, Subtarget, DAG))
13128         return Rotate;
13129 
13130     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
13131                                                   Subtarget, DAG))
13132       return Rotate;
13133   }
13134 
13135   // Assume that a single SHUFPS is faster than an alternative sequence of
13136   // multiple instructions (even if the CPU has a domain penalty).
13137   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
13138   if (!isSingleSHUFPSMask(Mask)) {
13139     // If we have direct support for blends, we should lower by decomposing into
13140     // a permute. That will be faster than the domain cross.
13141     if (IsBlendSupported)
13142       return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
13143                                                   Subtarget, DAG);
13144 
13145     // Try to lower by permuting the inputs into an unpack instruction.
13146     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
13147                                                         Mask, Subtarget, DAG))
13148       return Unpack;
13149   }
13150 
13151   // We implement this with SHUFPS because it can blend from two vectors.
13152   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
13153   // up the inputs, bypassing domain shift penalties that we would incur if we
13154   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
13155   // relevant.
13156   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
13157   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
13158   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
13159   return DAG.getBitcast(MVT::v4i32, ShufPS);
13160 }
13161 
13162 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
13163 /// shuffle lowering, and the most complex part.
13164 ///
13165 /// The lowering strategy is to try to form pairs of input lanes which are
13166 /// targeted at the same half of the final vector, and then use a dword shuffle
13167 /// to place them onto the right half, and finally unpack the paired lanes into
13168 /// their final position.
13169 ///
13170 /// The exact breakdown of how to form these dword pairs and align them on the
13171 /// correct sides is really tricky. See the comments within the function for
13172 /// more of the details.
13173 ///
13174 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
13175 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
13176 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
13177 /// vector, form the analogous 128-bit 8-element Mask.
lowerV8I16GeneralSingleInputShuffle(const SDLoc & DL,MVT VT,SDValue V,MutableArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)13178 static SDValue lowerV8I16GeneralSingleInputShuffle(
13179     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
13180     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13181   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
13182   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
13183 
13184   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
13185   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
13186   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
13187 
13188   // Attempt to directly match PSHUFLW or PSHUFHW.
13189   if (isUndefOrInRange(LoMask, 0, 4) &&
13190       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
13191     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13192                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13193   }
13194   if (isUndefOrInRange(HiMask, 4, 8) &&
13195       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
13196     for (int i = 0; i != 4; ++i)
13197       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
13198     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13199                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13200   }
13201 
13202   SmallVector<int, 4> LoInputs;
13203   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
13204   array_pod_sort(LoInputs.begin(), LoInputs.end());
13205   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
13206   SmallVector<int, 4> HiInputs;
13207   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
13208   array_pod_sort(HiInputs.begin(), HiInputs.end());
13209   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
13210   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
13211   int NumHToL = LoInputs.size() - NumLToL;
13212   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
13213   int NumHToH = HiInputs.size() - NumLToH;
13214   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
13215   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
13216   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
13217   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
13218 
13219   // If we are shuffling values from one half - check how many different DWORD
13220   // pairs we need to create. If only 1 or 2 then we can perform this as a
13221   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
13222   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
13223                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
13224     V = DAG.getNode(ShufWOp, DL, VT, V,
13225                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13226     V = DAG.getBitcast(PSHUFDVT, V);
13227     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
13228                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13229     return DAG.getBitcast(VT, V);
13230   };
13231 
13232   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
13233     int PSHUFDMask[4] = { -1, -1, -1, -1 };
13234     SmallVector<std::pair<int, int>, 4> DWordPairs;
13235     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
13236 
13237     // Collect the different DWORD pairs.
13238     for (int DWord = 0; DWord != 4; ++DWord) {
13239       int M0 = Mask[2 * DWord + 0];
13240       int M1 = Mask[2 * DWord + 1];
13241       M0 = (M0 >= 0 ? M0 % 4 : M0);
13242       M1 = (M1 >= 0 ? M1 % 4 : M1);
13243       if (M0 < 0 && M1 < 0)
13244         continue;
13245 
13246       bool Match = false;
13247       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
13248         auto &DWordPair = DWordPairs[j];
13249         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
13250             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
13251           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
13252           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
13253           PSHUFDMask[DWord] = DOffset + j;
13254           Match = true;
13255           break;
13256         }
13257       }
13258       if (!Match) {
13259         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
13260         DWordPairs.push_back(std::make_pair(M0, M1));
13261       }
13262     }
13263 
13264     if (DWordPairs.size() <= 2) {
13265       DWordPairs.resize(2, std::make_pair(-1, -1));
13266       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
13267                               DWordPairs[1].first, DWordPairs[1].second};
13268       if ((NumHToL + NumHToH) == 0)
13269         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
13270       if ((NumLToL + NumLToH) == 0)
13271         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
13272     }
13273   }
13274 
13275   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
13276   // such inputs we can swap two of the dwords across the half mark and end up
13277   // with <=2 inputs to each half in each half. Once there, we can fall through
13278   // to the generic code below. For example:
13279   //
13280   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13281   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
13282   //
13283   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
13284   // and an existing 2-into-2 on the other half. In this case we may have to
13285   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
13286   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
13287   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
13288   // because any other situation (including a 3-into-1 or 1-into-3 in the other
13289   // half than the one we target for fixing) will be fixed when we re-enter this
13290   // path. We will also combine away any sequence of PSHUFD instructions that
13291   // result into a single instruction. Here is an example of the tricky case:
13292   //
13293   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13294   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
13295   //
13296   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
13297   //
13298   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
13299   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
13300   //
13301   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
13302   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
13303   //
13304   // The result is fine to be handled by the generic logic.
13305   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
13306                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
13307                           int AOffset, int BOffset) {
13308     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
13309            "Must call this with A having 3 or 1 inputs from the A half.");
13310     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
13311            "Must call this with B having 1 or 3 inputs from the B half.");
13312     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
13313            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
13314 
13315     bool ThreeAInputs = AToAInputs.size() == 3;
13316 
13317     // Compute the index of dword with only one word among the three inputs in
13318     // a half by taking the sum of the half with three inputs and subtracting
13319     // the sum of the actual three inputs. The difference is the remaining
13320     // slot.
13321     int ADWord = 0, BDWord = 0;
13322     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
13323     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
13324     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
13325     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
13326     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
13327     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
13328     int TripleNonInputIdx =
13329         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
13330     TripleDWord = TripleNonInputIdx / 2;
13331 
13332     // We use xor with one to compute the adjacent DWord to whichever one the
13333     // OneInput is in.
13334     OneInputDWord = (OneInput / 2) ^ 1;
13335 
13336     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
13337     // and BToA inputs. If there is also such a problem with the BToB and AToB
13338     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
13339     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
13340     // is essential that we don't *create* a 3<-1 as then we might oscillate.
13341     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
13342       // Compute how many inputs will be flipped by swapping these DWords. We
13343       // need
13344       // to balance this to ensure we don't form a 3-1 shuffle in the other
13345       // half.
13346       int NumFlippedAToBInputs = llvm::count(AToBInputs, 2 * ADWord) +
13347                                  llvm::count(AToBInputs, 2 * ADWord + 1);
13348       int NumFlippedBToBInputs = llvm::count(BToBInputs, 2 * BDWord) +
13349                                  llvm::count(BToBInputs, 2 * BDWord + 1);
13350       if ((NumFlippedAToBInputs == 1 &&
13351            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
13352           (NumFlippedBToBInputs == 1 &&
13353            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
13354         // We choose whether to fix the A half or B half based on whether that
13355         // half has zero flipped inputs. At zero, we may not be able to fix it
13356         // with that half. We also bias towards fixing the B half because that
13357         // will more commonly be the high half, and we have to bias one way.
13358         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
13359                                                        ArrayRef<int> Inputs) {
13360           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
13361           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
13362           // Determine whether the free index is in the flipped dword or the
13363           // unflipped dword based on where the pinned index is. We use this bit
13364           // in an xor to conditionally select the adjacent dword.
13365           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
13366           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13367           if (IsFixIdxInput == IsFixFreeIdxInput)
13368             FixFreeIdx += 1;
13369           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13370           assert(IsFixIdxInput != IsFixFreeIdxInput &&
13371                  "We need to be changing the number of flipped inputs!");
13372           int PSHUFHalfMask[] = {0, 1, 2, 3};
13373           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
13374           V = DAG.getNode(
13375               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
13376               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
13377               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13378 
13379           for (int &M : Mask)
13380             if (M >= 0 && M == FixIdx)
13381               M = FixFreeIdx;
13382             else if (M >= 0 && M == FixFreeIdx)
13383               M = FixIdx;
13384         };
13385         if (NumFlippedBToBInputs != 0) {
13386           int BPinnedIdx =
13387               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
13388           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
13389         } else {
13390           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
13391           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
13392           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
13393         }
13394       }
13395     }
13396 
13397     int PSHUFDMask[] = {0, 1, 2, 3};
13398     PSHUFDMask[ADWord] = BDWord;
13399     PSHUFDMask[BDWord] = ADWord;
13400     V = DAG.getBitcast(
13401         VT,
13402         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13403                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13404 
13405     // Adjust the mask to match the new locations of A and B.
13406     for (int &M : Mask)
13407       if (M >= 0 && M/2 == ADWord)
13408         M = 2 * BDWord + M % 2;
13409       else if (M >= 0 && M/2 == BDWord)
13410         M = 2 * ADWord + M % 2;
13411 
13412     // Recurse back into this routine to re-compute state now that this isn't
13413     // a 3 and 1 problem.
13414     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
13415   };
13416   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
13417     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
13418   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
13419     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
13420 
13421   // At this point there are at most two inputs to the low and high halves from
13422   // each half. That means the inputs can always be grouped into dwords and
13423   // those dwords can then be moved to the correct half with a dword shuffle.
13424   // We use at most one low and one high word shuffle to collect these paired
13425   // inputs into dwords, and finally a dword shuffle to place them.
13426   int PSHUFLMask[4] = {-1, -1, -1, -1};
13427   int PSHUFHMask[4] = {-1, -1, -1, -1};
13428   int PSHUFDMask[4] = {-1, -1, -1, -1};
13429 
13430   // First fix the masks for all the inputs that are staying in their
13431   // original halves. This will then dictate the targets of the cross-half
13432   // shuffles.
13433   auto fixInPlaceInputs =
13434       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
13435                     MutableArrayRef<int> SourceHalfMask,
13436                     MutableArrayRef<int> HalfMask, int HalfOffset) {
13437     if (InPlaceInputs.empty())
13438       return;
13439     if (InPlaceInputs.size() == 1) {
13440       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13441           InPlaceInputs[0] - HalfOffset;
13442       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
13443       return;
13444     }
13445     if (IncomingInputs.empty()) {
13446       // Just fix all of the in place inputs.
13447       for (int Input : InPlaceInputs) {
13448         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
13449         PSHUFDMask[Input / 2] = Input / 2;
13450       }
13451       return;
13452     }
13453 
13454     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
13455     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13456         InPlaceInputs[0] - HalfOffset;
13457     // Put the second input next to the first so that they are packed into
13458     // a dword. We find the adjacent index by toggling the low bit.
13459     int AdjIndex = InPlaceInputs[0] ^ 1;
13460     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
13461     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
13462     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
13463   };
13464   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
13465   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
13466 
13467   // Now gather the cross-half inputs and place them into a free dword of
13468   // their target half.
13469   // FIXME: This operation could almost certainly be simplified dramatically to
13470   // look more like the 3-1 fixing operation.
13471   auto moveInputsToRightHalf = [&PSHUFDMask](
13472       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
13473       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
13474       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
13475       int DestOffset) {
13476     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
13477       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
13478     };
13479     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
13480                                                int Word) {
13481       int LowWord = Word & ~1;
13482       int HighWord = Word | 1;
13483       return isWordClobbered(SourceHalfMask, LowWord) ||
13484              isWordClobbered(SourceHalfMask, HighWord);
13485     };
13486 
13487     if (IncomingInputs.empty())
13488       return;
13489 
13490     if (ExistingInputs.empty()) {
13491       // Map any dwords with inputs from them into the right half.
13492       for (int Input : IncomingInputs) {
13493         // If the source half mask maps over the inputs, turn those into
13494         // swaps and use the swapped lane.
13495         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
13496           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
13497             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
13498                 Input - SourceOffset;
13499             // We have to swap the uses in our half mask in one sweep.
13500             for (int &M : HalfMask)
13501               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
13502                 M = Input;
13503               else if (M == Input)
13504                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13505           } else {
13506             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
13507                        Input - SourceOffset &&
13508                    "Previous placement doesn't match!");
13509           }
13510           // Note that this correctly re-maps both when we do a swap and when
13511           // we observe the other side of the swap above. We rely on that to
13512           // avoid swapping the members of the input list directly.
13513           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13514         }
13515 
13516         // Map the input's dword into the correct half.
13517         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
13518           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
13519         else
13520           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
13521                      Input / 2 &&
13522                  "Previous placement doesn't match!");
13523       }
13524 
13525       // And just directly shift any other-half mask elements to be same-half
13526       // as we will have mirrored the dword containing the element into the
13527       // same position within that half.
13528       for (int &M : HalfMask)
13529         if (M >= SourceOffset && M < SourceOffset + 4) {
13530           M = M - SourceOffset + DestOffset;
13531           assert(M >= 0 && "This should never wrap below zero!");
13532         }
13533       return;
13534     }
13535 
13536     // Ensure we have the input in a viable dword of its current half. This
13537     // is particularly tricky because the original position may be clobbered
13538     // by inputs being moved and *staying* in that half.
13539     if (IncomingInputs.size() == 1) {
13540       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13541         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
13542                          SourceOffset;
13543         SourceHalfMask[InputFixed - SourceOffset] =
13544             IncomingInputs[0] - SourceOffset;
13545         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
13546                      InputFixed);
13547         IncomingInputs[0] = InputFixed;
13548       }
13549     } else if (IncomingInputs.size() == 2) {
13550       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
13551           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13552         // We have two non-adjacent or clobbered inputs we need to extract from
13553         // the source half. To do this, we need to map them into some adjacent
13554         // dword slot in the source mask.
13555         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
13556                               IncomingInputs[1] - SourceOffset};
13557 
13558         // If there is a free slot in the source half mask adjacent to one of
13559         // the inputs, place the other input in it. We use (Index XOR 1) to
13560         // compute an adjacent index.
13561         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
13562             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
13563           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
13564           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13565           InputsFixed[1] = InputsFixed[0] ^ 1;
13566         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
13567                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
13568           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
13569           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
13570           InputsFixed[0] = InputsFixed[1] ^ 1;
13571         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
13572                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
13573           // The two inputs are in the same DWord but it is clobbered and the
13574           // adjacent DWord isn't used at all. Move both inputs to the free
13575           // slot.
13576           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
13577           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
13578           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
13579           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
13580         } else {
13581           // The only way we hit this point is if there is no clobbering
13582           // (because there are no off-half inputs to this half) and there is no
13583           // free slot adjacent to one of the inputs. In this case, we have to
13584           // swap an input with a non-input.
13585           for (int i = 0; i < 4; ++i)
13586             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
13587                    "We can't handle any clobbers here!");
13588           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
13589                  "Cannot have adjacent inputs here!");
13590 
13591           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13592           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
13593 
13594           // We also have to update the final source mask in this case because
13595           // it may need to undo the above swap.
13596           for (int &M : FinalSourceHalfMask)
13597             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
13598               M = InputsFixed[1] + SourceOffset;
13599             else if (M == InputsFixed[1] + SourceOffset)
13600               M = (InputsFixed[0] ^ 1) + SourceOffset;
13601 
13602           InputsFixed[1] = InputsFixed[0] ^ 1;
13603         }
13604 
13605         // Point everything at the fixed inputs.
13606         for (int &M : HalfMask)
13607           if (M == IncomingInputs[0])
13608             M = InputsFixed[0] + SourceOffset;
13609           else if (M == IncomingInputs[1])
13610             M = InputsFixed[1] + SourceOffset;
13611 
13612         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
13613         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
13614       }
13615     } else {
13616       llvm_unreachable("Unhandled input size!");
13617     }
13618 
13619     // Now hoist the DWord down to the right half.
13620     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
13621     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
13622     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
13623     for (int &M : HalfMask)
13624       for (int Input : IncomingInputs)
13625         if (M == Input)
13626           M = FreeDWord * 2 + Input % 2;
13627   };
13628   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
13629                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
13630   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
13631                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
13632 
13633   // Now enact all the shuffles we've computed to move the inputs into their
13634   // target half.
13635   if (!isNoopShuffleMask(PSHUFLMask))
13636     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13637                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
13638   if (!isNoopShuffleMask(PSHUFHMask))
13639     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13640                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
13641   if (!isNoopShuffleMask(PSHUFDMask))
13642     V = DAG.getBitcast(
13643         VT,
13644         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13645                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13646 
13647   // At this point, each half should contain all its inputs, and we can then
13648   // just shuffle them into their final position.
13649   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
13650          "Failed to lift all the high half inputs to the low mask!");
13651   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
13652          "Failed to lift all the low half inputs to the high mask!");
13653 
13654   // Do a half shuffle for the low mask.
13655   if (!isNoopShuffleMask(LoMask))
13656     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13657                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13658 
13659   // Do a half shuffle with the high mask after shifting its values down.
13660   for (int &M : HiMask)
13661     if (M >= 0)
13662       M -= 4;
13663   if (!isNoopShuffleMask(HiMask))
13664     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13665                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13666 
13667   return V;
13668 }
13669 
13670 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
13671 /// blend if only one input is used.
lowerShuffleAsBlendOfPSHUFBs(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG,bool & V1InUse,bool & V2InUse)13672 static SDValue lowerShuffleAsBlendOfPSHUFBs(
13673     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13674     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
13675   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
13676          "Lane crossing shuffle masks not supported");
13677 
13678   int NumBytes = VT.getSizeInBits() / 8;
13679   int Size = Mask.size();
13680   int Scale = NumBytes / Size;
13681 
13682   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
13683   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
13684   V1InUse = false;
13685   V2InUse = false;
13686 
13687   for (int i = 0; i < NumBytes; ++i) {
13688     int M = Mask[i / Scale];
13689     if (M < 0)
13690       continue;
13691 
13692     const int ZeroMask = 0x80;
13693     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
13694     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
13695     if (Zeroable[i / Scale])
13696       V1Idx = V2Idx = ZeroMask;
13697 
13698     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
13699     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
13700     V1InUse |= (ZeroMask != V1Idx);
13701     V2InUse |= (ZeroMask != V2Idx);
13702   }
13703 
13704   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
13705   if (V1InUse)
13706     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
13707                      DAG.getBuildVector(ShufVT, DL, V1Mask));
13708   if (V2InUse)
13709     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
13710                      DAG.getBuildVector(ShufVT, DL, V2Mask));
13711 
13712   // If we need shuffled inputs from both, blend the two.
13713   SDValue V;
13714   if (V1InUse && V2InUse)
13715     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
13716   else
13717     V = V1InUse ? V1 : V2;
13718 
13719   // Cast the result back to the correct type.
13720   return DAG.getBitcast(VT, V);
13721 }
13722 
13723 /// Generic lowering of 8-lane i16 shuffles.
13724 ///
13725 /// This handles both single-input shuffles and combined shuffle/blends with
13726 /// two inputs. The single input shuffles are immediately delegated to
13727 /// a dedicated lowering routine.
13728 ///
13729 /// The blends are lowered in one of three fundamental ways. If there are few
13730 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
13731 /// of the input is significantly cheaper when lowered as an interleaving of
13732 /// the two inputs, try to interleave them. Otherwise, blend the low and high
13733 /// halves of the inputs separately (making them have relatively few inputs)
13734 /// and then concatenate them.
lowerV8I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13735 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13736                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13737                                  const X86Subtarget &Subtarget,
13738                                  SelectionDAG &DAG) {
13739   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
13740   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
13741   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
13742 
13743   // Whenever we can lower this as a zext, that instruction is strictly faster
13744   // than any alternative.
13745   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
13746                                                    Zeroable, Subtarget, DAG))
13747     return ZExt;
13748 
13749   // Try to use lower using a truncation.
13750   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
13751                                         Subtarget, DAG))
13752     return V;
13753 
13754   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
13755 
13756   if (NumV2Inputs == 0) {
13757     // Try to use shift instructions.
13758     if (SDValue Shift =
13759             lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, Zeroable,
13760                                 Subtarget, DAG, /*BitwiseOnly*/ false))
13761       return Shift;
13762 
13763     // Check for being able to broadcast a single element.
13764     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
13765                                                     Mask, Subtarget, DAG))
13766       return Broadcast;
13767 
13768     // Try to use bit rotation instructions.
13769     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
13770                                                  Subtarget, DAG))
13771       return Rotate;
13772 
13773     // Use dedicated unpack instructions for masks that match their pattern.
13774     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
13775       return V;
13776 
13777     // Use dedicated pack instructions for masks that match their pattern.
13778     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
13779                                          Subtarget))
13780       return V;
13781 
13782     // Try to use byte rotation instructions.
13783     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
13784                                                   Subtarget, DAG))
13785       return Rotate;
13786 
13787     // Make a copy of the mask so it can be modified.
13788     SmallVector<int, 8> MutableMask(Mask);
13789     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
13790                                                Subtarget, DAG);
13791   }
13792 
13793   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
13794          "All single-input shuffles should be canonicalized to be V1-input "
13795          "shuffles.");
13796 
13797   // Try to use shift instructions.
13798   if (SDValue Shift =
13799           lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget,
13800                               DAG, /*BitwiseOnly*/ false))
13801     return Shift;
13802 
13803   // See if we can use SSE4A Extraction / Insertion.
13804   if (Subtarget.hasSSE4A())
13805     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
13806                                           Zeroable, DAG))
13807       return V;
13808 
13809   // There are special ways we can lower some single-element blends.
13810   if (NumV2Inputs == 1)
13811     if (SDValue V = lowerShuffleAsElementInsertion(
13812             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
13813       return V;
13814 
13815   // We have different paths for blend lowering, but they all must use the
13816   // *exact* same predicate.
13817   bool IsBlendSupported = Subtarget.hasSSE41();
13818   if (IsBlendSupported)
13819     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
13820                                             Zeroable, Subtarget, DAG))
13821       return Blend;
13822 
13823   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
13824                                              Zeroable, Subtarget, DAG))
13825     return Masked;
13826 
13827   // Use dedicated unpack instructions for masks that match their pattern.
13828   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
13829     return V;
13830 
13831   // Use dedicated pack instructions for masks that match their pattern.
13832   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
13833                                        Subtarget))
13834     return V;
13835 
13836   // Try to use lower using a truncation.
13837   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
13838                                        Subtarget, DAG))
13839     return V;
13840 
13841   // Try to use byte rotation instructions.
13842   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
13843                                                 Subtarget, DAG))
13844     return Rotate;
13845 
13846   if (SDValue BitBlend =
13847           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
13848     return BitBlend;
13849 
13850   // Try to use byte shift instructions to mask.
13851   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
13852                                               Zeroable, Subtarget, DAG))
13853     return V;
13854 
13855   // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
13856   int NumEvenDrops = canLowerByDroppingElements(Mask, true, false);
13857   if ((NumEvenDrops == 1 || (NumEvenDrops == 2 && Subtarget.hasSSE41())) &&
13858       !Subtarget.hasVLX()) {
13859     // Check if this is part of a 256-bit vector truncation.
13860     unsigned PackOpc = 0;
13861     if (NumEvenDrops == 2 && Subtarget.hasAVX2() &&
13862         peekThroughBitcasts(V1).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
13863         peekThroughBitcasts(V2).getOpcode() == ISD::EXTRACT_SUBVECTOR) {
13864       SDValue V1V2 = concatSubVectors(V1, V2, DAG, DL);
13865       V1V2 = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1V2,
13866                          getZeroVector(MVT::v16i16, Subtarget, DAG, DL),
13867                          DAG.getTargetConstant(0xEE, DL, MVT::i8));
13868       V1V2 = DAG.getBitcast(MVT::v8i32, V1V2);
13869       V1 = extract128BitVector(V1V2, 0, DAG, DL);
13870       V2 = extract128BitVector(V1V2, 4, DAG, DL);
13871       PackOpc = X86ISD::PACKUS;
13872     } else if (Subtarget.hasSSE41()) {
13873       SmallVector<SDValue, 4> DWordClearOps(4,
13874                                             DAG.getConstant(0, DL, MVT::i32));
13875       for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
13876         DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
13877       SDValue DWordClearMask =
13878           DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
13879       V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
13880                        DWordClearMask);
13881       V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
13882                        DWordClearMask);
13883       PackOpc = X86ISD::PACKUS;
13884     } else if (!Subtarget.hasSSSE3()) {
13885       SDValue ShAmt = DAG.getTargetConstant(16, DL, MVT::i8);
13886       V1 = DAG.getBitcast(MVT::v4i32, V1);
13887       V2 = DAG.getBitcast(MVT::v4i32, V2);
13888       V1 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V1, ShAmt);
13889       V2 = DAG.getNode(X86ISD::VSHLI, DL, MVT::v4i32, V2, ShAmt);
13890       V1 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V1, ShAmt);
13891       V2 = DAG.getNode(X86ISD::VSRAI, DL, MVT::v4i32, V2, ShAmt);
13892       PackOpc = X86ISD::PACKSS;
13893     }
13894     if (PackOpc) {
13895       // Now pack things back together.
13896       SDValue Result = DAG.getNode(PackOpc, DL, MVT::v8i16, V1, V2);
13897       if (NumEvenDrops == 2) {
13898         Result = DAG.getBitcast(MVT::v4i32, Result);
13899         Result = DAG.getNode(PackOpc, DL, MVT::v8i16, Result, Result);
13900       }
13901       return Result;
13902     }
13903   }
13904 
13905   // When compacting odd (upper) elements, use PACKSS pre-SSE41.
13906   int NumOddDrops = canLowerByDroppingElements(Mask, false, false);
13907   if (NumOddDrops == 1) {
13908     bool HasSSE41 = Subtarget.hasSSE41();
13909     V1 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
13910                      DAG.getBitcast(MVT::v4i32, V1),
13911                      DAG.getTargetConstant(16, DL, MVT::i8));
13912     V2 = DAG.getNode(HasSSE41 ? X86ISD::VSRLI : X86ISD::VSRAI, DL, MVT::v4i32,
13913                      DAG.getBitcast(MVT::v4i32, V2),
13914                      DAG.getTargetConstant(16, DL, MVT::i8));
13915     return DAG.getNode(HasSSE41 ? X86ISD::PACKUS : X86ISD::PACKSS, DL,
13916                        MVT::v8i16, V1, V2);
13917   }
13918 
13919   // Try to lower by permuting the inputs into an unpack instruction.
13920   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
13921                                                       Mask, Subtarget, DAG))
13922     return Unpack;
13923 
13924   // If we can't directly blend but can use PSHUFB, that will be better as it
13925   // can both shuffle and set up the inefficient blend.
13926   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
13927     bool V1InUse, V2InUse;
13928     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
13929                                         Zeroable, DAG, V1InUse, V2InUse);
13930   }
13931 
13932   // We can always bit-blend if we have to so the fallback strategy is to
13933   // decompose into single-input permutes and blends/unpacks.
13934   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2,
13935                                               Mask, Subtarget, DAG);
13936 }
13937 
13938 /// Lower 8-lane 16-bit floating point shuffles.
lowerV8F16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13939 static SDValue lowerV8F16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13940                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13941                                  const X86Subtarget &Subtarget,
13942                                  SelectionDAG &DAG) {
13943   assert(V1.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
13944   assert(V2.getSimpleValueType() == MVT::v8f16 && "Bad operand type!");
13945   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
13946   int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
13947 
13948   if (Subtarget.hasFP16()) {
13949     if (NumV2Elements == 0) {
13950       // Check for being able to broadcast a single element.
13951       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f16, V1, V2,
13952                                                       Mask, Subtarget, DAG))
13953         return Broadcast;
13954     }
13955     if (NumV2Elements == 1 && Mask[0] >= 8)
13956       if (SDValue V = lowerShuffleAsElementInsertion(
13957               DL, MVT::v8f16, V1, V2, Mask, Zeroable, Subtarget, DAG))
13958         return V;
13959   }
13960 
13961   V1 = DAG.getBitcast(MVT::v8i16, V1);
13962   V2 = DAG.getBitcast(MVT::v8i16, V2);
13963   return DAG.getBitcast(MVT::v8f16,
13964                         DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
13965 }
13966 
13967 // Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
13968 // sub-512-bit shuffles are padded to 512-bits for the shuffle and then
13969 // the active subvector is extracted.
lowerShuffleWithPERMV(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13970 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
13971                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
13972                                      const X86Subtarget &Subtarget,
13973                                      SelectionDAG &DAG) {
13974   MVT MaskVT = VT.changeTypeToInteger();
13975   SDValue MaskNode;
13976   MVT ShuffleVT = VT;
13977   if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
13978     V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
13979     V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
13980     ShuffleVT = V1.getSimpleValueType();
13981 
13982     // Adjust mask to correct indices for the second input.
13983     int NumElts = VT.getVectorNumElements();
13984     unsigned Scale = 512 / VT.getSizeInBits();
13985     SmallVector<int, 32> AdjustedMask(Mask);
13986     for (int &M : AdjustedMask)
13987       if (NumElts <= M)
13988         M += (Scale - 1) * NumElts;
13989     MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
13990     MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
13991   } else {
13992     MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
13993   }
13994 
13995   SDValue Result;
13996   if (V2.isUndef())
13997     Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
13998   else
13999     Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
14000 
14001   if (VT != ShuffleVT)
14002     Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
14003 
14004   return Result;
14005 }
14006 
14007 /// Generic lowering of v16i8 shuffles.
14008 ///
14009 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
14010 /// detect any complexity reducing interleaving. If that doesn't help, it uses
14011 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
14012 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
14013 /// back together.
lowerV16I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14014 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14015                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14016                                  const X86Subtarget &Subtarget,
14017                                  SelectionDAG &DAG) {
14018   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14019   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14020   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
14021 
14022   // Try to use shift instructions.
14023   if (SDValue Shift =
14024           lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget,
14025                               DAG, /*BitwiseOnly*/ false))
14026     return Shift;
14027 
14028   // Try to use byte rotation instructions.
14029   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
14030                                                 Subtarget, DAG))
14031     return Rotate;
14032 
14033   // Use dedicated pack instructions for masks that match their pattern.
14034   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
14035                                        Subtarget))
14036     return V;
14037 
14038   // Try to use a zext lowering.
14039   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
14040                                                    Zeroable, Subtarget, DAG))
14041     return ZExt;
14042 
14043   // Try to use lower using a truncation.
14044   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
14045                                         Subtarget, DAG))
14046     return V;
14047 
14048   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
14049                                        Subtarget, DAG))
14050     return V;
14051 
14052   // See if we can use SSE4A Extraction / Insertion.
14053   if (Subtarget.hasSSE4A())
14054     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
14055                                           Zeroable, DAG))
14056       return V;
14057 
14058   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
14059 
14060   // For single-input shuffles, there are some nicer lowering tricks we can use.
14061   if (NumV2Elements == 0) {
14062     // Check for being able to broadcast a single element.
14063     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
14064                                                     Mask, Subtarget, DAG))
14065       return Broadcast;
14066 
14067     // Try to use bit rotation instructions.
14068     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
14069                                                  Subtarget, DAG))
14070       return Rotate;
14071 
14072     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
14073       return V;
14074 
14075     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
14076     // Notably, this handles splat and partial-splat shuffles more efficiently.
14077     // However, it only makes sense if the pre-duplication shuffle simplifies
14078     // things significantly. Currently, this means we need to be able to
14079     // express the pre-duplication shuffle as an i16 shuffle.
14080     //
14081     // FIXME: We should check for other patterns which can be widened into an
14082     // i16 shuffle as well.
14083     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
14084       for (int i = 0; i < 16; i += 2)
14085         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
14086           return false;
14087 
14088       return true;
14089     };
14090     auto tryToWidenViaDuplication = [&]() -> SDValue {
14091       if (!canWidenViaDuplication(Mask))
14092         return SDValue();
14093       SmallVector<int, 4> LoInputs;
14094       copy_if(Mask, std::back_inserter(LoInputs),
14095               [](int M) { return M >= 0 && M < 8; });
14096       array_pod_sort(LoInputs.begin(), LoInputs.end());
14097       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
14098                      LoInputs.end());
14099       SmallVector<int, 4> HiInputs;
14100       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
14101       array_pod_sort(HiInputs.begin(), HiInputs.end());
14102       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
14103                      HiInputs.end());
14104 
14105       bool TargetLo = LoInputs.size() >= HiInputs.size();
14106       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
14107       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
14108 
14109       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
14110       SmallDenseMap<int, int, 8> LaneMap;
14111       for (int I : InPlaceInputs) {
14112         PreDupI16Shuffle[I/2] = I/2;
14113         LaneMap[I] = I;
14114       }
14115       int j = TargetLo ? 0 : 4, je = j + 4;
14116       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
14117         // Check if j is already a shuffle of this input. This happens when
14118         // there are two adjacent bytes after we move the low one.
14119         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
14120           // If we haven't yet mapped the input, search for a slot into which
14121           // we can map it.
14122           while (j < je && PreDupI16Shuffle[j] >= 0)
14123             ++j;
14124 
14125           if (j == je)
14126             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
14127             return SDValue();
14128 
14129           // Map this input with the i16 shuffle.
14130           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
14131         }
14132 
14133         // Update the lane map based on the mapping we ended up with.
14134         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
14135       }
14136       V1 = DAG.getBitcast(
14137           MVT::v16i8,
14138           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14139                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
14140 
14141       // Unpack the bytes to form the i16s that will be shuffled into place.
14142       bool EvenInUse = false, OddInUse = false;
14143       for (int i = 0; i < 16; i += 2) {
14144         EvenInUse |= (Mask[i + 0] >= 0);
14145         OddInUse |= (Mask[i + 1] >= 0);
14146         if (EvenInUse && OddInUse)
14147           break;
14148       }
14149       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14150                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
14151                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
14152 
14153       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
14154       for (int i = 0; i < 16; ++i)
14155         if (Mask[i] >= 0) {
14156           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
14157           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
14158           if (PostDupI16Shuffle[i / 2] < 0)
14159             PostDupI16Shuffle[i / 2] = MappedMask;
14160           else
14161             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
14162                    "Conflicting entries in the original shuffle!");
14163         }
14164       return DAG.getBitcast(
14165           MVT::v16i8,
14166           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14167                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
14168     };
14169     if (SDValue V = tryToWidenViaDuplication())
14170       return V;
14171   }
14172 
14173   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
14174                                              Zeroable, Subtarget, DAG))
14175     return Masked;
14176 
14177   // Use dedicated unpack instructions for masks that match their pattern.
14178   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
14179     return V;
14180 
14181   // Try to use byte shift instructions to mask.
14182   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
14183                                               Zeroable, Subtarget, DAG))
14184     return V;
14185 
14186   // Check for compaction patterns.
14187   bool IsSingleInput = V2.isUndef();
14188   int NumEvenDrops = canLowerByDroppingElements(Mask, true, IsSingleInput);
14189 
14190   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
14191   // with PSHUFB. It is important to do this before we attempt to generate any
14192   // blends but after all of the single-input lowerings. If the single input
14193   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
14194   // want to preserve that and we can DAG combine any longer sequences into
14195   // a PSHUFB in the end. But once we start blending from multiple inputs,
14196   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
14197   // and there are *very* few patterns that would actually be faster than the
14198   // PSHUFB approach because of its ability to zero lanes.
14199   //
14200   // If the mask is a binary compaction, we can more efficiently perform this
14201   // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
14202   //
14203   // FIXME: The only exceptions to the above are blends which are exact
14204   // interleavings with direct instructions supporting them. We currently don't
14205   // handle those well here.
14206   if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
14207     bool V1InUse = false;
14208     bool V2InUse = false;
14209 
14210     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
14211         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
14212 
14213     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
14214     // do so. This avoids using them to handle blends-with-zero which is
14215     // important as a single pshufb is significantly faster for that.
14216     if (V1InUse && V2InUse) {
14217       if (Subtarget.hasSSE41())
14218         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
14219                                                 Zeroable, Subtarget, DAG))
14220           return Blend;
14221 
14222       // We can use an unpack to do the blending rather than an or in some
14223       // cases. Even though the or may be (very minorly) more efficient, we
14224       // preference this lowering because there are common cases where part of
14225       // the complexity of the shuffles goes away when we do the final blend as
14226       // an unpack.
14227       // FIXME: It might be worth trying to detect if the unpack-feeding
14228       // shuffles will both be pshufb, in which case we shouldn't bother with
14229       // this.
14230       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
14231               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14232         return Unpack;
14233 
14234       // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
14235       if (Subtarget.hasVBMI())
14236         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
14237                                      DAG);
14238 
14239       // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
14240       if (Subtarget.hasXOP()) {
14241         SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
14242         return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
14243       }
14244 
14245       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
14246       // PALIGNR will be cheaper than the second PSHUFB+OR.
14247       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
14248               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
14249         return V;
14250     }
14251 
14252     return PSHUFB;
14253   }
14254 
14255   // There are special ways we can lower some single-element blends.
14256   if (NumV2Elements == 1)
14257     if (SDValue V = lowerShuffleAsElementInsertion(
14258             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
14259       return V;
14260 
14261   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
14262     return Blend;
14263 
14264   // Check whether a compaction lowering can be done. This handles shuffles
14265   // which take every Nth element for some even N. See the helper function for
14266   // details.
14267   //
14268   // We special case these as they can be particularly efficiently handled with
14269   // the PACKUSB instruction on x86 and they show up in common patterns of
14270   // rearranging bytes to truncate wide elements.
14271   if (NumEvenDrops) {
14272     // NumEvenDrops is the power of two stride of the elements. Another way of
14273     // thinking about it is that we need to drop the even elements this many
14274     // times to get the original input.
14275 
14276     // First we need to zero all the dropped bytes.
14277     assert(NumEvenDrops <= 3 &&
14278            "No support for dropping even elements more than 3 times.");
14279     SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
14280     for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
14281       WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
14282     SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
14283     V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
14284                      WordClearMask);
14285     if (!IsSingleInput)
14286       V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
14287                        WordClearMask);
14288 
14289     // Now pack things back together.
14290     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
14291                                  IsSingleInput ? V1 : V2);
14292     for (int i = 1; i < NumEvenDrops; ++i) {
14293       Result = DAG.getBitcast(MVT::v8i16, Result);
14294       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
14295     }
14296     return Result;
14297   }
14298 
14299   int NumOddDrops = canLowerByDroppingElements(Mask, false, IsSingleInput);
14300   if (NumOddDrops == 1) {
14301     V1 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
14302                      DAG.getBitcast(MVT::v8i16, V1),
14303                      DAG.getTargetConstant(8, DL, MVT::i8));
14304     if (!IsSingleInput)
14305       V2 = DAG.getNode(X86ISD::VSRLI, DL, MVT::v8i16,
14306                        DAG.getBitcast(MVT::v8i16, V2),
14307                        DAG.getTargetConstant(8, DL, MVT::i8));
14308     return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
14309                        IsSingleInput ? V1 : V2);
14310   }
14311 
14312   // Handle multi-input cases by blending/unpacking single-input shuffles.
14313   if (NumV2Elements > 0)
14314     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
14315                                                 Subtarget, DAG);
14316 
14317   // The fallback path for single-input shuffles widens this into two v8i16
14318   // vectors with unpacks, shuffles those, and then pulls them back together
14319   // with a pack.
14320   SDValue V = V1;
14321 
14322   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14323   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14324   for (int i = 0; i < 16; ++i)
14325     if (Mask[i] >= 0)
14326       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
14327 
14328   SDValue VLoHalf, VHiHalf;
14329   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
14330   // them out and avoid using UNPCK{L,H} to extract the elements of V as
14331   // i16s.
14332   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
14333       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
14334     // Use a mask to drop the high bytes.
14335     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
14336     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
14337                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
14338 
14339     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
14340     VHiHalf = DAG.getUNDEF(MVT::v8i16);
14341 
14342     // Squash the masks to point directly into VLoHalf.
14343     for (int &M : LoBlendMask)
14344       if (M >= 0)
14345         M /= 2;
14346     for (int &M : HiBlendMask)
14347       if (M >= 0)
14348         M /= 2;
14349   } else {
14350     // Otherwise just unpack the low half of V into VLoHalf and the high half into
14351     // VHiHalf so that we can blend them as i16s.
14352     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
14353 
14354     VLoHalf = DAG.getBitcast(
14355         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
14356     VHiHalf = DAG.getBitcast(
14357         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
14358   }
14359 
14360   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
14361   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
14362 
14363   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
14364 }
14365 
14366 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
14367 ///
14368 /// This routine breaks down the specific type of 128-bit shuffle and
14369 /// dispatches to the lowering routines accordingly.
lower128BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)14370 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14371                                   MVT VT, SDValue V1, SDValue V2,
14372                                   const APInt &Zeroable,
14373                                   const X86Subtarget &Subtarget,
14374                                   SelectionDAG &DAG) {
14375   if (VT == MVT::v8bf16) {
14376     V1 = DAG.getBitcast(MVT::v8i16, V1);
14377     V2 = DAG.getBitcast(MVT::v8i16, V2);
14378     return DAG.getBitcast(VT,
14379                           DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, Mask));
14380   }
14381 
14382   switch (VT.SimpleTy) {
14383   case MVT::v2i64:
14384     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14385   case MVT::v2f64:
14386     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14387   case MVT::v4i32:
14388     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14389   case MVT::v4f32:
14390     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14391   case MVT::v8i16:
14392     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14393   case MVT::v8f16:
14394     return lowerV8F16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14395   case MVT::v16i8:
14396     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14397 
14398   default:
14399     llvm_unreachable("Unimplemented!");
14400   }
14401 }
14402 
14403 /// Generic routine to split vector shuffle into half-sized shuffles.
14404 ///
14405 /// This routine just extracts two subvectors, shuffles them independently, and
14406 /// then concatenates them back together. This should work effectively with all
14407 /// AVX vector shuffle types.
splitAndLowerShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,bool SimpleOnly)14408 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
14409                                     SDValue V2, ArrayRef<int> Mask,
14410                                     SelectionDAG &DAG, bool SimpleOnly) {
14411   assert(VT.getSizeInBits() >= 256 &&
14412          "Only for 256-bit or wider vector shuffles!");
14413   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
14414   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
14415 
14416   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
14417   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
14418 
14419   int NumElements = VT.getVectorNumElements();
14420   int SplitNumElements = NumElements / 2;
14421   MVT ScalarVT = VT.getVectorElementType();
14422   MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
14423 
14424   // Use splitVector/extractSubVector so that split build-vectors just build two
14425   // narrower build vectors. This helps shuffling with splats and zeros.
14426   auto SplitVector = [&](SDValue V) {
14427     SDValue LoV, HiV;
14428     std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
14429     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
14430                           DAG.getBitcast(SplitVT, HiV));
14431   };
14432 
14433   SDValue LoV1, HiV1, LoV2, HiV2;
14434   std::tie(LoV1, HiV1) = SplitVector(V1);
14435   std::tie(LoV2, HiV2) = SplitVector(V2);
14436 
14437   // Now create two 4-way blends of these half-width vectors.
14438   auto GetHalfBlendPiecesReq = [&](const ArrayRef<int> &HalfMask, bool &UseLoV1,
14439                                    bool &UseHiV1, bool &UseLoV2,
14440                                    bool &UseHiV2) {
14441     UseLoV1 = UseHiV1 = UseLoV2 = UseHiV2 = false;
14442     for (int i = 0; i < SplitNumElements; ++i) {
14443       int M = HalfMask[i];
14444       if (M >= NumElements) {
14445         if (M >= NumElements + SplitNumElements)
14446           UseHiV2 = true;
14447         else
14448           UseLoV2 = true;
14449       } else if (M >= 0) {
14450         if (M >= SplitNumElements)
14451           UseHiV1 = true;
14452         else
14453           UseLoV1 = true;
14454       }
14455     }
14456   };
14457 
14458   auto CheckHalfBlendUsable = [&](const ArrayRef<int> &HalfMask) -> bool {
14459     if (!SimpleOnly)
14460       return true;
14461 
14462     bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
14463     GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
14464 
14465     return !(UseHiV1 || UseHiV2);
14466   };
14467 
14468   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
14469     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
14470     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
14471     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
14472     for (int i = 0; i < SplitNumElements; ++i) {
14473       int M = HalfMask[i];
14474       if (M >= NumElements) {
14475         V2BlendMask[i] = M - NumElements;
14476         BlendMask[i] = SplitNumElements + i;
14477       } else if (M >= 0) {
14478         V1BlendMask[i] = M;
14479         BlendMask[i] = i;
14480       }
14481     }
14482 
14483     bool UseLoV1, UseHiV1, UseLoV2, UseHiV2;
14484     GetHalfBlendPiecesReq(HalfMask, UseLoV1, UseHiV1, UseLoV2, UseHiV2);
14485 
14486     // Because the lowering happens after all combining takes place, we need to
14487     // manually combine these blend masks as much as possible so that we create
14488     // a minimal number of high-level vector shuffle nodes.
14489     assert((!SimpleOnly || (!UseHiV1 && !UseHiV2)) && "Shuffle isn't simple");
14490 
14491     // First try just blending the halves of V1 or V2.
14492     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
14493       return DAG.getUNDEF(SplitVT);
14494     if (!UseLoV2 && !UseHiV2)
14495       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14496     if (!UseLoV1 && !UseHiV1)
14497       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14498 
14499     SDValue V1Blend, V2Blend;
14500     if (UseLoV1 && UseHiV1) {
14501       V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14502     } else {
14503       // We only use half of V1 so map the usage down into the final blend mask.
14504       V1Blend = UseLoV1 ? LoV1 : HiV1;
14505       for (int i = 0; i < SplitNumElements; ++i)
14506         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
14507           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
14508     }
14509     if (UseLoV2 && UseHiV2) {
14510       V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14511     } else {
14512       // We only use half of V2 so map the usage down into the final blend mask.
14513       V2Blend = UseLoV2 ? LoV2 : HiV2;
14514       for (int i = 0; i < SplitNumElements; ++i)
14515         if (BlendMask[i] >= SplitNumElements)
14516           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
14517     }
14518     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
14519   };
14520 
14521   if (!CheckHalfBlendUsable(LoMask) || !CheckHalfBlendUsable(HiMask))
14522     return SDValue();
14523 
14524   SDValue Lo = HalfBlend(LoMask);
14525   SDValue Hi = HalfBlend(HiMask);
14526   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
14527 }
14528 
14529 /// Either split a vector in halves or decompose the shuffles and the
14530 /// blend/unpack.
14531 ///
14532 /// This is provided as a good fallback for many lowerings of non-single-input
14533 /// shuffles with more than one 128-bit lane. In those cases, we want to select
14534 /// between splitting the shuffle into 128-bit components and stitching those
14535 /// back together vs. extracting the single-input shuffles and blending those
14536 /// results.
lowerShuffleAsSplitOrBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)14537 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
14538                                           SDValue V2, ArrayRef<int> Mask,
14539                                           const X86Subtarget &Subtarget,
14540                                           SelectionDAG &DAG) {
14541   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
14542          "shuffles as it could then recurse on itself.");
14543   int Size = Mask.size();
14544 
14545   // If this can be modeled as a broadcast of two elements followed by a blend,
14546   // prefer that lowering. This is especially important because broadcasts can
14547   // often fold with memory operands.
14548   auto DoBothBroadcast = [&] {
14549     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
14550     for (int M : Mask)
14551       if (M >= Size) {
14552         if (V2BroadcastIdx < 0)
14553           V2BroadcastIdx = M - Size;
14554         else if (M - Size != V2BroadcastIdx)
14555           return false;
14556       } else if (M >= 0) {
14557         if (V1BroadcastIdx < 0)
14558           V1BroadcastIdx = M;
14559         else if (M != V1BroadcastIdx)
14560           return false;
14561       }
14562     return true;
14563   };
14564   if (DoBothBroadcast())
14565     return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
14566                                                 DAG);
14567 
14568   // If the inputs all stem from a single 128-bit lane of each input, then we
14569   // split them rather than blending because the split will decompose to
14570   // unusually few instructions.
14571   int LaneCount = VT.getSizeInBits() / 128;
14572   int LaneSize = Size / LaneCount;
14573   SmallBitVector LaneInputs[2];
14574   LaneInputs[0].resize(LaneCount, false);
14575   LaneInputs[1].resize(LaneCount, false);
14576   for (int i = 0; i < Size; ++i)
14577     if (Mask[i] >= 0)
14578       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
14579   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
14580     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
14581                                 /*SimpleOnly*/ false);
14582 
14583   // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
14584   // requires that the decomposed single-input shuffles don't end up here.
14585   return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
14586                                               DAG);
14587 }
14588 
14589 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
14590 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
lowerShuffleAsLanePermuteAndSHUFP(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)14591 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
14592                                                  SDValue V1, SDValue V2,
14593                                                  ArrayRef<int> Mask,
14594                                                  SelectionDAG &DAG) {
14595   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
14596 
14597   int LHSMask[4] = {-1, -1, -1, -1};
14598   int RHSMask[4] = {-1, -1, -1, -1};
14599   unsigned SHUFPMask = 0;
14600 
14601   // As SHUFPD uses a single LHS/RHS element per lane, we can always
14602   // perform the shuffle once the lanes have been shuffled in place.
14603   for (int i = 0; i != 4; ++i) {
14604     int M = Mask[i];
14605     if (M < 0)
14606       continue;
14607     int LaneBase = i & ~1;
14608     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
14609     LaneMask[LaneBase + (M & 1)] = M;
14610     SHUFPMask |= (M & 1) << i;
14611   }
14612 
14613   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
14614   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
14615   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
14616                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
14617 }
14618 
14619 /// Lower a vector shuffle crossing multiple 128-bit lanes as
14620 /// a lane permutation followed by a per-lane permutation.
14621 ///
14622 /// This is mainly for cases where we can have non-repeating permutes
14623 /// in each lane.
14624 ///
14625 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
14626 /// we should investigate merging them.
lowerShuffleAsLanePermuteAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)14627 static SDValue lowerShuffleAsLanePermuteAndPermute(
14628     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14629     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14630   int NumElts = VT.getVectorNumElements();
14631   int NumLanes = VT.getSizeInBits() / 128;
14632   int NumEltsPerLane = NumElts / NumLanes;
14633   bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
14634 
14635   /// Attempts to find a sublane permute with the given size
14636   /// that gets all elements into their target lanes.
14637   ///
14638   /// If successful, fills CrossLaneMask and InLaneMask and returns true.
14639   /// If unsuccessful, returns false and may overwrite InLaneMask.
14640   auto getSublanePermute = [&](int NumSublanes) -> SDValue {
14641     int NumSublanesPerLane = NumSublanes / NumLanes;
14642     int NumEltsPerSublane = NumElts / NumSublanes;
14643 
14644     SmallVector<int, 16> CrossLaneMask;
14645     SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
14646     // CrossLaneMask but one entry == one sublane.
14647     SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
14648 
14649     for (int i = 0; i != NumElts; ++i) {
14650       int M = Mask[i];
14651       if (M < 0)
14652         continue;
14653 
14654       int SrcSublane = M / NumEltsPerSublane;
14655       int DstLane = i / NumEltsPerLane;
14656 
14657       // We only need to get the elements into the right lane, not sublane.
14658       // So search all sublanes that make up the destination lane.
14659       bool Found = false;
14660       int DstSubStart = DstLane * NumSublanesPerLane;
14661       int DstSubEnd = DstSubStart + NumSublanesPerLane;
14662       for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
14663         if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
14664           continue;
14665 
14666         Found = true;
14667         CrossLaneMaskLarge[DstSublane] = SrcSublane;
14668         int DstSublaneOffset = DstSublane * NumEltsPerSublane;
14669         InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
14670         break;
14671       }
14672       if (!Found)
14673         return SDValue();
14674     }
14675 
14676     // Fill CrossLaneMask using CrossLaneMaskLarge.
14677     narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
14678 
14679     if (!CanUseSublanes) {
14680       // If we're only shuffling a single lowest lane and the rest are identity
14681       // then don't bother.
14682       // TODO - isShuffleMaskInputInPlace could be extended to something like
14683       // this.
14684       int NumIdentityLanes = 0;
14685       bool OnlyShuffleLowestLane = true;
14686       for (int i = 0; i != NumLanes; ++i) {
14687         int LaneOffset = i * NumEltsPerLane;
14688         if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
14689                                        i * NumEltsPerLane))
14690           NumIdentityLanes++;
14691         else if (CrossLaneMask[LaneOffset] != 0)
14692           OnlyShuffleLowestLane = false;
14693       }
14694       if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
14695         return SDValue();
14696     }
14697 
14698     // Avoid returning the same shuffle operation. For example,
14699     // t7: v16i16 = vector_shuffle<8,9,10,11,4,5,6,7,0,1,2,3,12,13,14,15> t5,
14700     //                             undef:v16i16
14701     if (CrossLaneMask == Mask || InLaneMask == Mask)
14702       return SDValue();
14703 
14704     SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
14705     return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
14706                                 InLaneMask);
14707   };
14708 
14709   // First attempt a solution with full lanes.
14710   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
14711     return V;
14712 
14713   // The rest of the solutions use sublanes.
14714   if (!CanUseSublanes)
14715     return SDValue();
14716 
14717   // Then attempt a solution with 64-bit sublanes (vpermq).
14718   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
14719     return V;
14720 
14721   // If that doesn't work and we have fast variable cross-lane shuffle,
14722   // attempt 32-bit sublanes (vpermd).
14723   if (!Subtarget.hasFastVariableCrossLaneShuffle())
14724     return SDValue();
14725 
14726   return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
14727 }
14728 
14729 /// Helper to get compute inlane shuffle mask for a complete shuffle mask.
computeInLaneShuffleMask(const ArrayRef<int> & Mask,int LaneSize,SmallVector<int> & InLaneMask)14730 static void computeInLaneShuffleMask(const ArrayRef<int> &Mask, int LaneSize,
14731                                      SmallVector<int> &InLaneMask) {
14732   int Size = Mask.size();
14733   InLaneMask.assign(Mask.begin(), Mask.end());
14734   for (int i = 0; i < Size; ++i) {
14735     int &M = InLaneMask[i];
14736     if (M < 0)
14737       continue;
14738     if (((M % Size) / LaneSize) != (i / LaneSize))
14739       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
14740   }
14741 }
14742 
14743 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
14744 /// source with a lane permutation.
14745 ///
14746 /// This lowering strategy results in four instructions in the worst case for a
14747 /// single-input cross lane shuffle which is lower than any other fully general
14748 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
14749 /// shuffle pattern should be handled prior to trying this lowering.
lowerShuffleAsLanePermuteAndShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)14750 static SDValue lowerShuffleAsLanePermuteAndShuffle(
14751     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14752     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14753   // FIXME: This should probably be generalized for 512-bit vectors as well.
14754   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
14755   int Size = Mask.size();
14756   int LaneSize = Size / 2;
14757 
14758   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
14759   // Only do this if the elements aren't all from the lower lane,
14760   // otherwise we're (probably) better off doing a split.
14761   if (VT == MVT::v4f64 &&
14762       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
14763     return lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG);
14764 
14765   // If there are only inputs from one 128-bit lane, splitting will in fact be
14766   // less expensive. The flags track whether the given lane contains an element
14767   // that crosses to another lane.
14768   bool AllLanes;
14769   if (!Subtarget.hasAVX2()) {
14770     bool LaneCrossing[2] = {false, false};
14771     for (int i = 0; i < Size; ++i)
14772       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
14773         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
14774     AllLanes = LaneCrossing[0] && LaneCrossing[1];
14775   } else {
14776     bool LaneUsed[2] = {false, false};
14777     for (int i = 0; i < Size; ++i)
14778       if (Mask[i] >= 0)
14779         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
14780     AllLanes = LaneUsed[0] && LaneUsed[1];
14781   }
14782 
14783   // TODO - we could support shuffling V2 in the Flipped input.
14784   assert(V2.isUndef() &&
14785          "This last part of this routine only works on single input shuffles");
14786 
14787   SmallVector<int> InLaneMask;
14788   computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
14789 
14790   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
14791          "In-lane shuffle mask expected");
14792 
14793   // If we're not using both lanes in each lane and the inlane mask is not
14794   // repeating, then we're better off splitting.
14795   if (!AllLanes && !is128BitLaneRepeatedShuffleMask(VT, InLaneMask))
14796     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
14797                                 /*SimpleOnly*/ false);
14798 
14799   // Flip the lanes, and shuffle the results which should now be in-lane.
14800   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
14801   SDValue Flipped = DAG.getBitcast(PVT, V1);
14802   Flipped =
14803       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
14804   Flipped = DAG.getBitcast(VT, Flipped);
14805   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
14806 }
14807 
14808 /// Handle lowering 2-lane 128-bit shuffles.
lowerV2X128Shuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)14809 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
14810                                   SDValue V2, ArrayRef<int> Mask,
14811                                   const APInt &Zeroable,
14812                                   const X86Subtarget &Subtarget,
14813                                   SelectionDAG &DAG) {
14814   if (V2.isUndef()) {
14815     // Attempt to match VBROADCAST*128 subvector broadcast load.
14816     bool SplatLo = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1);
14817     bool SplatHi = isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1);
14818     if ((SplatLo || SplatHi) && !Subtarget.hasAVX512() && V1.hasOneUse() &&
14819         X86::mayFoldLoad(peekThroughOneUseBitcasts(V1), Subtarget)) {
14820       MVT MemVT = VT.getHalfNumVectorElementsVT();
14821       unsigned Ofs = SplatLo ? 0 : MemVT.getStoreSize();
14822       auto *Ld = cast<LoadSDNode>(peekThroughOneUseBitcasts(V1));
14823       if (SDValue BcstLd = getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, DL,
14824                                              VT, MemVT, Ld, Ofs, DAG))
14825         return BcstLd;
14826     }
14827 
14828     // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
14829     if (Subtarget.hasAVX2())
14830       return SDValue();
14831   }
14832 
14833   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
14834 
14835   SmallVector<int, 4> WidenedMask;
14836   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
14837     return SDValue();
14838 
14839   bool IsLowZero = (Zeroable & 0x3) == 0x3;
14840   bool IsHighZero = (Zeroable & 0xc) == 0xc;
14841 
14842   // Try to use an insert into a zero vector.
14843   if (WidenedMask[0] == 0 && IsHighZero) {
14844     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
14845     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
14846                               DAG.getIntPtrConstant(0, DL));
14847     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14848                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
14849                        DAG.getIntPtrConstant(0, DL));
14850   }
14851 
14852   // TODO: If minimizing size and one of the inputs is a zero vector and the
14853   // the zero vector has only one use, we could use a VPERM2X128 to save the
14854   // instruction bytes needed to explicitly generate the zero vector.
14855 
14856   // Blends are faster and handle all the non-lane-crossing cases.
14857   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
14858                                           Subtarget, DAG))
14859     return Blend;
14860 
14861   // If either input operand is a zero vector, use VPERM2X128 because its mask
14862   // allows us to replace the zero input with an implicit zero.
14863   if (!IsLowZero && !IsHighZero) {
14864     // Check for patterns which can be matched with a single insert of a 128-bit
14865     // subvector.
14866     bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
14867     if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
14868 
14869       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
14870       // this will likely become vinsertf128 which can't fold a 256-bit memop.
14871       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
14872         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
14873         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
14874                                      OnlyUsesV1 ? V1 : V2,
14875                                      DAG.getIntPtrConstant(0, DL));
14876         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
14877                            DAG.getIntPtrConstant(2, DL));
14878       }
14879     }
14880 
14881     // Try to use SHUF128 if possible.
14882     if (Subtarget.hasVLX()) {
14883       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
14884         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
14885                             ((WidenedMask[1] % 2) << 1);
14886         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
14887                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
14888       }
14889     }
14890   }
14891 
14892   // Otherwise form a 128-bit permutation. After accounting for undefs,
14893   // convert the 64-bit shuffle mask selection values into 128-bit
14894   // selection bits by dividing the indexes by 2 and shifting into positions
14895   // defined by a vperm2*128 instruction's immediate control byte.
14896 
14897   // The immediate permute control byte looks like this:
14898   //    [1:0] - select 128 bits from sources for low half of destination
14899   //    [2]   - ignore
14900   //    [3]   - zero low half of destination
14901   //    [5:4] - select 128 bits from sources for high half of destination
14902   //    [6]   - ignore
14903   //    [7]   - zero high half of destination
14904 
14905   assert((WidenedMask[0] >= 0 || IsLowZero) &&
14906          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
14907 
14908   unsigned PermMask = 0;
14909   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
14910   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
14911 
14912   // Check the immediate mask and replace unused sources with undef.
14913   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
14914     V1 = DAG.getUNDEF(VT);
14915   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
14916     V2 = DAG.getUNDEF(VT);
14917 
14918   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
14919                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
14920 }
14921 
14922 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
14923 /// shuffling each lane.
14924 ///
14925 /// This attempts to create a repeated lane shuffle where each lane uses one
14926 /// or two of the lanes of the inputs. The lanes of the input vectors are
14927 /// shuffled in one or two independent shuffles to get the lanes into the
14928 /// position needed by the final shuffle.
lowerShuffleAsLanePermuteAndRepeatedMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)14929 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
14930     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14931     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14932   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
14933 
14934   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
14935     return SDValue();
14936 
14937   int NumElts = Mask.size();
14938   int NumLanes = VT.getSizeInBits() / 128;
14939   int NumLaneElts = 128 / VT.getScalarSizeInBits();
14940   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
14941   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
14942 
14943   // First pass will try to fill in the RepeatMask from lanes that need two
14944   // sources.
14945   for (int Lane = 0; Lane != NumLanes; ++Lane) {
14946     int Srcs[2] = {-1, -1};
14947     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
14948     for (int i = 0; i != NumLaneElts; ++i) {
14949       int M = Mask[(Lane * NumLaneElts) + i];
14950       if (M < 0)
14951         continue;
14952       // Determine which of the possible input lanes (NumLanes from each source)
14953       // this element comes from. Assign that as one of the sources for this
14954       // lane. We can assign up to 2 sources for this lane. If we run out
14955       // sources we can't do anything.
14956       int LaneSrc = M / NumLaneElts;
14957       int Src;
14958       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
14959         Src = 0;
14960       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
14961         Src = 1;
14962       else
14963         return SDValue();
14964 
14965       Srcs[Src] = LaneSrc;
14966       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
14967     }
14968 
14969     // If this lane has two sources, see if it fits with the repeat mask so far.
14970     if (Srcs[1] < 0)
14971       continue;
14972 
14973     LaneSrcs[Lane][0] = Srcs[0];
14974     LaneSrcs[Lane][1] = Srcs[1];
14975 
14976     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
14977       assert(M1.size() == M2.size() && "Unexpected mask size");
14978       for (int i = 0, e = M1.size(); i != e; ++i)
14979         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
14980           return false;
14981       return true;
14982     };
14983 
14984     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
14985       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
14986       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
14987         int M = Mask[i];
14988         if (M < 0)
14989           continue;
14990         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
14991                "Unexpected mask element");
14992         MergedMask[i] = M;
14993       }
14994     };
14995 
14996     if (MatchMasks(InLaneMask, RepeatMask)) {
14997       // Merge this lane mask into the final repeat mask.
14998       MergeMasks(InLaneMask, RepeatMask);
14999       continue;
15000     }
15001 
15002     // Didn't find a match. Swap the operands and try again.
15003     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
15004     ShuffleVectorSDNode::commuteMask(InLaneMask);
15005 
15006     if (MatchMasks(InLaneMask, RepeatMask)) {
15007       // Merge this lane mask into the final repeat mask.
15008       MergeMasks(InLaneMask, RepeatMask);
15009       continue;
15010     }
15011 
15012     // Couldn't find a match with the operands in either order.
15013     return SDValue();
15014   }
15015 
15016   // Now handle any lanes with only one source.
15017   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15018     // If this lane has already been processed, skip it.
15019     if (LaneSrcs[Lane][0] >= 0)
15020       continue;
15021 
15022     for (int i = 0; i != NumLaneElts; ++i) {
15023       int M = Mask[(Lane * NumLaneElts) + i];
15024       if (M < 0)
15025         continue;
15026 
15027       // If RepeatMask isn't defined yet we can define it ourself.
15028       if (RepeatMask[i] < 0)
15029         RepeatMask[i] = M % NumLaneElts;
15030 
15031       if (RepeatMask[i] < NumElts) {
15032         if (RepeatMask[i] != M % NumLaneElts)
15033           return SDValue();
15034         LaneSrcs[Lane][0] = M / NumLaneElts;
15035       } else {
15036         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
15037           return SDValue();
15038         LaneSrcs[Lane][1] = M / NumLaneElts;
15039       }
15040     }
15041 
15042     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
15043       return SDValue();
15044   }
15045 
15046   SmallVector<int, 16> NewMask(NumElts, -1);
15047   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15048     int Src = LaneSrcs[Lane][0];
15049     for (int i = 0; i != NumLaneElts; ++i) {
15050       int M = -1;
15051       if (Src >= 0)
15052         M = Src * NumLaneElts + i;
15053       NewMask[Lane * NumLaneElts + i] = M;
15054     }
15055   }
15056   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15057   // Ensure we didn't get back the shuffle we started with.
15058   // FIXME: This is a hack to make up for some splat handling code in
15059   // getVectorShuffle.
15060   if (isa<ShuffleVectorSDNode>(NewV1) &&
15061       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
15062     return SDValue();
15063 
15064   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15065     int Src = LaneSrcs[Lane][1];
15066     for (int i = 0; i != NumLaneElts; ++i) {
15067       int M = -1;
15068       if (Src >= 0)
15069         M = Src * NumLaneElts + i;
15070       NewMask[Lane * NumLaneElts + i] = M;
15071     }
15072   }
15073   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15074   // Ensure we didn't get back the shuffle we started with.
15075   // FIXME: This is a hack to make up for some splat handling code in
15076   // getVectorShuffle.
15077   if (isa<ShuffleVectorSDNode>(NewV2) &&
15078       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
15079     return SDValue();
15080 
15081   for (int i = 0; i != NumElts; ++i) {
15082     if (Mask[i] < 0) {
15083       NewMask[i] = -1;
15084       continue;
15085     }
15086     NewMask[i] = RepeatMask[i % NumLaneElts];
15087     if (NewMask[i] < 0)
15088       continue;
15089 
15090     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
15091   }
15092   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
15093 }
15094 
15095 /// If the input shuffle mask results in a vector that is undefined in all upper
15096 /// or lower half elements and that mask accesses only 2 halves of the
15097 /// shuffle's operands, return true. A mask of half the width with mask indexes
15098 /// adjusted to access the extracted halves of the original shuffle operands is
15099 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
15100 /// lower half of each input operand is accessed.
15101 static bool
getHalfShuffleMask(ArrayRef<int> Mask,MutableArrayRef<int> HalfMask,int & HalfIdx1,int & HalfIdx2)15102 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
15103                    int &HalfIdx1, int &HalfIdx2) {
15104   assert((Mask.size() == HalfMask.size() * 2) &&
15105          "Expected input mask to be twice as long as output");
15106 
15107   // Exactly one half of the result must be undef to allow narrowing.
15108   bool UndefLower = isUndefLowerHalf(Mask);
15109   bool UndefUpper = isUndefUpperHalf(Mask);
15110   if (UndefLower == UndefUpper)
15111     return false;
15112 
15113   unsigned HalfNumElts = HalfMask.size();
15114   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
15115   HalfIdx1 = -1;
15116   HalfIdx2 = -1;
15117   for (unsigned i = 0; i != HalfNumElts; ++i) {
15118     int M = Mask[i + MaskIndexOffset];
15119     if (M < 0) {
15120       HalfMask[i] = M;
15121       continue;
15122     }
15123 
15124     // Determine which of the 4 half vectors this element is from.
15125     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
15126     int HalfIdx = M / HalfNumElts;
15127 
15128     // Determine the element index into its half vector source.
15129     int HalfElt = M % HalfNumElts;
15130 
15131     // We can shuffle with up to 2 half vectors, set the new 'half'
15132     // shuffle mask accordingly.
15133     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
15134       HalfMask[i] = HalfElt;
15135       HalfIdx1 = HalfIdx;
15136       continue;
15137     }
15138     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
15139       HalfMask[i] = HalfElt + HalfNumElts;
15140       HalfIdx2 = HalfIdx;
15141       continue;
15142     }
15143 
15144     // Too many half vectors referenced.
15145     return false;
15146   }
15147 
15148   return true;
15149 }
15150 
15151 /// Given the output values from getHalfShuffleMask(), create a half width
15152 /// shuffle of extracted vectors followed by an insert back to full width.
getShuffleHalfVectors(const SDLoc & DL,SDValue V1,SDValue V2,ArrayRef<int> HalfMask,int HalfIdx1,int HalfIdx2,bool UndefLower,SelectionDAG & DAG,bool UseConcat=false)15153 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
15154                                      ArrayRef<int> HalfMask, int HalfIdx1,
15155                                      int HalfIdx2, bool UndefLower,
15156                                      SelectionDAG &DAG, bool UseConcat = false) {
15157   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
15158   assert(V1.getValueType().isSimple() && "Expecting only simple types");
15159 
15160   MVT VT = V1.getSimpleValueType();
15161   MVT HalfVT = VT.getHalfNumVectorElementsVT();
15162   unsigned HalfNumElts = HalfVT.getVectorNumElements();
15163 
15164   auto getHalfVector = [&](int HalfIdx) {
15165     if (HalfIdx < 0)
15166       return DAG.getUNDEF(HalfVT);
15167     SDValue V = (HalfIdx < 2 ? V1 : V2);
15168     HalfIdx = (HalfIdx % 2) * HalfNumElts;
15169     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
15170                        DAG.getIntPtrConstant(HalfIdx, DL));
15171   };
15172 
15173   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
15174   SDValue Half1 = getHalfVector(HalfIdx1);
15175   SDValue Half2 = getHalfVector(HalfIdx2);
15176   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
15177   if (UseConcat) {
15178     SDValue Op0 = V;
15179     SDValue Op1 = DAG.getUNDEF(HalfVT);
15180     if (UndefLower)
15181       std::swap(Op0, Op1);
15182     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
15183   }
15184 
15185   unsigned Offset = UndefLower ? HalfNumElts : 0;
15186   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
15187                      DAG.getIntPtrConstant(Offset, DL));
15188 }
15189 
15190 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
15191 /// This allows for fast cases such as subvector extraction/insertion
15192 /// or shuffling smaller vector types which can lower more efficiently.
lowerShuffleWithUndefHalf(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15193 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
15194                                          SDValue V2, ArrayRef<int> Mask,
15195                                          const X86Subtarget &Subtarget,
15196                                          SelectionDAG &DAG) {
15197   assert((VT.is256BitVector() || VT.is512BitVector()) &&
15198          "Expected 256-bit or 512-bit vector");
15199 
15200   bool UndefLower = isUndefLowerHalf(Mask);
15201   if (!UndefLower && !isUndefUpperHalf(Mask))
15202     return SDValue();
15203 
15204   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
15205          "Completely undef shuffle mask should have been simplified already");
15206 
15207   // Upper half is undef and lower half is whole upper subvector.
15208   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15209   MVT HalfVT = VT.getHalfNumVectorElementsVT();
15210   unsigned HalfNumElts = HalfVT.getVectorNumElements();
15211   if (!UndefLower &&
15212       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
15213     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15214                              DAG.getIntPtrConstant(HalfNumElts, DL));
15215     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15216                        DAG.getIntPtrConstant(0, DL));
15217   }
15218 
15219   // Lower half is undef and upper half is whole lower subvector.
15220   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15221   if (UndefLower &&
15222       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
15223     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15224                              DAG.getIntPtrConstant(0, DL));
15225     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15226                        DAG.getIntPtrConstant(HalfNumElts, DL));
15227   }
15228 
15229   int HalfIdx1, HalfIdx2;
15230   SmallVector<int, 8> HalfMask(HalfNumElts);
15231   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
15232     return SDValue();
15233 
15234   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
15235 
15236   // Only shuffle the halves of the inputs when useful.
15237   unsigned NumLowerHalves =
15238       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
15239   unsigned NumUpperHalves =
15240       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
15241   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
15242 
15243   // Determine the larger pattern of undef/halves, then decide if it's worth
15244   // splitting the shuffle based on subtarget capabilities and types.
15245   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
15246   if (!UndefLower) {
15247     // XXXXuuuu: no insert is needed.
15248     // Always extract lowers when setting lower - these are all free subreg ops.
15249     if (NumUpperHalves == 0)
15250       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15251                                    UndefLower, DAG);
15252 
15253     if (NumUpperHalves == 1) {
15254       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
15255       if (Subtarget.hasAVX2()) {
15256         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
15257         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
15258             !is128BitUnpackShuffleMask(HalfMask, DAG) &&
15259             (!isSingleSHUFPSMask(HalfMask) ||
15260              Subtarget.hasFastVariableCrossLaneShuffle()))
15261           return SDValue();
15262         // If this is a unary shuffle (assume that the 2nd operand is
15263         // canonicalized to undef), then we can use vpermpd. Otherwise, we
15264         // are better off extracting the upper half of 1 operand and using a
15265         // narrow shuffle.
15266         if (EltWidth == 64 && V2.isUndef())
15267           return SDValue();
15268       }
15269       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15270       if (Subtarget.hasAVX512() && VT.is512BitVector())
15271         return SDValue();
15272       // Extract + narrow shuffle is better than the wide alternative.
15273       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15274                                    UndefLower, DAG);
15275     }
15276 
15277     // Don't extract both uppers, instead shuffle and then extract.
15278     assert(NumUpperHalves == 2 && "Half vector count went wrong");
15279     return SDValue();
15280   }
15281 
15282   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
15283   if (NumUpperHalves == 0) {
15284     // AVX2 has efficient 64-bit element cross-lane shuffles.
15285     // TODO: Refine to account for unary shuffle, splat, and other masks?
15286     if (Subtarget.hasAVX2() && EltWidth == 64)
15287       return SDValue();
15288     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15289     if (Subtarget.hasAVX512() && VT.is512BitVector())
15290       return SDValue();
15291     // Narrow shuffle + insert is better than the wide alternative.
15292     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15293                                  UndefLower, DAG);
15294   }
15295 
15296   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
15297   return SDValue();
15298 }
15299 
15300 /// Handle case where shuffle sources are coming from the same 128-bit lane and
15301 /// every lane can be represented as the same repeating mask - allowing us to
15302 /// shuffle the sources with the repeating shuffle and then permute the result
15303 /// to the destination lanes.
lowerShuffleAsRepeatedMaskAndLanePermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15304 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
15305     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15306     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15307   int NumElts = VT.getVectorNumElements();
15308   int NumLanes = VT.getSizeInBits() / 128;
15309   int NumLaneElts = NumElts / NumLanes;
15310 
15311   // On AVX2 we may be able to just shuffle the lowest elements and then
15312   // broadcast the result.
15313   if (Subtarget.hasAVX2()) {
15314     for (unsigned BroadcastSize : {16, 32, 64}) {
15315       if (BroadcastSize <= VT.getScalarSizeInBits())
15316         continue;
15317       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
15318 
15319       // Attempt to match a repeating pattern every NumBroadcastElts,
15320       // accounting for UNDEFs but only references the lowest 128-bit
15321       // lane of the inputs.
15322       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
15323         for (int i = 0; i != NumElts; i += NumBroadcastElts)
15324           for (int j = 0; j != NumBroadcastElts; ++j) {
15325             int M = Mask[i + j];
15326             if (M < 0)
15327               continue;
15328             int &R = RepeatMask[j];
15329             if (0 != ((M % NumElts) / NumLaneElts))
15330               return false;
15331             if (0 <= R && R != M)
15332               return false;
15333             R = M;
15334           }
15335         return true;
15336       };
15337 
15338       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
15339       if (!FindRepeatingBroadcastMask(RepeatMask))
15340         continue;
15341 
15342       // Shuffle the (lowest) repeated elements in place for broadcast.
15343       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
15344 
15345       // Shuffle the actual broadcast.
15346       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
15347       for (int i = 0; i != NumElts; i += NumBroadcastElts)
15348         for (int j = 0; j != NumBroadcastElts; ++j)
15349           BroadcastMask[i + j] = j;
15350 
15351       // Avoid returning the same shuffle operation. For example,
15352       // v8i32 = vector_shuffle<0,1,0,1,0,1,0,1> t5, undef:v8i32
15353       if (BroadcastMask == Mask)
15354         return SDValue();
15355 
15356       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
15357                                   BroadcastMask);
15358     }
15359   }
15360 
15361   // Bail if the shuffle mask doesn't cross 128-bit lanes.
15362   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
15363     return SDValue();
15364 
15365   // Bail if we already have a repeated lane shuffle mask.
15366   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
15367     return SDValue();
15368 
15369   // Helper to look for repeated mask in each split sublane, and that those
15370   // sublanes can then be permuted into place.
15371   auto ShuffleSubLanes = [&](int SubLaneScale) {
15372     int NumSubLanes = NumLanes * SubLaneScale;
15373     int NumSubLaneElts = NumLaneElts / SubLaneScale;
15374 
15375     // Check that all the sources are coming from the same lane and see if we
15376     // can form a repeating shuffle mask (local to each sub-lane). At the same
15377     // time, determine the source sub-lane for each destination sub-lane.
15378     int TopSrcSubLane = -1;
15379     SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
15380     SmallVector<SmallVector<int, 8>> RepeatedSubLaneMasks(
15381         SubLaneScale,
15382         SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef));
15383 
15384     for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
15385       // Extract the sub-lane mask, check that it all comes from the same lane
15386       // and normalize the mask entries to come from the first lane.
15387       int SrcLane = -1;
15388       SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
15389       for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15390         int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
15391         if (M < 0)
15392           continue;
15393         int Lane = (M % NumElts) / NumLaneElts;
15394         if ((0 <= SrcLane) && (SrcLane != Lane))
15395           return SDValue();
15396         SrcLane = Lane;
15397         int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
15398         SubLaneMask[Elt] = LocalM;
15399       }
15400 
15401       // Whole sub-lane is UNDEF.
15402       if (SrcLane < 0)
15403         continue;
15404 
15405       // Attempt to match against the candidate repeated sub-lane masks.
15406       for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
15407         auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
15408           for (int i = 0; i != NumSubLaneElts; ++i) {
15409             if (M1[i] < 0 || M2[i] < 0)
15410               continue;
15411             if (M1[i] != M2[i])
15412               return false;
15413           }
15414           return true;
15415         };
15416 
15417         auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
15418         if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
15419           continue;
15420 
15421         // Merge the sub-lane mask into the matching repeated sub-lane mask.
15422         for (int i = 0; i != NumSubLaneElts; ++i) {
15423           int M = SubLaneMask[i];
15424           if (M < 0)
15425             continue;
15426           assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
15427                  "Unexpected mask element");
15428           RepeatedSubLaneMask[i] = M;
15429         }
15430 
15431         // Track the top most source sub-lane - by setting the remaining to
15432         // UNDEF we can greatly simplify shuffle matching.
15433         int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
15434         TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
15435         Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
15436         break;
15437       }
15438 
15439       // Bail if we failed to find a matching repeated sub-lane mask.
15440       if (Dst2SrcSubLanes[DstSubLane] < 0)
15441         return SDValue();
15442     }
15443     assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
15444            "Unexpected source lane");
15445 
15446     // Create a repeating shuffle mask for the entire vector.
15447     SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
15448     for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
15449       int Lane = SubLane / SubLaneScale;
15450       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
15451       for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15452         int M = RepeatedSubLaneMask[Elt];
15453         if (M < 0)
15454           continue;
15455         int Idx = (SubLane * NumSubLaneElts) + Elt;
15456         RepeatedMask[Idx] = M + (Lane * NumLaneElts);
15457       }
15458     }
15459 
15460     // Shuffle each source sub-lane to its destination.
15461     SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
15462     for (int i = 0; i != NumElts; i += NumSubLaneElts) {
15463       int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
15464       if (SrcSubLane < 0)
15465         continue;
15466       for (int j = 0; j != NumSubLaneElts; ++j)
15467         SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
15468     }
15469 
15470     // Avoid returning the same shuffle operation.
15471     // v8i32 = vector_shuffle<0,1,4,5,2,3,6,7> t5, undef:v8i32
15472     if (RepeatedMask == Mask || SubLaneMask == Mask)
15473       return SDValue();
15474 
15475     SDValue RepeatedShuffle =
15476         DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
15477 
15478     return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
15479                                 SubLaneMask);
15480   };
15481 
15482   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
15483   // (with PERMQ/PERMPD). On AVX2/AVX512BW targets, permuting 32-bit sub-lanes,
15484   // even with a variable shuffle, can be worth it for v32i8/v64i8 vectors.
15485   // Otherwise we can only permute whole 128-bit lanes.
15486   int MinSubLaneScale = 1, MaxSubLaneScale = 1;
15487   if (Subtarget.hasAVX2() && VT.is256BitVector()) {
15488     bool OnlyLowestElts = isUndefOrInRange(Mask, 0, NumLaneElts);
15489     MinSubLaneScale = 2;
15490     MaxSubLaneScale =
15491         (!OnlyLowestElts && V2.isUndef() && VT == MVT::v32i8) ? 4 : 2;
15492   }
15493   if (Subtarget.hasBWI() && VT == MVT::v64i8)
15494     MinSubLaneScale = MaxSubLaneScale = 4;
15495 
15496   for (int Scale = MinSubLaneScale; Scale <= MaxSubLaneScale; Scale *= 2)
15497     if (SDValue Shuffle = ShuffleSubLanes(Scale))
15498       return Shuffle;
15499 
15500   return SDValue();
15501 }
15502 
matchShuffleWithSHUFPD(MVT VT,SDValue & V1,SDValue & V2,bool & ForceV1Zero,bool & ForceV2Zero,unsigned & ShuffleImm,ArrayRef<int> Mask,const APInt & Zeroable)15503 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
15504                                    bool &ForceV1Zero, bool &ForceV2Zero,
15505                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
15506                                    const APInt &Zeroable) {
15507   int NumElts = VT.getVectorNumElements();
15508   assert(VT.getScalarSizeInBits() == 64 &&
15509          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
15510          "Unexpected data type for VSHUFPD");
15511   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
15512          "Illegal shuffle mask");
15513 
15514   bool ZeroLane[2] = { true, true };
15515   for (int i = 0; i < NumElts; ++i)
15516     ZeroLane[i & 1] &= Zeroable[i];
15517 
15518   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
15519   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
15520   ShuffleImm = 0;
15521   bool ShufpdMask = true;
15522   bool CommutableMask = true;
15523   for (int i = 0; i < NumElts; ++i) {
15524     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
15525       continue;
15526     if (Mask[i] < 0)
15527       return false;
15528     int Val = (i & 6) + NumElts * (i & 1);
15529     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
15530     if (Mask[i] < Val || Mask[i] > Val + 1)
15531       ShufpdMask = false;
15532     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
15533       CommutableMask = false;
15534     ShuffleImm |= (Mask[i] % 2) << i;
15535   }
15536 
15537   if (!ShufpdMask && !CommutableMask)
15538     return false;
15539 
15540   if (!ShufpdMask && CommutableMask)
15541     std::swap(V1, V2);
15542 
15543   ForceV1Zero = ZeroLane[0];
15544   ForceV2Zero = ZeroLane[1];
15545   return true;
15546 }
15547 
lowerShuffleWithSHUFPD(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)15548 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
15549                                       SDValue V2, ArrayRef<int> Mask,
15550                                       const APInt &Zeroable,
15551                                       const X86Subtarget &Subtarget,
15552                                       SelectionDAG &DAG) {
15553   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
15554          "Unexpected data type for VSHUFPD");
15555 
15556   unsigned Immediate = 0;
15557   bool ForceV1Zero = false, ForceV2Zero = false;
15558   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
15559                               Mask, Zeroable))
15560     return SDValue();
15561 
15562   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
15563   if (ForceV1Zero)
15564     V1 = getZeroVector(VT, Subtarget, DAG, DL);
15565   if (ForceV2Zero)
15566     V2 = getZeroVector(VT, Subtarget, DAG, DL);
15567 
15568   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
15569                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
15570 }
15571 
15572 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
15573 // by zeroable elements in the remaining 24 elements. Turn this into two
15574 // vmovqb instructions shuffled together.
lowerShuffleAsVTRUNCAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)15575 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
15576                                              SDValue V1, SDValue V2,
15577                                              ArrayRef<int> Mask,
15578                                              const APInt &Zeroable,
15579                                              SelectionDAG &DAG) {
15580   assert(VT == MVT::v32i8 && "Unexpected type!");
15581 
15582   // The first 8 indices should be every 8th element.
15583   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
15584     return SDValue();
15585 
15586   // Remaining elements need to be zeroable.
15587   if (Zeroable.countl_one() < (Mask.size() - 8))
15588     return SDValue();
15589 
15590   V1 = DAG.getBitcast(MVT::v4i64, V1);
15591   V2 = DAG.getBitcast(MVT::v4i64, V2);
15592 
15593   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
15594   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
15595 
15596   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
15597   // the upper bits of the result using an unpckldq.
15598   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
15599                                         { 0, 1, 2, 3, 16, 17, 18, 19,
15600                                           4, 5, 6, 7, 20, 21, 22, 23 });
15601   // Insert the unpckldq into a zero vector to widen to v32i8.
15602   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
15603                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
15604                      DAG.getIntPtrConstant(0, DL));
15605 }
15606 
15607 // a = shuffle v1, v2, mask1    ; interleaving lower lanes of v1 and v2
15608 // b = shuffle v1, v2, mask2    ; interleaving higher lanes of v1 and v2
15609 //     =>
15610 // ul = unpckl v1, v2
15611 // uh = unpckh v1, v2
15612 // a = vperm ul, uh
15613 // b = vperm ul, uh
15614 //
15615 // Pattern-match interleave(256b v1, 256b v2) -> 512b v3 and lower it into unpck
15616 // and permute. We cannot directly match v3 because it is split into two
15617 // 256-bit vectors in earlier isel stages. Therefore, this function matches a
15618 // pair of 256-bit shuffles and makes sure the masks are consecutive.
15619 //
15620 // Once unpck and permute nodes are created, the permute corresponding to this
15621 // shuffle is returned, while the other permute replaces the other half of the
15622 // shuffle in the selection dag.
lowerShufflePairAsUNPCKAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)15623 static SDValue lowerShufflePairAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
15624                                                  SDValue V1, SDValue V2,
15625                                                  ArrayRef<int> Mask,
15626                                                  SelectionDAG &DAG) {
15627   if (VT != MVT::v8f32 && VT != MVT::v8i32 && VT != MVT::v16i16 &&
15628       VT != MVT::v32i8)
15629     return SDValue();
15630   // <B0, B1, B0+1, B1+1, ..., >
15631   auto IsInterleavingPattern = [&](ArrayRef<int> Mask, unsigned Begin0,
15632                                    unsigned Begin1) {
15633     size_t Size = Mask.size();
15634     assert(Size % 2 == 0 && "Expected even mask size");
15635     for (unsigned I = 0; I < Size; I += 2) {
15636       if (Mask[I] != (int)(Begin0 + I / 2) ||
15637           Mask[I + 1] != (int)(Begin1 + I / 2))
15638         return false;
15639     }
15640     return true;
15641   };
15642   // Check which half is this shuffle node
15643   int NumElts = VT.getVectorNumElements();
15644   size_t FirstQtr = NumElts / 2;
15645   size_t ThirdQtr = NumElts + NumElts / 2;
15646   bool IsFirstHalf = IsInterleavingPattern(Mask, 0, NumElts);
15647   bool IsSecondHalf = IsInterleavingPattern(Mask, FirstQtr, ThirdQtr);
15648   if (!IsFirstHalf && !IsSecondHalf)
15649     return SDValue();
15650 
15651   // Find the intersection between shuffle users of V1 and V2.
15652   SmallVector<SDNode *, 2> Shuffles;
15653   for (SDNode *User : V1->uses())
15654     if (User->getOpcode() == ISD::VECTOR_SHUFFLE && User->getOperand(0) == V1 &&
15655         User->getOperand(1) == V2)
15656       Shuffles.push_back(User);
15657   // Limit user size to two for now.
15658   if (Shuffles.size() != 2)
15659     return SDValue();
15660   // Find out which half of the 512-bit shuffles is each smaller shuffle
15661   auto *SVN1 = cast<ShuffleVectorSDNode>(Shuffles[0]);
15662   auto *SVN2 = cast<ShuffleVectorSDNode>(Shuffles[1]);
15663   SDNode *FirstHalf;
15664   SDNode *SecondHalf;
15665   if (IsInterleavingPattern(SVN1->getMask(), 0, NumElts) &&
15666       IsInterleavingPattern(SVN2->getMask(), FirstQtr, ThirdQtr)) {
15667     FirstHalf = Shuffles[0];
15668     SecondHalf = Shuffles[1];
15669   } else if (IsInterleavingPattern(SVN1->getMask(), FirstQtr, ThirdQtr) &&
15670              IsInterleavingPattern(SVN2->getMask(), 0, NumElts)) {
15671     FirstHalf = Shuffles[1];
15672     SecondHalf = Shuffles[0];
15673   } else {
15674     return SDValue();
15675   }
15676   // Lower into unpck and perm. Return the perm of this shuffle and replace
15677   // the other.
15678   SDValue Unpckl = DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
15679   SDValue Unpckh = DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
15680   SDValue Perm1 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
15681                               DAG.getTargetConstant(0x20, DL, MVT::i8));
15682   SDValue Perm2 = DAG.getNode(X86ISD::VPERM2X128, DL, VT, Unpckl, Unpckh,
15683                               DAG.getTargetConstant(0x31, DL, MVT::i8));
15684   if (IsFirstHalf) {
15685     DAG.ReplaceAllUsesWith(SecondHalf, &Perm2);
15686     return Perm1;
15687   }
15688   DAG.ReplaceAllUsesWith(FirstHalf, &Perm1);
15689   return Perm2;
15690 }
15691 
15692 /// Handle lowering of 4-lane 64-bit floating point shuffles.
15693 ///
15694 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
15695 /// isn't available.
lowerV4F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15696 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15697                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15698                                  const X86Subtarget &Subtarget,
15699                                  SelectionDAG &DAG) {
15700   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
15701   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
15702   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15703 
15704   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
15705                                      Subtarget, DAG))
15706     return V;
15707 
15708   if (V2.isUndef()) {
15709     // Check for being able to broadcast a single element.
15710     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
15711                                                     Mask, Subtarget, DAG))
15712       return Broadcast;
15713 
15714     // Use low duplicate instructions for masks that match their pattern.
15715     if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
15716       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
15717 
15718     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
15719       // Non-half-crossing single input shuffles can be lowered with an
15720       // interleaved permutation.
15721       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
15722                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
15723       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
15724                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
15725     }
15726 
15727     // With AVX2 we have direct support for this permutation.
15728     if (Subtarget.hasAVX2())
15729       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
15730                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15731 
15732     // Try to create an in-lane repeating shuffle mask and then shuffle the
15733     // results into the target lanes.
15734     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15735             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15736       return V;
15737 
15738     // Try to permute the lanes and then use a per-lane permute.
15739     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
15740                                                         Mask, DAG, Subtarget))
15741       return V;
15742 
15743     // Otherwise, fall back.
15744     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
15745                                                DAG, Subtarget);
15746   }
15747 
15748   // Use dedicated unpack instructions for masks that match their pattern.
15749   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
15750     return V;
15751 
15752   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
15753                                           Zeroable, Subtarget, DAG))
15754     return Blend;
15755 
15756   // Check if the blend happens to exactly fit that of SHUFPD.
15757   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
15758                                           Zeroable, Subtarget, DAG))
15759     return Op;
15760 
15761   bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
15762   bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
15763 
15764   // If we have lane crossing shuffles AND they don't all come from the lower
15765   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15766   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
15767   // canonicalize to a blend of splat which isn't necessary for this combine.
15768   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
15769       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
15770       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
15771       (V2.getOpcode() != ISD::BUILD_VECTOR))
15772     return lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2, Mask, DAG);
15773 
15774   // If we have one input in place, then we can permute the other input and
15775   // blend the result.
15776   if (V1IsInPlace || V2IsInPlace)
15777     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
15778                                                 Subtarget, DAG);
15779 
15780   // Try to create an in-lane repeating shuffle mask and then shuffle the
15781   // results into the target lanes.
15782   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15783           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15784     return V;
15785 
15786   // Try to simplify this by merging 128-bit lanes to enable a lane-based
15787   // shuffle. However, if we have AVX2 and either inputs are already in place,
15788   // we will be able to shuffle even across lanes the other input in a single
15789   // instruction so skip this pattern.
15790   if (!(Subtarget.hasAVX2() && (V1IsInPlace || V2IsInPlace)))
15791     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
15792             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15793       return V;
15794 
15795   // If we have VLX support, we can use VEXPAND.
15796   if (Subtarget.hasVLX())
15797     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
15798                                          DAG, Subtarget))
15799       return V;
15800 
15801   // If we have AVX2 then we always want to lower with a blend because an v4 we
15802   // can fully permute the elements.
15803   if (Subtarget.hasAVX2())
15804     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
15805                                                 Subtarget, DAG);
15806 
15807   // Otherwise fall back on generic lowering.
15808   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
15809                                     Subtarget, DAG);
15810 }
15811 
15812 /// Handle lowering of 4-lane 64-bit integer shuffles.
15813 ///
15814 /// This routine is only called when we have AVX2 and thus a reasonable
15815 /// instruction set for v4i64 shuffling..
lowerV4I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15816 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15817                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15818                                  const X86Subtarget &Subtarget,
15819                                  SelectionDAG &DAG) {
15820   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
15821   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
15822   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
15823   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
15824 
15825   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
15826                                      Subtarget, DAG))
15827     return V;
15828 
15829   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
15830                                           Zeroable, Subtarget, DAG))
15831     return Blend;
15832 
15833   // Check for being able to broadcast a single element.
15834   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
15835                                                   Subtarget, DAG))
15836     return Broadcast;
15837 
15838   // Try to use shift instructions if fast.
15839   if (Subtarget.preferLowerShuffleAsShift())
15840     if (SDValue Shift =
15841             lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
15842                                 Subtarget, DAG, /*BitwiseOnly*/ true))
15843       return Shift;
15844 
15845   if (V2.isUndef()) {
15846     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
15847     // can use lower latency instructions that will operate on both lanes.
15848     SmallVector<int, 2> RepeatedMask;
15849     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
15850       SmallVector<int, 4> PSHUFDMask;
15851       narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
15852       return DAG.getBitcast(
15853           MVT::v4i64,
15854           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
15855                       DAG.getBitcast(MVT::v8i32, V1),
15856                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15857     }
15858 
15859     // AVX2 provides a direct instruction for permuting a single input across
15860     // lanes.
15861     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
15862                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15863   }
15864 
15865   // Try to use shift instructions.
15866   if (SDValue Shift =
15867           lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, Zeroable, Subtarget,
15868                               DAG, /*BitwiseOnly*/ false))
15869     return Shift;
15870 
15871   // If we have VLX support, we can use VALIGN or VEXPAND.
15872   if (Subtarget.hasVLX()) {
15873     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
15874                                               Zeroable, Subtarget, DAG))
15875       return Rotate;
15876 
15877     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
15878                                          DAG, Subtarget))
15879       return V;
15880   }
15881 
15882   // Try to use PALIGNR.
15883   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
15884                                                 Subtarget, DAG))
15885     return Rotate;
15886 
15887   // Use dedicated unpack instructions for masks that match their pattern.
15888   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
15889     return V;
15890 
15891   bool V1IsInPlace = isShuffleMaskInputInPlace(0, Mask);
15892   bool V2IsInPlace = isShuffleMaskInputInPlace(1, Mask);
15893 
15894   // If we have one input in place, then we can permute the other input and
15895   // blend the result.
15896   if (V1IsInPlace || V2IsInPlace)
15897     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
15898                                                 Subtarget, DAG);
15899 
15900   // Try to create an in-lane repeating shuffle mask and then shuffle the
15901   // results into the target lanes.
15902   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15903           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
15904     return V;
15905 
15906   // Try to lower to PERMQ(BLENDD(V1,V2)).
15907   if (SDValue V =
15908           lowerShuffleAsBlendAndPermute(DL, MVT::v4i64, V1, V2, Mask, DAG))
15909     return V;
15910 
15911   // Try to simplify this by merging 128-bit lanes to enable a lane-based
15912   // shuffle. However, if we have AVX2 and either inputs are already in place,
15913   // we will be able to shuffle even across lanes the other input in a single
15914   // instruction so skip this pattern.
15915   if (!V1IsInPlace && !V2IsInPlace)
15916     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
15917             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
15918       return Result;
15919 
15920   // Otherwise fall back on generic blend lowering.
15921   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
15922                                               Subtarget, DAG);
15923 }
15924 
15925 /// Handle lowering of 8-lane 32-bit floating point shuffles.
15926 ///
15927 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
15928 /// isn't available.
lowerV8F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)15929 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15930                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15931                                  const X86Subtarget &Subtarget,
15932                                  SelectionDAG &DAG) {
15933   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
15934   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
15935   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15936 
15937   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
15938                                           Zeroable, Subtarget, DAG))
15939     return Blend;
15940 
15941   // Check for being able to broadcast a single element.
15942   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
15943                                                   Subtarget, DAG))
15944     return Broadcast;
15945 
15946   if (!Subtarget.hasAVX2()) {
15947     SmallVector<int> InLaneMask;
15948     computeInLaneShuffleMask(Mask, Mask.size() / 2, InLaneMask);
15949 
15950     if (!is128BitLaneRepeatedShuffleMask(MVT::v8f32, InLaneMask))
15951       if (SDValue R = splitAndLowerShuffle(DL, MVT::v8f32, V1, V2, Mask, DAG,
15952                                            /*SimpleOnly*/ true))
15953         return R;
15954   }
15955   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
15956                                                    Zeroable, Subtarget, DAG))
15957     return DAG.getBitcast(MVT::v8f32, ZExt);
15958 
15959   // If the shuffle mask is repeated in each 128-bit lane, we have many more
15960   // options to efficiently lower the shuffle.
15961   SmallVector<int, 4> RepeatedMask;
15962   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
15963     assert(RepeatedMask.size() == 4 &&
15964            "Repeated masks must be half the mask width!");
15965 
15966     // Use even/odd duplicate instructions for masks that match their pattern.
15967     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
15968       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
15969     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
15970       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
15971 
15972     if (V2.isUndef())
15973       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
15974                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15975 
15976     // Use dedicated unpack instructions for masks that match their pattern.
15977     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
15978       return V;
15979 
15980     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
15981     // have already handled any direct blends.
15982     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
15983   }
15984 
15985   // Try to create an in-lane repeating shuffle mask and then shuffle the
15986   // results into the target lanes.
15987   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15988           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
15989     return V;
15990 
15991   // If we have a single input shuffle with different shuffle patterns in the
15992   // two 128-bit lanes use the variable mask to VPERMILPS.
15993   if (V2.isUndef()) {
15994     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
15995       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
15996       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
15997     }
15998     if (Subtarget.hasAVX2()) {
15999       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16000       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
16001     }
16002     // Otherwise, fall back.
16003     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
16004                                                DAG, Subtarget);
16005   }
16006 
16007   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16008   // shuffle.
16009   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16010           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16011     return Result;
16012 
16013   // If we have VLX support, we can use VEXPAND.
16014   if (Subtarget.hasVLX())
16015     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
16016                                          DAG, Subtarget))
16017       return V;
16018 
16019   // Try to match an interleave of two v8f32s and lower them as unpck and
16020   // permutes using ymms. This needs to go before we try to split the vectors.
16021   //
16022   // TODO: Expand this to AVX1. Currently v8i32 is casted to v8f32 and hits
16023   // this path inadvertently.
16024   if (Subtarget.hasAVX2() && !Subtarget.hasAVX512())
16025     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8f32, V1, V2,
16026                                                       Mask, DAG))
16027       return V;
16028 
16029   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16030   // since after split we get a more efficient code using vpunpcklwd and
16031   // vpunpckhwd instrs than vblend.
16032   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32, DAG))
16033     return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Subtarget,
16034                                       DAG);
16035 
16036   // If we have AVX2 then we always want to lower with a blend because at v8 we
16037   // can fully permute the elements.
16038   if (Subtarget.hasAVX2())
16039     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
16040                                                 Subtarget, DAG);
16041 
16042   // Otherwise fall back on generic lowering.
16043   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
16044                                     Subtarget, DAG);
16045 }
16046 
16047 /// Handle lowering of 8-lane 32-bit integer shuffles.
16048 ///
16049 /// This routine is only called when we have AVX2 and thus a reasonable
16050 /// instruction set for v8i32 shuffling..
lowerV8I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16051 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16052                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16053                                  const X86Subtarget &Subtarget,
16054                                  SelectionDAG &DAG) {
16055   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16056   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16057   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16058   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
16059 
16060   int NumV2Elements = count_if(Mask, [](int M) { return M >= 8; });
16061 
16062   // Whenever we can lower this as a zext, that instruction is strictly faster
16063   // than any alternative. It also allows us to fold memory operands into the
16064   // shuffle in many cases.
16065   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
16066                                                    Zeroable, Subtarget, DAG))
16067     return ZExt;
16068 
16069   // Try to match an interleave of two v8i32s and lower them as unpck and
16070   // permutes using ymms. This needs to go before we try to split the vectors.
16071   if (!Subtarget.hasAVX512())
16072     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v8i32, V1, V2,
16073                                                       Mask, DAG))
16074       return V;
16075 
16076   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16077   // since after split we get a more efficient code than vblend by using
16078   // vpunpcklwd and vpunpckhwd instrs.
16079   if (isUnpackWdShuffleMask(Mask, MVT::v8i32, DAG) && !V2.isUndef() &&
16080       !Subtarget.hasAVX512())
16081     return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Subtarget,
16082                                       DAG);
16083 
16084   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
16085                                           Zeroable, Subtarget, DAG))
16086     return Blend;
16087 
16088   // Check for being able to broadcast a single element.
16089   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
16090                                                   Subtarget, DAG))
16091     return Broadcast;
16092 
16093   // Try to use shift instructions if fast.
16094   if (Subtarget.preferLowerShuffleAsShift()) {
16095     if (SDValue Shift =
16096             lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable,
16097                                 Subtarget, DAG, /*BitwiseOnly*/ true))
16098       return Shift;
16099     if (NumV2Elements == 0)
16100       if (SDValue Rotate =
16101               lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
16102         return Rotate;
16103   }
16104 
16105   // If the shuffle mask is repeated in each 128-bit lane we can use more
16106   // efficient instructions that mirror the shuffles across the two 128-bit
16107   // lanes.
16108   SmallVector<int, 4> RepeatedMask;
16109   bool Is128BitLaneRepeatedShuffle =
16110       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
16111   if (Is128BitLaneRepeatedShuffle) {
16112     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16113     if (V2.isUndef())
16114       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
16115                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16116 
16117     // Use dedicated unpack instructions for masks that match their pattern.
16118     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
16119       return V;
16120   }
16121 
16122   // Try to use shift instructions.
16123   if (SDValue Shift =
16124           lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, Zeroable, Subtarget,
16125                               DAG, /*BitwiseOnly*/ false))
16126     return Shift;
16127 
16128   if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements == 0)
16129     if (SDValue Rotate =
16130             lowerShuffleAsBitRotate(DL, MVT::v8i32, V1, Mask, Subtarget, DAG))
16131       return Rotate;
16132 
16133   // If we have VLX support, we can use VALIGN or EXPAND.
16134   if (Subtarget.hasVLX()) {
16135     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
16136                                               Zeroable, Subtarget, DAG))
16137       return Rotate;
16138 
16139     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
16140                                          DAG, Subtarget))
16141       return V;
16142   }
16143 
16144   // Try to use byte rotation instructions.
16145   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
16146                                                 Subtarget, DAG))
16147     return Rotate;
16148 
16149   // Try to create an in-lane repeating shuffle mask and then shuffle the
16150   // results into the target lanes.
16151   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16152           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16153     return V;
16154 
16155   if (V2.isUndef()) {
16156     // Try to produce a fixed cross-128-bit lane permute followed by unpack
16157     // because that should be faster than the variable permute alternatives.
16158     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
16159       return V;
16160 
16161     // If the shuffle patterns aren't repeated but it's a single input, directly
16162     // generate a cross-lane VPERMD instruction.
16163     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16164     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
16165   }
16166 
16167   // Assume that a single SHUFPS is faster than an alternative sequence of
16168   // multiple instructions (even if the CPU has a domain penalty).
16169   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16170   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16171     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
16172     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
16173     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
16174                                             CastV1, CastV2, DAG);
16175     return DAG.getBitcast(MVT::v8i32, ShufPS);
16176   }
16177 
16178   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16179   // shuffle.
16180   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16181           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16182     return Result;
16183 
16184   // Otherwise fall back on generic blend lowering.
16185   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
16186                                               Subtarget, DAG);
16187 }
16188 
16189 /// Handle lowering of 16-lane 16-bit integer shuffles.
16190 ///
16191 /// This routine is only called when we have AVX2 and thus a reasonable
16192 /// instruction set for v16i16 shuffling..
lowerV16I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16193 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16194                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16195                                   const X86Subtarget &Subtarget,
16196                                   SelectionDAG &DAG) {
16197   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16198   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16199   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16200   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
16201 
16202   // Whenever we can lower this as a zext, that instruction is strictly faster
16203   // than any alternative. It also allows us to fold memory operands into the
16204   // shuffle in many cases.
16205   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16206           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16207     return ZExt;
16208 
16209   // Check for being able to broadcast a single element.
16210   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
16211                                                   Subtarget, DAG))
16212     return Broadcast;
16213 
16214   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
16215                                           Zeroable, Subtarget, DAG))
16216     return Blend;
16217 
16218   // Use dedicated unpack instructions for masks that match their pattern.
16219   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
16220     return V;
16221 
16222   // Use dedicated pack instructions for masks that match their pattern.
16223   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
16224                                        Subtarget))
16225     return V;
16226 
16227   // Try to use lower using a truncation.
16228   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
16229                                        Subtarget, DAG))
16230     return V;
16231 
16232   // Try to use shift instructions.
16233   if (SDValue Shift =
16234           lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
16235                               Subtarget, DAG, /*BitwiseOnly*/ false))
16236     return Shift;
16237 
16238   // Try to use byte rotation instructions.
16239   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
16240                                                 Subtarget, DAG))
16241     return Rotate;
16242 
16243   // Try to create an in-lane repeating shuffle mask and then shuffle the
16244   // results into the target lanes.
16245   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16246           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16247     return V;
16248 
16249   if (V2.isUndef()) {
16250     // Try to use bit rotation instructions.
16251     if (SDValue Rotate =
16252             lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
16253       return Rotate;
16254 
16255     // Try to produce a fixed cross-128-bit lane permute followed by unpack
16256     // because that should be faster than the variable permute alternatives.
16257     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
16258       return V;
16259 
16260     // There are no generalized cross-lane shuffle operations available on i16
16261     // element types.
16262     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
16263       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16264               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16265         return V;
16266 
16267       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
16268                                                  DAG, Subtarget);
16269     }
16270 
16271     SmallVector<int, 8> RepeatedMask;
16272     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
16273       // As this is a single-input shuffle, the repeated mask should be
16274       // a strictly valid v8i16 mask that we can pass through to the v8i16
16275       // lowering to handle even the v16 case.
16276       return lowerV8I16GeneralSingleInputShuffle(
16277           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
16278     }
16279   }
16280 
16281   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
16282                                               Zeroable, Subtarget, DAG))
16283     return PSHUFB;
16284 
16285   // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
16286   if (Subtarget.hasBWI())
16287     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
16288 
16289   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16290   // shuffle.
16291   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16292           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16293     return Result;
16294 
16295   // Try to permute the lanes and then use a per-lane permute.
16296   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16297           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16298     return V;
16299 
16300   // Try to match an interleave of two v16i16s and lower them as unpck and
16301   // permutes using ymms.
16302   if (!Subtarget.hasAVX512())
16303     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v16i16, V1, V2,
16304                                                       Mask, DAG))
16305       return V;
16306 
16307   // Otherwise fall back on generic lowering.
16308   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
16309                                     Subtarget, DAG);
16310 }
16311 
16312 /// Handle lowering of 32-lane 8-bit integer shuffles.
16313 ///
16314 /// This routine is only called when we have AVX2 and thus a reasonable
16315 /// instruction set for v32i8 shuffling..
lowerV32I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16316 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16317                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16318                                  const X86Subtarget &Subtarget,
16319                                  SelectionDAG &DAG) {
16320   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16321   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16322   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
16323   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
16324 
16325   // Whenever we can lower this as a zext, that instruction is strictly faster
16326   // than any alternative. It also allows us to fold memory operands into the
16327   // shuffle in many cases.
16328   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
16329                                                    Zeroable, Subtarget, DAG))
16330     return ZExt;
16331 
16332   // Check for being able to broadcast a single element.
16333   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
16334                                                   Subtarget, DAG))
16335     return Broadcast;
16336 
16337   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
16338                                           Zeroable, Subtarget, DAG))
16339     return Blend;
16340 
16341   // Use dedicated unpack instructions for masks that match their pattern.
16342   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
16343     return V;
16344 
16345   // Use dedicated pack instructions for masks that match their pattern.
16346   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
16347                                        Subtarget))
16348     return V;
16349 
16350   // Try to use lower using a truncation.
16351   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
16352                                        Subtarget, DAG))
16353     return V;
16354 
16355   // Try to use shift instructions.
16356   if (SDValue Shift =
16357           lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, Zeroable, Subtarget,
16358                               DAG, /*BitwiseOnly*/ false))
16359     return Shift;
16360 
16361   // Try to use byte rotation instructions.
16362   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
16363                                                 Subtarget, DAG))
16364     return Rotate;
16365 
16366   // Try to use bit rotation instructions.
16367   if (V2.isUndef())
16368     if (SDValue Rotate =
16369             lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
16370       return Rotate;
16371 
16372   // Try to create an in-lane repeating shuffle mask and then shuffle the
16373   // results into the target lanes.
16374   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16375           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16376     return V;
16377 
16378   // There are no generalized cross-lane shuffle operations available on i8
16379   // element types.
16380   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
16381     // Try to produce a fixed cross-128-bit lane permute followed by unpack
16382     // because that should be faster than the variable permute alternatives.
16383     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
16384       return V;
16385 
16386     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16387             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16388       return V;
16389 
16390     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
16391                                                DAG, Subtarget);
16392   }
16393 
16394   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
16395                                               Zeroable, Subtarget, DAG))
16396     return PSHUFB;
16397 
16398   // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
16399   if (Subtarget.hasVBMI())
16400     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
16401 
16402   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16403   // shuffle.
16404   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16405           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16406     return Result;
16407 
16408   // Try to permute the lanes and then use a per-lane permute.
16409   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16410           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16411     return V;
16412 
16413   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16414   // by zeroable elements in the remaining 24 elements. Turn this into two
16415   // vmovqb instructions shuffled together.
16416   if (Subtarget.hasVLX())
16417     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
16418                                                   Mask, Zeroable, DAG))
16419       return V;
16420 
16421   // Try to match an interleave of two v32i8s and lower them as unpck and
16422   // permutes using ymms.
16423   if (!Subtarget.hasAVX512())
16424     if (SDValue V = lowerShufflePairAsUNPCKAndPermute(DL, MVT::v32i8, V1, V2,
16425                                                       Mask, DAG))
16426       return V;
16427 
16428   // Otherwise fall back on generic lowering.
16429   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
16430                                     Subtarget, DAG);
16431 }
16432 
16433 /// High-level routine to lower various 256-bit x86 vector shuffles.
16434 ///
16435 /// This routine either breaks down the specific type of a 256-bit x86 vector
16436 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
16437 /// together based on the available instructions.
lower256BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)16438 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
16439                                   SDValue V1, SDValue V2, const APInt &Zeroable,
16440                                   const X86Subtarget &Subtarget,
16441                                   SelectionDAG &DAG) {
16442   // If we have a single input to the zero element, insert that into V1 if we
16443   // can do so cheaply.
16444   int NumElts = VT.getVectorNumElements();
16445   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
16446 
16447   if (NumV2Elements == 1 && Mask[0] >= NumElts)
16448     if (SDValue Insertion = lowerShuffleAsElementInsertion(
16449             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
16450       return Insertion;
16451 
16452   // Handle special cases where the lower or upper half is UNDEF.
16453   if (SDValue V =
16454           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
16455     return V;
16456 
16457   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
16458   // can check for those subtargets here and avoid much of the subtarget
16459   // querying in the per-vector-type lowering routines. With AVX1 we have
16460   // essentially *zero* ability to manipulate a 256-bit vector with integer
16461   // types. Since we'll use floating point types there eventually, just
16462   // immediately cast everything to a float and operate entirely in that domain.
16463   if (VT.isInteger() && !Subtarget.hasAVX2()) {
16464     int ElementBits = VT.getScalarSizeInBits();
16465     if (ElementBits < 32) {
16466       // No floating point type available, if we can't use the bit operations
16467       // for masking/blending then decompose into 128-bit vectors.
16468       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
16469                                             Subtarget, DAG))
16470         return V;
16471       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
16472         return V;
16473       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
16474     }
16475 
16476     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
16477                                 VT.getVectorNumElements());
16478     V1 = DAG.getBitcast(FpVT, V1);
16479     V2 = DAG.getBitcast(FpVT, V2);
16480     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
16481   }
16482 
16483   if (VT == MVT::v16f16 || VT == MVT::v16bf16) {
16484     V1 = DAG.getBitcast(MVT::v16i16, V1);
16485     V2 = DAG.getBitcast(MVT::v16i16, V2);
16486     return DAG.getBitcast(VT,
16487                           DAG.getVectorShuffle(MVT::v16i16, DL, V1, V2, Mask));
16488   }
16489 
16490   switch (VT.SimpleTy) {
16491   case MVT::v4f64:
16492     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16493   case MVT::v4i64:
16494     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16495   case MVT::v8f32:
16496     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16497   case MVT::v8i32:
16498     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16499   case MVT::v16i16:
16500     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16501   case MVT::v32i8:
16502     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16503 
16504   default:
16505     llvm_unreachable("Not a valid 256-bit x86 vector type!");
16506   }
16507 }
16508 
16509 /// Try to lower a vector shuffle as a 128-bit shuffles.
lowerV4X128Shuffle(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16510 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
16511                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16512                                   const X86Subtarget &Subtarget,
16513                                   SelectionDAG &DAG) {
16514   assert(VT.getScalarSizeInBits() == 64 &&
16515          "Unexpected element type size for 128bit shuffle.");
16516 
16517   // To handle 256 bit vector requires VLX and most probably
16518   // function lowerV2X128VectorShuffle() is better solution.
16519   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
16520 
16521   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
16522   SmallVector<int, 4> Widened128Mask;
16523   if (!canWidenShuffleElements(Mask, Widened128Mask))
16524     return SDValue();
16525   assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
16526 
16527   // Try to use an insert into a zero vector.
16528   if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
16529       (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
16530     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
16531     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
16532     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
16533                               DAG.getIntPtrConstant(0, DL));
16534     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16535                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
16536                        DAG.getIntPtrConstant(0, DL));
16537   }
16538 
16539   // Check for patterns which can be matched with a single insert of a 256-bit
16540   // subvector.
16541   bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
16542   if (OnlyUsesV1 ||
16543       isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
16544     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
16545     SDValue SubVec =
16546         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
16547                     DAG.getIntPtrConstant(0, DL));
16548     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
16549                        DAG.getIntPtrConstant(4, DL));
16550   }
16551 
16552   // See if this is an insertion of the lower 128-bits of V2 into V1.
16553   bool IsInsert = true;
16554   int V2Index = -1;
16555   for (int i = 0; i < 4; ++i) {
16556     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
16557     if (Widened128Mask[i] < 0)
16558       continue;
16559 
16560     // Make sure all V1 subvectors are in place.
16561     if (Widened128Mask[i] < 4) {
16562       if (Widened128Mask[i] != i) {
16563         IsInsert = false;
16564         break;
16565       }
16566     } else {
16567       // Make sure we only have a single V2 index and its the lowest 128-bits.
16568       if (V2Index >= 0 || Widened128Mask[i] != 4) {
16569         IsInsert = false;
16570         break;
16571       }
16572       V2Index = i;
16573     }
16574   }
16575   if (IsInsert && V2Index >= 0) {
16576     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16577     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
16578                                  DAG.getIntPtrConstant(0, DL));
16579     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
16580   }
16581 
16582   // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
16583   // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
16584   // possible we at least ensure the lanes stay sequential to help later
16585   // combines.
16586   SmallVector<int, 2> Widened256Mask;
16587   if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
16588     Widened128Mask.clear();
16589     narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
16590   }
16591 
16592   // Try to lower to vshuf64x2/vshuf32x4.
16593   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
16594   int PermMask[4] = {-1, -1, -1, -1};
16595   // Ensure elements came from the same Op.
16596   for (int i = 0; i < 4; ++i) {
16597     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
16598     if (Widened128Mask[i] < 0)
16599       continue;
16600 
16601     SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
16602     unsigned OpIndex = i / 2;
16603     if (Ops[OpIndex].isUndef())
16604       Ops[OpIndex] = Op;
16605     else if (Ops[OpIndex] != Op)
16606       return SDValue();
16607 
16608     PermMask[i] = Widened128Mask[i] % 4;
16609   }
16610 
16611   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
16612                      getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
16613 }
16614 
16615 /// Handle lowering of 8-lane 64-bit floating point shuffles.
lowerV8F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16616 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16617                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16618                                  const X86Subtarget &Subtarget,
16619                                  SelectionDAG &DAG) {
16620   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
16621   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
16622   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16623 
16624   if (V2.isUndef()) {
16625     // Use low duplicate instructions for masks that match their pattern.
16626     if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
16627       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
16628 
16629     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
16630       // Non-half-crossing single input shuffles can be lowered with an
16631       // interleaved permutation.
16632       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16633                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
16634                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
16635                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
16636       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
16637                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16638     }
16639 
16640     SmallVector<int, 4> RepeatedMask;
16641     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
16642       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
16643                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16644   }
16645 
16646   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
16647                                            V2, Subtarget, DAG))
16648     return Shuf128;
16649 
16650   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
16651     return Unpck;
16652 
16653   // Check if the blend happens to exactly fit that of SHUFPD.
16654   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
16655                                           Zeroable, Subtarget, DAG))
16656     return Op;
16657 
16658   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
16659                                        DAG, Subtarget))
16660     return V;
16661 
16662   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
16663                                           Zeroable, Subtarget, DAG))
16664     return Blend;
16665 
16666   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
16667 }
16668 
16669 /// Handle lowering of 16-lane 32-bit floating point shuffles.
lowerV16F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16670 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16671                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16672                                   const X86Subtarget &Subtarget,
16673                                   SelectionDAG &DAG) {
16674   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
16675   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
16676   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16677 
16678   // If the shuffle mask is repeated in each 128-bit lane, we have many more
16679   // options to efficiently lower the shuffle.
16680   SmallVector<int, 4> RepeatedMask;
16681   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
16682     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16683 
16684     // Use even/odd duplicate instructions for masks that match their pattern.
16685     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
16686       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
16687     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
16688       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
16689 
16690     if (V2.isUndef())
16691       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
16692                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16693 
16694     // Use dedicated unpack instructions for masks that match their pattern.
16695     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
16696       return V;
16697 
16698     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
16699                                             Zeroable, Subtarget, DAG))
16700       return Blend;
16701 
16702     // Otherwise, fall back to a SHUFPS sequence.
16703     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
16704   }
16705 
16706   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
16707                                           Zeroable, Subtarget, DAG))
16708     return Blend;
16709 
16710   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16711           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
16712     return DAG.getBitcast(MVT::v16f32, ZExt);
16713 
16714   // Try to create an in-lane repeating shuffle mask and then shuffle the
16715   // results into the target lanes.
16716   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16717           DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
16718     return V;
16719 
16720   // If we have a single input shuffle with different shuffle patterns in the
16721   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
16722   if (V2.isUndef() &&
16723       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
16724     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
16725     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
16726   }
16727 
16728   // If we have AVX512F support, we can use VEXPAND.
16729   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
16730                                              V1, V2, DAG, Subtarget))
16731     return V;
16732 
16733   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
16734 }
16735 
16736 /// Handle lowering of 8-lane 64-bit integer shuffles.
lowerV8I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16737 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16738                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16739                                  const X86Subtarget &Subtarget,
16740                                  SelectionDAG &DAG) {
16741   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
16742   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
16743   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16744 
16745   // Try to use shift instructions if fast.
16746   if (Subtarget.preferLowerShuffleAsShift())
16747     if (SDValue Shift =
16748             lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable,
16749                                 Subtarget, DAG, /*BitwiseOnly*/ true))
16750       return Shift;
16751 
16752   if (V2.isUndef()) {
16753     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16754     // can use lower latency instructions that will operate on all four
16755     // 128-bit lanes.
16756     SmallVector<int, 2> Repeated128Mask;
16757     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
16758       SmallVector<int, 4> PSHUFDMask;
16759       narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
16760       return DAG.getBitcast(
16761           MVT::v8i64,
16762           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
16763                       DAG.getBitcast(MVT::v16i32, V1),
16764                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16765     }
16766 
16767     SmallVector<int, 4> Repeated256Mask;
16768     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
16769       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
16770                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
16771   }
16772 
16773   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
16774                                            V2, Subtarget, DAG))
16775     return Shuf128;
16776 
16777   // Try to use shift instructions.
16778   if (SDValue Shift =
16779           lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask, Zeroable, Subtarget,
16780                               DAG, /*BitwiseOnly*/ false))
16781     return Shift;
16782 
16783   // Try to use VALIGN.
16784   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
16785                                             Zeroable, Subtarget, DAG))
16786     return Rotate;
16787 
16788   // Try to use PALIGNR.
16789   if (Subtarget.hasBWI())
16790     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
16791                                                   Subtarget, DAG))
16792       return Rotate;
16793 
16794   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
16795     return Unpck;
16796 
16797   // If we have AVX512F support, we can use VEXPAND.
16798   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
16799                                        DAG, Subtarget))
16800     return V;
16801 
16802   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
16803                                           Zeroable, Subtarget, DAG))
16804     return Blend;
16805 
16806   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
16807 }
16808 
16809 /// Handle lowering of 16-lane 32-bit integer shuffles.
lowerV16I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16810 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16811                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16812                                   const X86Subtarget &Subtarget,
16813                                   SelectionDAG &DAG) {
16814   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
16815   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
16816   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16817 
16818   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
16819 
16820   // Whenever we can lower this as a zext, that instruction is strictly faster
16821   // than any alternative. It also allows us to fold memory operands into the
16822   // shuffle in many cases.
16823   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16824           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
16825     return ZExt;
16826 
16827   // Try to use shift instructions if fast.
16828   if (Subtarget.preferLowerShuffleAsShift()) {
16829     if (SDValue Shift =
16830             lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
16831                                 Subtarget, DAG, /*BitwiseOnly*/ true))
16832       return Shift;
16833     if (NumV2Elements == 0)
16834       if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask,
16835                                                    Subtarget, DAG))
16836         return Rotate;
16837   }
16838 
16839   // If the shuffle mask is repeated in each 128-bit lane we can use more
16840   // efficient instructions that mirror the shuffles across the four 128-bit
16841   // lanes.
16842   SmallVector<int, 4> RepeatedMask;
16843   bool Is128BitLaneRepeatedShuffle =
16844       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
16845   if (Is128BitLaneRepeatedShuffle) {
16846     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16847     if (V2.isUndef())
16848       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
16849                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16850 
16851     // Use dedicated unpack instructions for masks that match their pattern.
16852     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
16853       return V;
16854   }
16855 
16856   // Try to use shift instructions.
16857   if (SDValue Shift =
16858           lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask, Zeroable,
16859                               Subtarget, DAG, /*BitwiseOnly*/ false))
16860     return Shift;
16861 
16862   if (!Subtarget.preferLowerShuffleAsShift() && NumV2Elements != 0)
16863     if (SDValue Rotate =
16864             lowerShuffleAsBitRotate(DL, MVT::v16i32, V1, Mask, Subtarget, DAG))
16865       return Rotate;
16866 
16867   // Try to use VALIGN.
16868   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
16869                                             Zeroable, Subtarget, DAG))
16870     return Rotate;
16871 
16872   // Try to use byte rotation instructions.
16873   if (Subtarget.hasBWI())
16874     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
16875                                                   Subtarget, DAG))
16876       return Rotate;
16877 
16878   // Assume that a single SHUFPS is faster than using a permv shuffle.
16879   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16880   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16881     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
16882     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
16883     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
16884                                             CastV1, CastV2, DAG);
16885     return DAG.getBitcast(MVT::v16i32, ShufPS);
16886   }
16887 
16888   // Try to create an in-lane repeating shuffle mask and then shuffle the
16889   // results into the target lanes.
16890   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16891           DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
16892     return V;
16893 
16894   // If we have AVX512F support, we can use VEXPAND.
16895   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
16896                                        DAG, Subtarget))
16897     return V;
16898 
16899   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
16900                                           Zeroable, Subtarget, DAG))
16901     return Blend;
16902 
16903   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
16904 }
16905 
16906 /// Handle lowering of 32-lane 16-bit integer shuffles.
lowerV32I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16907 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16908                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16909                                   const X86Subtarget &Subtarget,
16910                                   SelectionDAG &DAG) {
16911   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
16912   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
16913   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
16914   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
16915 
16916   // Whenever we can lower this as a zext, that instruction is strictly faster
16917   // than any alternative. It also allows us to fold memory operands into the
16918   // shuffle in many cases.
16919   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16920           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16921     return ZExt;
16922 
16923   // Use dedicated unpack instructions for masks that match their pattern.
16924   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
16925     return V;
16926 
16927   // Use dedicated pack instructions for masks that match their pattern.
16928   if (SDValue V =
16929           lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
16930     return V;
16931 
16932   // Try to use shift instructions.
16933   if (SDValue Shift =
16934           lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask, Zeroable,
16935                               Subtarget, DAG, /*BitwiseOnly*/ false))
16936     return Shift;
16937 
16938   // Try to use byte rotation instructions.
16939   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
16940                                                 Subtarget, DAG))
16941     return Rotate;
16942 
16943   if (V2.isUndef()) {
16944     // Try to use bit rotation instructions.
16945     if (SDValue Rotate =
16946             lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
16947       return Rotate;
16948 
16949     SmallVector<int, 8> RepeatedMask;
16950     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
16951       // As this is a single-input shuffle, the repeated mask should be
16952       // a strictly valid v8i16 mask that we can pass through to the v8i16
16953       // lowering to handle even the v32 case.
16954       return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
16955                                                  RepeatedMask, Subtarget, DAG);
16956     }
16957   }
16958 
16959   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
16960                                           Zeroable, Subtarget, DAG))
16961     return Blend;
16962 
16963   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
16964                                               Zeroable, Subtarget, DAG))
16965     return PSHUFB;
16966 
16967   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
16968 }
16969 
16970 /// Handle lowering of 64-lane 8-bit integer shuffles.
lowerV64I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16971 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16972                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16973                                  const X86Subtarget &Subtarget,
16974                                  SelectionDAG &DAG) {
16975   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
16976   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
16977   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
16978   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
16979 
16980   // Whenever we can lower this as a zext, that instruction is strictly faster
16981   // than any alternative. It also allows us to fold memory operands into the
16982   // shuffle in many cases.
16983   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16984           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
16985     return ZExt;
16986 
16987   // Use dedicated unpack instructions for masks that match their pattern.
16988   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
16989     return V;
16990 
16991   // Use dedicated pack instructions for masks that match their pattern.
16992   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
16993                                        Subtarget))
16994     return V;
16995 
16996   // Try to use shift instructions.
16997   if (SDValue Shift =
16998           lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget,
16999                               DAG, /*BitwiseOnly*/ false))
17000     return Shift;
17001 
17002   // Try to use byte rotation instructions.
17003   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
17004                                                 Subtarget, DAG))
17005     return Rotate;
17006 
17007   // Try to use bit rotation instructions.
17008   if (V2.isUndef())
17009     if (SDValue Rotate =
17010             lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
17011       return Rotate;
17012 
17013   // Lower as AND if possible.
17014   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
17015                                              Zeroable, Subtarget, DAG))
17016     return Masked;
17017 
17018   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
17019                                               Zeroable, Subtarget, DAG))
17020     return PSHUFB;
17021 
17022   // Try to create an in-lane repeating shuffle mask and then shuffle the
17023   // results into the target lanes.
17024   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17025           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17026     return V;
17027 
17028   if (SDValue Result = lowerShuffleAsLanePermuteAndPermute(
17029           DL, MVT::v64i8, V1, V2, Mask, DAG, Subtarget))
17030     return Result;
17031 
17032   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
17033                                           Zeroable, Subtarget, DAG))
17034     return Blend;
17035 
17036   if (!is128BitLaneCrossingShuffleMask(MVT::v64i8, Mask)) {
17037     // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
17038     // PALIGNR will be cheaper than the second PSHUFB+OR.
17039     if (SDValue V = lowerShuffleAsByteRotateAndPermute(DL, MVT::v64i8, V1, V2,
17040                                                        Mask, Subtarget, DAG))
17041       return V;
17042 
17043     // If we can't directly blend but can use PSHUFB, that will be better as it
17044     // can both shuffle and set up the inefficient blend.
17045     bool V1InUse, V2InUse;
17046     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v64i8, V1, V2, Mask, Zeroable,
17047                                         DAG, V1InUse, V2InUse);
17048   }
17049 
17050   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17051   // shuffle.
17052   if (!V2.isUndef())
17053     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17054             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17055       return Result;
17056 
17057   // VBMI can use VPERMV/VPERMV3 byte shuffles.
17058   if (Subtarget.hasVBMI())
17059     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
17060 
17061   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17062 }
17063 
17064 /// High-level routine to lower various 512-bit x86 vector shuffles.
17065 ///
17066 /// This routine either breaks down the specific type of a 512-bit x86 vector
17067 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
17068 /// together based on the available instructions.
lower512BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)17069 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17070                                   MVT VT, SDValue V1, SDValue V2,
17071                                   const APInt &Zeroable,
17072                                   const X86Subtarget &Subtarget,
17073                                   SelectionDAG &DAG) {
17074   assert(Subtarget.hasAVX512() &&
17075          "Cannot lower 512-bit vectors w/ basic ISA!");
17076 
17077   // If we have a single input to the zero element, insert that into V1 if we
17078   // can do so cheaply.
17079   int NumElts = Mask.size();
17080   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17081 
17082   if (NumV2Elements == 1 && Mask[0] >= NumElts)
17083     if (SDValue Insertion = lowerShuffleAsElementInsertion(
17084             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17085       return Insertion;
17086 
17087   // Handle special cases where the lower or upper half is UNDEF.
17088   if (SDValue V =
17089           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17090     return V;
17091 
17092   // Check for being able to broadcast a single element.
17093   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
17094                                                   Subtarget, DAG))
17095     return Broadcast;
17096 
17097   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
17098     // Try using bit ops for masking and blending before falling back to
17099     // splitting.
17100     if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
17101                                           Subtarget, DAG))
17102       return V;
17103     if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17104       return V;
17105 
17106     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG, /*SimpleOnly*/ false);
17107   }
17108 
17109   if (VT == MVT::v32f16 || VT == MVT::v32bf16) {
17110     if (!Subtarget.hasBWI())
17111       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG,
17112                                   /*SimpleOnly*/ false);
17113 
17114     V1 = DAG.getBitcast(MVT::v32i16, V1);
17115     V2 = DAG.getBitcast(MVT::v32i16, V2);
17116     return DAG.getBitcast(VT,
17117                           DAG.getVectorShuffle(MVT::v32i16, DL, V1, V2, Mask));
17118   }
17119 
17120   // Dispatch to each element type for lowering. If we don't have support for
17121   // specific element type shuffles at 512 bits, immediately split them and
17122   // lower them. Each lowering routine of a given type is allowed to assume that
17123   // the requisite ISA extensions for that element type are available.
17124   switch (VT.SimpleTy) {
17125   case MVT::v8f64:
17126     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17127   case MVT::v16f32:
17128     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17129   case MVT::v8i64:
17130     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17131   case MVT::v16i32:
17132     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17133   case MVT::v32i16:
17134     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17135   case MVT::v64i8:
17136     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17137 
17138   default:
17139     llvm_unreachable("Not a valid 512-bit x86 vector type!");
17140   }
17141 }
17142 
lower1BitShuffleAsKSHIFTR(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)17143 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
17144                                          MVT VT, SDValue V1, SDValue V2,
17145                                          const X86Subtarget &Subtarget,
17146                                          SelectionDAG &DAG) {
17147   // Shuffle should be unary.
17148   if (!V2.isUndef())
17149     return SDValue();
17150 
17151   int ShiftAmt = -1;
17152   int NumElts = Mask.size();
17153   for (int i = 0; i != NumElts; ++i) {
17154     int M = Mask[i];
17155     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
17156            "Unexpected mask index.");
17157     if (M < 0)
17158       continue;
17159 
17160     // The first non-undef element determines our shift amount.
17161     if (ShiftAmt < 0) {
17162       ShiftAmt = M - i;
17163       // Need to be shifting right.
17164       if (ShiftAmt <= 0)
17165         return SDValue();
17166     }
17167     // All non-undef elements must shift by the same amount.
17168     if (ShiftAmt != M - i)
17169       return SDValue();
17170   }
17171   assert(ShiftAmt >= 0 && "All undef?");
17172 
17173   // Great we found a shift right.
17174   SDValue Res = widenMaskVector(V1, false, Subtarget, DAG, DL);
17175   Res = DAG.getNode(X86ISD::KSHIFTR, DL, Res.getValueType(), Res,
17176                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17177   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17178                      DAG.getIntPtrConstant(0, DL));
17179 }
17180 
17181 // Determine if this shuffle can be implemented with a KSHIFT instruction.
17182 // Returns the shift amount if possible or -1 if not. This is a simplified
17183 // version of matchShuffleAsShift.
match1BitShuffleAsKSHIFT(unsigned & Opcode,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable)17184 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
17185                                     int MaskOffset, const APInt &Zeroable) {
17186   int Size = Mask.size();
17187 
17188   auto CheckZeros = [&](int Shift, bool Left) {
17189     for (int j = 0; j < Shift; ++j)
17190       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
17191         return false;
17192 
17193     return true;
17194   };
17195 
17196   auto MatchShift = [&](int Shift, bool Left) {
17197     unsigned Pos = Left ? Shift : 0;
17198     unsigned Low = Left ? 0 : Shift;
17199     unsigned Len = Size - Shift;
17200     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
17201   };
17202 
17203   for (int Shift = 1; Shift != Size; ++Shift)
17204     for (bool Left : {true, false})
17205       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
17206         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
17207         return Shift;
17208       }
17209 
17210   return -1;
17211 }
17212 
17213 
17214 // Lower vXi1 vector shuffles.
17215 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
17216 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
17217 // vector, shuffle and then truncate it back.
lower1BitShuffle(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)17218 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17219                                 MVT VT, SDValue V1, SDValue V2,
17220                                 const APInt &Zeroable,
17221                                 const X86Subtarget &Subtarget,
17222                                 SelectionDAG &DAG) {
17223   assert(Subtarget.hasAVX512() &&
17224          "Cannot lower 512-bit vectors w/o basic ISA!");
17225 
17226   int NumElts = Mask.size();
17227   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17228 
17229   // Try to recognize shuffles that are just padding a subvector with zeros.
17230   int SubvecElts = 0;
17231   int Src = -1;
17232   for (int i = 0; i != NumElts; ++i) {
17233     if (Mask[i] >= 0) {
17234       // Grab the source from the first valid mask. All subsequent elements need
17235       // to use this same source.
17236       if (Src < 0)
17237         Src = Mask[i] / NumElts;
17238       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
17239         break;
17240     }
17241 
17242     ++SubvecElts;
17243   }
17244   assert(SubvecElts != NumElts && "Identity shuffle?");
17245 
17246   // Clip to a power 2.
17247   SubvecElts = llvm::bit_floor<uint32_t>(SubvecElts);
17248 
17249   // Make sure the number of zeroable bits in the top at least covers the bits
17250   // not covered by the subvector.
17251   if ((int)Zeroable.countl_one() >= (NumElts - SubvecElts)) {
17252     assert(Src >= 0 && "Expected a source!");
17253     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
17254     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
17255                                   Src == 0 ? V1 : V2,
17256                                   DAG.getIntPtrConstant(0, DL));
17257     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17258                        DAG.getConstant(0, DL, VT),
17259                        Extract, DAG.getIntPtrConstant(0, DL));
17260   }
17261 
17262   // Try a simple shift right with undef elements. Later we'll try with zeros.
17263   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
17264                                                 DAG))
17265     return Shift;
17266 
17267   // Try to match KSHIFTs.
17268   unsigned Offset = 0;
17269   for (SDValue V : { V1, V2 }) {
17270     unsigned Opcode;
17271     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
17272     if (ShiftAmt >= 0) {
17273       SDValue Res = widenMaskVector(V, false, Subtarget, DAG, DL);
17274       MVT WideVT = Res.getSimpleValueType();
17275       // Widened right shifts need two shifts to ensure we shift in zeroes.
17276       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
17277         int WideElts = WideVT.getVectorNumElements();
17278         // Shift left to put the original vector in the MSBs of the new size.
17279         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
17280                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
17281         // Increase the shift amount to account for the left shift.
17282         ShiftAmt += WideElts - NumElts;
17283       }
17284 
17285       Res = DAG.getNode(Opcode, DL, WideVT, Res,
17286                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17287       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17288                          DAG.getIntPtrConstant(0, DL));
17289     }
17290     Offset += NumElts; // Increment for next iteration.
17291   }
17292 
17293   // If we're performing an unary shuffle on a SETCC result, try to shuffle the
17294   // ops instead.
17295   // TODO: What other unary shuffles would benefit from this?
17296   if (NumV2Elements == 0 && V1.getOpcode() == ISD::SETCC && V1->hasOneUse()) {
17297     SDValue Op0 = V1.getOperand(0);
17298     SDValue Op1 = V1.getOperand(1);
17299     ISD::CondCode CC = cast<CondCodeSDNode>(V1.getOperand(2))->get();
17300     EVT OpVT = Op0.getValueType();
17301     if (OpVT.getScalarSizeInBits() >= 32 || isBroadcastShuffleMask(Mask))
17302       return DAG.getSetCC(
17303           DL, VT, DAG.getVectorShuffle(OpVT, DL, Op0, DAG.getUNDEF(OpVT), Mask),
17304           DAG.getVectorShuffle(OpVT, DL, Op1, DAG.getUNDEF(OpVT), Mask), CC);
17305   }
17306 
17307   MVT ExtVT;
17308   switch (VT.SimpleTy) {
17309   default:
17310     llvm_unreachable("Expected a vector of i1 elements");
17311   case MVT::v2i1:
17312     ExtVT = MVT::v2i64;
17313     break;
17314   case MVT::v4i1:
17315     ExtVT = MVT::v4i32;
17316     break;
17317   case MVT::v8i1:
17318     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
17319     // shuffle.
17320     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
17321     break;
17322   case MVT::v16i1:
17323     // Take 512-bit type, unless we are avoiding 512-bit types and have the
17324     // 256-bit operation available.
17325     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
17326     break;
17327   case MVT::v32i1:
17328     // Take 512-bit type, unless we are avoiding 512-bit types and have the
17329     // 256-bit operation available.
17330     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
17331     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
17332     break;
17333   case MVT::v64i1:
17334     // Fall back to scalarization. FIXME: We can do better if the shuffle
17335     // can be partitioned cleanly.
17336     if (!Subtarget.useBWIRegs())
17337       return SDValue();
17338     ExtVT = MVT::v64i8;
17339     break;
17340   }
17341 
17342   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
17343   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
17344 
17345   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
17346   // i1 was sign extended we can use X86ISD::CVT2MASK.
17347   int NumElems = VT.getVectorNumElements();
17348   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
17349       (Subtarget.hasDQI() && (NumElems < 32)))
17350     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
17351                        Shuffle, ISD::SETGT);
17352 
17353   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
17354 }
17355 
17356 /// Helper function that returns true if the shuffle mask should be
17357 /// commuted to improve canonicalization.
canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask)17358 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
17359   int NumElements = Mask.size();
17360 
17361   int NumV1Elements = 0, NumV2Elements = 0;
17362   for (int M : Mask)
17363     if (M < 0)
17364       continue;
17365     else if (M < NumElements)
17366       ++NumV1Elements;
17367     else
17368       ++NumV2Elements;
17369 
17370   // Commute the shuffle as needed such that more elements come from V1 than
17371   // V2. This allows us to match the shuffle pattern strictly on how many
17372   // elements come from V1 without handling the symmetric cases.
17373   if (NumV2Elements > NumV1Elements)
17374     return true;
17375 
17376   assert(NumV1Elements > 0 && "No V1 indices");
17377 
17378   if (NumV2Elements == 0)
17379     return false;
17380 
17381   // When the number of V1 and V2 elements are the same, try to minimize the
17382   // number of uses of V2 in the low half of the vector. When that is tied,
17383   // ensure that the sum of indices for V1 is equal to or lower than the sum
17384   // indices for V2. When those are equal, try to ensure that the number of odd
17385   // indices for V1 is lower than the number of odd indices for V2.
17386   if (NumV1Elements == NumV2Elements) {
17387     int LowV1Elements = 0, LowV2Elements = 0;
17388     for (int M : Mask.slice(0, NumElements / 2))
17389       if (M >= NumElements)
17390         ++LowV2Elements;
17391       else if (M >= 0)
17392         ++LowV1Elements;
17393     if (LowV2Elements > LowV1Elements)
17394       return true;
17395     if (LowV2Elements == LowV1Elements) {
17396       int SumV1Indices = 0, SumV2Indices = 0;
17397       for (int i = 0, Size = Mask.size(); i < Size; ++i)
17398         if (Mask[i] >= NumElements)
17399           SumV2Indices += i;
17400         else if (Mask[i] >= 0)
17401           SumV1Indices += i;
17402       if (SumV2Indices < SumV1Indices)
17403         return true;
17404       if (SumV2Indices == SumV1Indices) {
17405         int NumV1OddIndices = 0, NumV2OddIndices = 0;
17406         for (int i = 0, Size = Mask.size(); i < Size; ++i)
17407           if (Mask[i] >= NumElements)
17408             NumV2OddIndices += i % 2;
17409           else if (Mask[i] >= 0)
17410             NumV1OddIndices += i % 2;
17411         if (NumV2OddIndices < NumV1OddIndices)
17412           return true;
17413       }
17414     }
17415   }
17416 
17417   return false;
17418 }
17419 
canCombineAsMaskOperation(SDValue V,const X86Subtarget & Subtarget)17420 static bool canCombineAsMaskOperation(SDValue V,
17421                                       const X86Subtarget &Subtarget) {
17422   if (!Subtarget.hasAVX512())
17423     return false;
17424 
17425   if (!V.getValueType().isSimple())
17426     return false;
17427 
17428   MVT VT = V.getSimpleValueType().getScalarType();
17429   if ((VT == MVT::i16 || VT == MVT::i8) && !Subtarget.hasBWI())
17430     return false;
17431 
17432   // If vec width < 512, widen i8/i16 even with BWI as blendd/blendps/blendpd
17433   // are preferable to blendw/blendvb/masked-mov.
17434   if ((VT == MVT::i16 || VT == MVT::i8) &&
17435       V.getSimpleValueType().getSizeInBits() < 512)
17436     return false;
17437 
17438   auto HasMaskOperation = [&](SDValue V) {
17439     // TODO: Currently we only check limited opcode. We probably extend
17440     // it to all binary operation by checking TLI.isBinOp().
17441     switch (V->getOpcode()) {
17442     default:
17443       return false;
17444     case ISD::ADD:
17445     case ISD::SUB:
17446     case ISD::AND:
17447     case ISD::XOR:
17448     case ISD::OR:
17449     case ISD::SMAX:
17450     case ISD::SMIN:
17451     case ISD::UMAX:
17452     case ISD::UMIN:
17453     case ISD::ABS:
17454     case ISD::SHL:
17455     case ISD::SRL:
17456     case ISD::SRA:
17457     case ISD::MUL:
17458       break;
17459     }
17460     if (!V->hasOneUse())
17461       return false;
17462 
17463     return true;
17464   };
17465 
17466   if (HasMaskOperation(V))
17467     return true;
17468 
17469   return false;
17470 }
17471 
17472 // Forward declaration.
17473 static SDValue canonicalizeShuffleMaskWithHorizOp(
17474     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
17475     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
17476     const X86Subtarget &Subtarget);
17477 
17478     /// Top-level lowering for x86 vector shuffles.
17479 ///
17480 /// This handles decomposition, canonicalization, and lowering of all x86
17481 /// vector shuffles. Most of the specific lowering strategies are encapsulated
17482 /// above in helper routines. The canonicalization attempts to widen shuffles
17483 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
17484 /// s.t. only one of the two inputs needs to be tested, etc.
lowerVECTOR_SHUFFLE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17485 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
17486                                    SelectionDAG &DAG) {
17487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
17488   ArrayRef<int> OrigMask = SVOp->getMask();
17489   SDValue V1 = Op.getOperand(0);
17490   SDValue V2 = Op.getOperand(1);
17491   MVT VT = Op.getSimpleValueType();
17492   int NumElements = VT.getVectorNumElements();
17493   SDLoc DL(Op);
17494   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
17495 
17496   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
17497          "Can't lower MMX shuffles");
17498 
17499   bool V1IsUndef = V1.isUndef();
17500   bool V2IsUndef = V2.isUndef();
17501   if (V1IsUndef && V2IsUndef)
17502     return DAG.getUNDEF(VT);
17503 
17504   // When we create a shuffle node we put the UNDEF node to second operand,
17505   // but in some cases the first operand may be transformed to UNDEF.
17506   // In this case we should just commute the node.
17507   if (V1IsUndef)
17508     return DAG.getCommutedVectorShuffle(*SVOp);
17509 
17510   // Check for non-undef masks pointing at an undef vector and make the masks
17511   // undef as well. This makes it easier to match the shuffle based solely on
17512   // the mask.
17513   if (V2IsUndef &&
17514       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
17515     SmallVector<int, 8> NewMask(OrigMask);
17516     for (int &M : NewMask)
17517       if (M >= NumElements)
17518         M = -1;
17519     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17520   }
17521 
17522   // Check for illegal shuffle mask element index values.
17523   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
17524   (void)MaskUpperLimit;
17525   assert(llvm::all_of(OrigMask,
17526                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
17527          "Out of bounds shuffle index");
17528 
17529   // We actually see shuffles that are entirely re-arrangements of a set of
17530   // zero inputs. This mostly happens while decomposing complex shuffles into
17531   // simple ones. Directly lower these as a buildvector of zeros.
17532   APInt KnownUndef, KnownZero;
17533   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
17534 
17535   APInt Zeroable = KnownUndef | KnownZero;
17536   if (Zeroable.isAllOnes())
17537     return getZeroVector(VT, Subtarget, DAG, DL);
17538 
17539   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
17540 
17541   // Try to collapse shuffles into using a vector type with fewer elements but
17542   // wider element types. We cap this to not form integers or floating point
17543   // elements wider than 64 bits. It does not seem beneficial to form i128
17544   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
17545   SmallVector<int, 16> WidenedMask;
17546   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
17547       !canCombineAsMaskOperation(V1, Subtarget) &&
17548       !canCombineAsMaskOperation(V2, Subtarget) &&
17549       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
17550     // Shuffle mask widening should not interfere with a broadcast opportunity
17551     // by obfuscating the operands with bitcasts.
17552     // TODO: Avoid lowering directly from this top-level function: make this
17553     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
17554     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
17555                                                     Subtarget, DAG))
17556       return Broadcast;
17557 
17558     MVT NewEltVT = VT.isFloatingPoint()
17559                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
17560                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
17561     int NewNumElts = NumElements / 2;
17562     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
17563     // Make sure that the new vector type is legal. For example, v2f64 isn't
17564     // legal on SSE1.
17565     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
17566       if (V2IsZero) {
17567         // Modify the new Mask to take all zeros from the all-zero vector.
17568         // Choose indices that are blend-friendly.
17569         bool UsedZeroVector = false;
17570         assert(is_contained(WidenedMask, SM_SentinelZero) &&
17571                "V2's non-undef elements are used?!");
17572         for (int i = 0; i != NewNumElts; ++i)
17573           if (WidenedMask[i] == SM_SentinelZero) {
17574             WidenedMask[i] = i + NewNumElts;
17575             UsedZeroVector = true;
17576           }
17577         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
17578         // some elements to be undef.
17579         if (UsedZeroVector)
17580           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
17581       }
17582       V1 = DAG.getBitcast(NewVT, V1);
17583       V2 = DAG.getBitcast(NewVT, V2);
17584       return DAG.getBitcast(
17585           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
17586     }
17587   }
17588 
17589   SmallVector<SDValue> Ops = {V1, V2};
17590   SmallVector<int> Mask(OrigMask);
17591 
17592   // Canonicalize the shuffle with any horizontal ops inputs.
17593   // NOTE: This may update Ops and Mask.
17594   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
17595           Ops, Mask, VT.getSizeInBits(), DL, DAG, Subtarget))
17596     return DAG.getBitcast(VT, HOp);
17597 
17598   V1 = DAG.getBitcast(VT, Ops[0]);
17599   V2 = DAG.getBitcast(VT, Ops[1]);
17600   assert(NumElements == (int)Mask.size() &&
17601          "canonicalizeShuffleMaskWithHorizOp "
17602          "shouldn't alter the shuffle mask size");
17603 
17604   // Commute the shuffle if it will improve canonicalization.
17605   if (canonicalizeShuffleMaskWithCommute(Mask)) {
17606     ShuffleVectorSDNode::commuteMask(Mask);
17607     std::swap(V1, V2);
17608   }
17609 
17610   // For each vector width, delegate to a specialized lowering routine.
17611   if (VT.is128BitVector())
17612     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17613 
17614   if (VT.is256BitVector())
17615     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17616 
17617   if (VT.is512BitVector())
17618     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17619 
17620   if (Is1BitVector)
17621     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17622 
17623   llvm_unreachable("Unimplemented!");
17624 }
17625 
17626 /// Try to lower a VSELECT instruction to a vector shuffle.
lowerVSELECTtoVectorShuffle(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17627 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
17628                                            const X86Subtarget &Subtarget,
17629                                            SelectionDAG &DAG) {
17630   SDValue Cond = Op.getOperand(0);
17631   SDValue LHS = Op.getOperand(1);
17632   SDValue RHS = Op.getOperand(2);
17633   MVT VT = Op.getSimpleValueType();
17634 
17635   // Only non-legal VSELECTs reach this lowering, convert those into generic
17636   // shuffles and re-use the shuffle lowering path for blends.
17637   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
17638     SmallVector<int, 32> Mask;
17639     if (createShuffleMaskFromVSELECT(Mask, Cond))
17640       return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
17641   }
17642 
17643   return SDValue();
17644 }
17645 
LowerVSELECT(SDValue Op,SelectionDAG & DAG) const17646 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
17647   SDValue Cond = Op.getOperand(0);
17648   SDValue LHS = Op.getOperand(1);
17649   SDValue RHS = Op.getOperand(2);
17650 
17651   SDLoc dl(Op);
17652   MVT VT = Op.getSimpleValueType();
17653   if (isSoftF16(VT, Subtarget)) {
17654     MVT NVT = VT.changeVectorElementTypeToInteger();
17655     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, dl, NVT, Cond,
17656                                           DAG.getBitcast(NVT, LHS),
17657                                           DAG.getBitcast(NVT, RHS)));
17658   }
17659 
17660   // A vselect where all conditions and data are constants can be optimized into
17661   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
17662   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
17663       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
17664       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
17665     return SDValue();
17666 
17667   // Try to lower this to a blend-style vector shuffle. This can handle all
17668   // constant condition cases.
17669   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
17670     return BlendOp;
17671 
17672   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
17673   // with patterns on the mask registers on AVX-512.
17674   MVT CondVT = Cond.getSimpleValueType();
17675   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
17676   if (CondEltSize == 1)
17677     return Op;
17678 
17679   // Variable blends are only legal from SSE4.1 onward.
17680   if (!Subtarget.hasSSE41())
17681     return SDValue();
17682 
17683   unsigned EltSize = VT.getScalarSizeInBits();
17684   unsigned NumElts = VT.getVectorNumElements();
17685 
17686   // Expand v32i16/v64i8 without BWI.
17687   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
17688     return SDValue();
17689 
17690   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
17691   // into an i1 condition so that we can use the mask-based 512-bit blend
17692   // instructions.
17693   if (VT.getSizeInBits() == 512) {
17694     // Build a mask by testing the condition against zero.
17695     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
17696     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
17697                                 DAG.getConstant(0, dl, CondVT),
17698                                 ISD::SETNE);
17699     // Now return a new VSELECT using the mask.
17700     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
17701   }
17702 
17703   // SEXT/TRUNC cases where the mask doesn't match the destination size.
17704   if (CondEltSize != EltSize) {
17705     // If we don't have a sign splat, rely on the expansion.
17706     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
17707       return SDValue();
17708 
17709     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
17710     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
17711     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
17712     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
17713   }
17714 
17715   // Only some types will be legal on some subtargets. If we can emit a legal
17716   // VSELECT-matching blend, return Op, and but if we need to expand, return
17717   // a null value.
17718   switch (VT.SimpleTy) {
17719   default:
17720     // Most of the vector types have blends past SSE4.1.
17721     return Op;
17722 
17723   case MVT::v32i8:
17724     // The byte blends for AVX vectors were introduced only in AVX2.
17725     if (Subtarget.hasAVX2())
17726       return Op;
17727 
17728     return SDValue();
17729 
17730   case MVT::v8i16:
17731   case MVT::v16i16: {
17732     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
17733     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
17734     Cond = DAG.getBitcast(CastVT, Cond);
17735     LHS = DAG.getBitcast(CastVT, LHS);
17736     RHS = DAG.getBitcast(CastVT, RHS);
17737     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
17738     return DAG.getBitcast(VT, Select);
17739   }
17740   }
17741 }
17742 
LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,SelectionDAG & DAG)17743 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
17744   MVT VT = Op.getSimpleValueType();
17745   SDValue Vec = Op.getOperand(0);
17746   SDValue Idx = Op.getOperand(1);
17747   assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
17748   SDLoc dl(Op);
17749 
17750   if (!Vec.getSimpleValueType().is128BitVector())
17751     return SDValue();
17752 
17753   if (VT.getSizeInBits() == 8) {
17754     // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
17755     // we're going to zero extend the register or fold the store.
17756     if (llvm::isNullConstant(Idx) && !X86::mayFoldIntoZeroExtend(Op) &&
17757         !X86::mayFoldIntoStore(Op))
17758       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
17759                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17760                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
17761 
17762     unsigned IdxVal = Idx->getAsZExtVal();
17763     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
17764                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
17765     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
17766   }
17767 
17768   if (VT == MVT::f32) {
17769     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
17770     // the result back to FR32 register. It's only worth matching if the
17771     // result has a single use which is a store or a bitcast to i32.  And in
17772     // the case of a store, it's not worth it if the index is a constant 0,
17773     // because a MOVSSmr can be used instead, which is smaller and faster.
17774     if (!Op.hasOneUse())
17775       return SDValue();
17776     SDNode *User = *Op.getNode()->use_begin();
17777     if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
17778         (User->getOpcode() != ISD::BITCAST ||
17779          User->getValueType(0) != MVT::i32))
17780       return SDValue();
17781     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17782                                   DAG.getBitcast(MVT::v4i32, Vec), Idx);
17783     return DAG.getBitcast(MVT::f32, Extract);
17784   }
17785 
17786   if (VT == MVT::i32 || VT == MVT::i64)
17787       return Op;
17788 
17789   return SDValue();
17790 }
17791 
17792 /// Extract one bit from mask vector, like v16i1 or v8i1.
17793 /// AVX-512 feature.
ExtractBitFromMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)17794 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
17795                                         const X86Subtarget &Subtarget) {
17796   SDValue Vec = Op.getOperand(0);
17797   SDLoc dl(Vec);
17798   MVT VecVT = Vec.getSimpleValueType();
17799   SDValue Idx = Op.getOperand(1);
17800   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
17801   MVT EltVT = Op.getSimpleValueType();
17802 
17803   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
17804          "Unexpected vector type in ExtractBitFromMaskVector");
17805 
17806   // variable index can't be handled in mask registers,
17807   // extend vector to VR512/128
17808   if (!IdxC) {
17809     unsigned NumElts = VecVT.getVectorNumElements();
17810     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
17811     // than extending to 128/256bit.
17812     if (NumElts == 1) {
17813       Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
17814       MVT IntVT = MVT::getIntegerVT(Vec.getValueType().getVectorNumElements());
17815       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, DAG.getBitcast(IntVT, Vec));
17816     }
17817     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
17818     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
17819     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
17820     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
17821     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
17822   }
17823 
17824   unsigned IdxVal = IdxC->getZExtValue();
17825   if (IdxVal == 0) // the operation is legal
17826     return Op;
17827 
17828   // Extend to natively supported kshift.
17829   Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
17830 
17831   // Use kshiftr instruction to move to the lower element.
17832   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
17833                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
17834 
17835   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
17836                      DAG.getIntPtrConstant(0, dl));
17837 }
17838 
17839 // Helper to find all the extracted elements from a vector.
getExtractedDemandedElts(SDNode * N)17840 static APInt getExtractedDemandedElts(SDNode *N) {
17841   MVT VT = N->getSimpleValueType(0);
17842   unsigned NumElts = VT.getVectorNumElements();
17843   APInt DemandedElts = APInt::getZero(NumElts);
17844   for (SDNode *User : N->uses()) {
17845     switch (User->getOpcode()) {
17846     case X86ISD::PEXTRB:
17847     case X86ISD::PEXTRW:
17848     case ISD::EXTRACT_VECTOR_ELT:
17849       if (!isa<ConstantSDNode>(User->getOperand(1))) {
17850         DemandedElts.setAllBits();
17851         return DemandedElts;
17852       }
17853       DemandedElts.setBit(User->getConstantOperandVal(1));
17854       break;
17855     case ISD::BITCAST: {
17856       if (!User->getValueType(0).isSimple() ||
17857           !User->getValueType(0).isVector()) {
17858         DemandedElts.setAllBits();
17859         return DemandedElts;
17860       }
17861       APInt DemandedSrcElts = getExtractedDemandedElts(User);
17862       DemandedElts |= APIntOps::ScaleBitMask(DemandedSrcElts, NumElts);
17863       break;
17864     }
17865     default:
17866       DemandedElts.setAllBits();
17867       return DemandedElts;
17868     }
17869   }
17870   return DemandedElts;
17871 }
17872 
17873 SDValue
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const17874 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
17875                                            SelectionDAG &DAG) const {
17876   SDLoc dl(Op);
17877   SDValue Vec = Op.getOperand(0);
17878   MVT VecVT = Vec.getSimpleValueType();
17879   SDValue Idx = Op.getOperand(1);
17880   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
17881 
17882   if (VecVT.getVectorElementType() == MVT::i1)
17883     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
17884 
17885   if (!IdxC) {
17886     // Its more profitable to go through memory (1 cycles throughput)
17887     // than using VMOVD + VPERMV/PSHUFB sequence (2/3 cycles throughput)
17888     // IACA tool was used to get performance estimation
17889     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
17890     //
17891     // example : extractelement <16 x i8> %a, i32 %i
17892     //
17893     // Block Throughput: 3.00 Cycles
17894     // Throughput Bottleneck: Port5
17895     //
17896     // | Num Of |   Ports pressure in cycles  |    |
17897     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
17898     // ---------------------------------------------
17899     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
17900     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
17901     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
17902     // Total Num Of Uops: 4
17903     //
17904     //
17905     // Block Throughput: 1.00 Cycles
17906     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
17907     //
17908     // |    |  Ports pressure in cycles   |  |
17909     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
17910     // ---------------------------------------------------------
17911     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
17912     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
17913     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
17914     // Total Num Of Uops: 4
17915 
17916     return SDValue();
17917   }
17918 
17919   unsigned IdxVal = IdxC->getZExtValue();
17920 
17921   // If this is a 256-bit vector result, first extract the 128-bit vector and
17922   // then extract the element from the 128-bit vector.
17923   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
17924     // Get the 128-bit vector.
17925     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
17926     MVT EltVT = VecVT.getVectorElementType();
17927 
17928     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
17929     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
17930 
17931     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
17932     // this can be done with a mask.
17933     IdxVal &= ElemsPerChunk - 1;
17934     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
17935                        DAG.getIntPtrConstant(IdxVal, dl));
17936   }
17937 
17938   assert(VecVT.is128BitVector() && "Unexpected vector length");
17939 
17940   MVT VT = Op.getSimpleValueType();
17941 
17942   if (VT == MVT::i16) {
17943     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
17944     // we're going to zero extend the register or fold the store (SSE41 only).
17945     if (IdxVal == 0 && !X86::mayFoldIntoZeroExtend(Op) &&
17946         !(Subtarget.hasSSE41() && X86::mayFoldIntoStore(Op))) {
17947       if (Subtarget.hasFP16())
17948         return Op;
17949 
17950       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
17951                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17952                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
17953     }
17954 
17955     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
17956                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
17957     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
17958   }
17959 
17960   if (Subtarget.hasSSE41())
17961     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
17962       return Res;
17963 
17964   // Only extract a single element from a v16i8 source - determine the common
17965   // DWORD/WORD that all extractions share, and extract the sub-byte.
17966   // TODO: Add QWORD MOVQ extraction?
17967   if (VT == MVT::i8) {
17968     APInt DemandedElts = getExtractedDemandedElts(Vec.getNode());
17969     assert(DemandedElts.getBitWidth() == 16 && "Vector width mismatch");
17970 
17971     // Extract either the lowest i32 or any i16, and extract the sub-byte.
17972     int DWordIdx = IdxVal / 4;
17973     if (DWordIdx == 0 && DemandedElts == (DemandedElts & 15)) {
17974       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
17975                                 DAG.getBitcast(MVT::v4i32, Vec),
17976                                 DAG.getIntPtrConstant(DWordIdx, dl));
17977       int ShiftVal = (IdxVal % 4) * 8;
17978       if (ShiftVal != 0)
17979         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
17980                           DAG.getConstant(ShiftVal, dl, MVT::i8));
17981       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
17982     }
17983 
17984     int WordIdx = IdxVal / 2;
17985     if (DemandedElts == (DemandedElts & (3 << (WordIdx * 2)))) {
17986       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
17987                                 DAG.getBitcast(MVT::v8i16, Vec),
17988                                 DAG.getIntPtrConstant(WordIdx, dl));
17989       int ShiftVal = (IdxVal % 2) * 8;
17990       if (ShiftVal != 0)
17991         Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
17992                           DAG.getConstant(ShiftVal, dl, MVT::i8));
17993       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
17994     }
17995   }
17996 
17997   if (VT == MVT::f16 || VT.getSizeInBits() == 32) {
17998     if (IdxVal == 0)
17999       return Op;
18000 
18001     // Shuffle the element to the lowest element, then movss or movsh.
18002     SmallVector<int, 8> Mask(VecVT.getVectorNumElements(), -1);
18003     Mask[0] = static_cast<int>(IdxVal);
18004     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18005     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18006                        DAG.getIntPtrConstant(0, dl));
18007   }
18008 
18009   if (VT.getSizeInBits() == 64) {
18010     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
18011     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
18012     //        to match extract_elt for f64.
18013     if (IdxVal == 0)
18014       return Op;
18015 
18016     // UNPCKHPD the element to the lowest double word, then movsd.
18017     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
18018     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
18019     int Mask[2] = { 1, -1 };
18020     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18021     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18022                        DAG.getIntPtrConstant(0, dl));
18023   }
18024 
18025   return SDValue();
18026 }
18027 
18028 /// Insert one bit to mask vector, like v16i1 or v8i1.
18029 /// AVX-512 feature.
InsertBitToMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18030 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
18031                                      const X86Subtarget &Subtarget) {
18032   SDLoc dl(Op);
18033   SDValue Vec = Op.getOperand(0);
18034   SDValue Elt = Op.getOperand(1);
18035   SDValue Idx = Op.getOperand(2);
18036   MVT VecVT = Vec.getSimpleValueType();
18037 
18038   if (!isa<ConstantSDNode>(Idx)) {
18039     // Non constant index. Extend source and destination,
18040     // insert element and then truncate the result.
18041     unsigned NumElts = VecVT.getVectorNumElements();
18042     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18043     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18044     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
18045       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
18046       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
18047     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
18048   }
18049 
18050   // Copy into a k-register, extract to v1i1 and insert_subvector.
18051   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
18052   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
18053 }
18054 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const18055 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
18056                                                   SelectionDAG &DAG) const {
18057   MVT VT = Op.getSimpleValueType();
18058   MVT EltVT = VT.getVectorElementType();
18059   unsigned NumElts = VT.getVectorNumElements();
18060   unsigned EltSizeInBits = EltVT.getScalarSizeInBits();
18061 
18062   if (EltVT == MVT::i1)
18063     return InsertBitToMaskVector(Op, DAG, Subtarget);
18064 
18065   SDLoc dl(Op);
18066   SDValue N0 = Op.getOperand(0);
18067   SDValue N1 = Op.getOperand(1);
18068   SDValue N2 = Op.getOperand(2);
18069   auto *N2C = dyn_cast<ConstantSDNode>(N2);
18070 
18071   if (EltVT == MVT::bf16) {
18072     MVT IVT = VT.changeVectorElementTypeToInteger();
18073     SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVT,
18074                               DAG.getBitcast(IVT, N0),
18075                               DAG.getBitcast(MVT::i16, N1), N2);
18076     return DAG.getBitcast(VT, Res);
18077   }
18078 
18079   if (!N2C) {
18080     // Variable insertion indices, usually we're better off spilling to stack,
18081     // but AVX512 can use a variable compare+select by comparing against all
18082     // possible vector indices, and FP insertion has less gpr->simd traffic.
18083     if (!(Subtarget.hasBWI() ||
18084           (Subtarget.hasAVX512() && EltSizeInBits >= 32) ||
18085           (Subtarget.hasSSE41() && (EltVT == MVT::f32 || EltVT == MVT::f64))))
18086       return SDValue();
18087 
18088     MVT IdxSVT = MVT::getIntegerVT(EltSizeInBits);
18089     MVT IdxVT = MVT::getVectorVT(IdxSVT, NumElts);
18090     if (!isTypeLegal(IdxSVT) || !isTypeLegal(IdxVT))
18091       return SDValue();
18092 
18093     SDValue IdxExt = DAG.getZExtOrTrunc(N2, dl, IdxSVT);
18094     SDValue IdxSplat = DAG.getSplatBuildVector(IdxVT, dl, IdxExt);
18095     SDValue EltSplat = DAG.getSplatBuildVector(VT, dl, N1);
18096 
18097     SmallVector<SDValue, 16> RawIndices;
18098     for (unsigned I = 0; I != NumElts; ++I)
18099       RawIndices.push_back(DAG.getConstant(I, dl, IdxSVT));
18100     SDValue Indices = DAG.getBuildVector(IdxVT, dl, RawIndices);
18101 
18102     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
18103     return DAG.getSelectCC(dl, IdxSplat, Indices, EltSplat, N0,
18104                            ISD::CondCode::SETEQ);
18105   }
18106 
18107   if (N2C->getAPIntValue().uge(NumElts))
18108     return SDValue();
18109   uint64_t IdxVal = N2C->getZExtValue();
18110 
18111   bool IsZeroElt = X86::isZeroNode(N1);
18112   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
18113 
18114   if (IsZeroElt || IsAllOnesElt) {
18115     // Lower insertion of v16i8/v32i8/v64i16 -1 elts as an 'OR' blend.
18116     // We don't deal with i8 0 since it appears to be handled elsewhere.
18117     if (IsAllOnesElt &&
18118         ((VT == MVT::v16i8 && !Subtarget.hasSSE41()) ||
18119          ((VT == MVT::v32i8 || VT == MVT::v16i16) && !Subtarget.hasInt256()))) {
18120       SDValue ZeroCst = DAG.getConstant(0, dl, VT.getScalarType());
18121       SDValue OnesCst = DAG.getAllOnesConstant(dl, VT.getScalarType());
18122       SmallVector<SDValue, 8> CstVectorElts(NumElts, ZeroCst);
18123       CstVectorElts[IdxVal] = OnesCst;
18124       SDValue CstVector = DAG.getBuildVector(VT, dl, CstVectorElts);
18125       return DAG.getNode(ISD::OR, dl, VT, N0, CstVector);
18126     }
18127     // See if we can do this more efficiently with a blend shuffle with a
18128     // rematerializable vector.
18129     if (Subtarget.hasSSE41() &&
18130         (EltSizeInBits >= 16 || (IsZeroElt && !VT.is128BitVector()))) {
18131       SmallVector<int, 8> BlendMask;
18132       for (unsigned i = 0; i != NumElts; ++i)
18133         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18134       SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
18135                                     : getOnesVector(VT, DAG, dl);
18136       return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
18137     }
18138   }
18139 
18140   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
18141   // into that, and then insert the subvector back into the result.
18142   if (VT.is256BitVector() || VT.is512BitVector()) {
18143     // With a 256-bit vector, we can insert into the zero element efficiently
18144     // using a blend if we have AVX or AVX2 and the right data type.
18145     if (VT.is256BitVector() && IdxVal == 0) {
18146       // TODO: It is worthwhile to cast integer to floating point and back
18147       // and incur a domain crossing penalty if that's what we'll end up
18148       // doing anyway after extracting to a 128-bit vector.
18149       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
18150           (Subtarget.hasAVX2() && (EltVT == MVT::i32 || EltVT == MVT::i64))) {
18151         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18152         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
18153                            DAG.getTargetConstant(1, dl, MVT::i8));
18154       }
18155     }
18156 
18157     unsigned NumEltsIn128 = 128 / EltSizeInBits;
18158     assert(isPowerOf2_32(NumEltsIn128) &&
18159            "Vectors will always have power-of-two number of elements.");
18160 
18161     // If we are not inserting into the low 128-bit vector chunk,
18162     // then prefer the broadcast+blend sequence.
18163     // FIXME: relax the profitability check iff all N1 uses are insertions.
18164     if (IdxVal >= NumEltsIn128 &&
18165         ((Subtarget.hasAVX2() && EltSizeInBits != 8) ||
18166          (Subtarget.hasAVX() && (EltSizeInBits >= 32) &&
18167           X86::mayFoldLoad(N1, Subtarget)))) {
18168       SDValue N1SplatVec = DAG.getSplatBuildVector(VT, dl, N1);
18169       SmallVector<int, 8> BlendMask;
18170       for (unsigned i = 0; i != NumElts; ++i)
18171         BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18172       return DAG.getVectorShuffle(VT, dl, N0, N1SplatVec, BlendMask);
18173     }
18174 
18175     // Get the desired 128-bit vector chunk.
18176     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
18177 
18178     // Insert the element into the desired chunk.
18179     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
18180     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
18181 
18182     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
18183                     DAG.getIntPtrConstant(IdxIn128, dl));
18184 
18185     // Insert the changed part back into the bigger vector
18186     return insert128BitVector(N0, V, IdxVal, DAG, dl);
18187   }
18188   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
18189 
18190   // This will be just movw/movd/movq/movsh/movss/movsd.
18191   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
18192     if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
18193         EltVT == MVT::f16 || EltVT == MVT::i64) {
18194       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18195       return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18196     }
18197 
18198     // We can't directly insert an i8 or i16 into a vector, so zero extend
18199     // it to i32 first.
18200     if (EltVT == MVT::i16 || EltVT == MVT::i8) {
18201       N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
18202       MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
18203       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
18204       N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18205       return DAG.getBitcast(VT, N1);
18206     }
18207   }
18208 
18209   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
18210   // argument. SSE41 required for pinsrb.
18211   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
18212     unsigned Opc;
18213     if (VT == MVT::v8i16) {
18214       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
18215       Opc = X86ISD::PINSRW;
18216     } else {
18217       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
18218       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
18219       Opc = X86ISD::PINSRB;
18220     }
18221 
18222     assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
18223     N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
18224     N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
18225     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
18226   }
18227 
18228   if (Subtarget.hasSSE41()) {
18229     if (EltVT == MVT::f32) {
18230       // Bits [7:6] of the constant are the source select. This will always be
18231       //   zero here. The DAG Combiner may combine an extract_elt index into
18232       //   these bits. For example (insert (extract, 3), 2) could be matched by
18233       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
18234       // Bits [5:4] of the constant are the destination select. This is the
18235       //   value of the incoming immediate.
18236       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
18237       //   combine either bitwise AND or insert of float 0.0 to set these bits.
18238 
18239       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
18240       if (IdxVal == 0 && (!MinSize || !X86::mayFoldLoad(N1, Subtarget))) {
18241         // If this is an insertion of 32-bits into the low 32-bits of
18242         // a vector, we prefer to generate a blend with immediate rather
18243         // than an insertps. Blends are simpler operations in hardware and so
18244         // will always have equal or better performance than insertps.
18245         // But if optimizing for size and there's a load folding opportunity,
18246         // generate insertps because blendps does not have a 32-bit memory
18247         // operand form.
18248         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18249         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
18250                            DAG.getTargetConstant(1, dl, MVT::i8));
18251       }
18252       // Create this as a scalar to vector..
18253       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18254       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
18255                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
18256     }
18257 
18258     // PINSR* works with constant index.
18259     if (EltVT == MVT::i32 || EltVT == MVT::i64)
18260       return Op;
18261   }
18262 
18263   return SDValue();
18264 }
18265 
LowerSCALAR_TO_VECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18266 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
18267                                      SelectionDAG &DAG) {
18268   SDLoc dl(Op);
18269   MVT OpVT = Op.getSimpleValueType();
18270 
18271   // It's always cheaper to replace a xor+movd with xorps and simplifies further
18272   // combines.
18273   if (X86::isZeroNode(Op.getOperand(0)))
18274     return getZeroVector(OpVT, Subtarget, DAG, dl);
18275 
18276   // If this is a 256-bit vector result, first insert into a 128-bit
18277   // vector and then insert into the 256-bit vector.
18278   if (!OpVT.is128BitVector()) {
18279     // Insert into a 128-bit vector.
18280     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
18281     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
18282                                  OpVT.getVectorNumElements() / SizeFactor);
18283 
18284     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
18285 
18286     // Insert the 128-bit vector.
18287     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
18288   }
18289   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
18290          "Expected an SSE type!");
18291 
18292   // Pass through a v4i32 or V8i16 SCALAR_TO_VECTOR as that's what we use in
18293   // tblgen.
18294   if (OpVT == MVT::v4i32 || (OpVT == MVT::v8i16 && Subtarget.hasFP16()))
18295     return Op;
18296 
18297   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
18298   return DAG.getBitcast(
18299       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
18300 }
18301 
18302 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
18303 // simple superregister reference or explicit instructions to insert
18304 // the upper bits of a vector.
LowerINSERT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18305 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18306                                      SelectionDAG &DAG) {
18307   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
18308 
18309   return insert1BitVector(Op, DAG, Subtarget);
18310 }
18311 
LowerEXTRACT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18312 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18313                                       SelectionDAG &DAG) {
18314   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
18315          "Only vXi1 extract_subvectors need custom lowering");
18316 
18317   SDLoc dl(Op);
18318   SDValue Vec = Op.getOperand(0);
18319   uint64_t IdxVal = Op.getConstantOperandVal(1);
18320 
18321   if (IdxVal == 0) // the operation is legal
18322     return Op;
18323 
18324   // Extend to natively supported kshift.
18325   Vec = widenMaskVector(Vec, false, Subtarget, DAG, dl);
18326 
18327   // Shift to the LSB.
18328   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, Vec.getSimpleValueType(), Vec,
18329                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18330 
18331   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
18332                      DAG.getIntPtrConstant(0, dl));
18333 }
18334 
18335 // Returns the appropriate wrapper opcode for a global reference.
getGlobalWrapperKind(const GlobalValue * GV,const unsigned char OpFlags) const18336 unsigned X86TargetLowering::getGlobalWrapperKind(
18337     const GlobalValue *GV, const unsigned char OpFlags) const {
18338   // References to absolute symbols are never PC-relative.
18339   if (GV && GV->isAbsoluteSymbolRef())
18340     return X86ISD::Wrapper;
18341 
18342   // The following OpFlags under RIP-rel PIC use RIP.
18343   if (Subtarget.isPICStyleRIPRel() &&
18344       (OpFlags == X86II::MO_NO_FLAG || OpFlags == X86II::MO_COFFSTUB ||
18345        OpFlags == X86II::MO_DLLIMPORT))
18346     return X86ISD::WrapperRIP;
18347 
18348   // GOTPCREL references must always use RIP.
18349   if (OpFlags == X86II::MO_GOTPCREL || OpFlags == X86II::MO_GOTPCREL_NORELAX)
18350     return X86ISD::WrapperRIP;
18351 
18352   return X86ISD::Wrapper;
18353 }
18354 
18355 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
18356 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
18357 // one of the above mentioned nodes. It has to be wrapped because otherwise
18358 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
18359 // be used to form addressing mode. These wrapped nodes will be selected
18360 // into MOV32ri.
18361 SDValue
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const18362 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
18363   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
18364 
18365   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18366   // global base reg.
18367   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18368 
18369   auto PtrVT = getPointerTy(DAG.getDataLayout());
18370   SDValue Result = DAG.getTargetConstantPool(
18371       CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
18372   SDLoc DL(CP);
18373   Result =
18374       DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
18375   // With PIC, the address is actually $g + Offset.
18376   if (OpFlag) {
18377     Result =
18378         DAG.getNode(ISD::ADD, DL, PtrVT,
18379                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18380   }
18381 
18382   return Result;
18383 }
18384 
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const18385 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
18386   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
18387 
18388   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18389   // global base reg.
18390   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18391 
18392   auto PtrVT = getPointerTy(DAG.getDataLayout());
18393   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
18394   SDLoc DL(JT);
18395   Result =
18396       DAG.getNode(getGlobalWrapperKind(nullptr, OpFlag), DL, PtrVT, Result);
18397 
18398   // With PIC, the address is actually $g + Offset.
18399   if (OpFlag)
18400     Result =
18401         DAG.getNode(ISD::ADD, DL, PtrVT,
18402                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18403 
18404   return Result;
18405 }
18406 
LowerExternalSymbol(SDValue Op,SelectionDAG & DAG) const18407 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
18408                                                SelectionDAG &DAG) const {
18409   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18410 }
18411 
18412 SDValue
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const18413 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
18414   // Create the TargetBlockAddressAddress node.
18415   unsigned char OpFlags =
18416     Subtarget.classifyBlockAddressReference();
18417   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
18418   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
18419   SDLoc dl(Op);
18420   auto PtrVT = getPointerTy(DAG.getDataLayout());
18421   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
18422   Result =
18423       DAG.getNode(getGlobalWrapperKind(nullptr, OpFlags), dl, PtrVT, Result);
18424 
18425   // With PIC, the address is actually $g + Offset.
18426   if (isGlobalRelativeToPICBase(OpFlags)) {
18427     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18428                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18429   }
18430 
18431   return Result;
18432 }
18433 
18434 /// Creates target global address or external symbol nodes for calls or
18435 /// other uses.
LowerGlobalOrExternal(SDValue Op,SelectionDAG & DAG,bool ForCall) const18436 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
18437                                                  bool ForCall) const {
18438   // Unpack the global address or external symbol.
18439   const SDLoc &dl = SDLoc(Op);
18440   const GlobalValue *GV = nullptr;
18441   int64_t Offset = 0;
18442   const char *ExternalSym = nullptr;
18443   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
18444     GV = G->getGlobal();
18445     Offset = G->getOffset();
18446   } else {
18447     const auto *ES = cast<ExternalSymbolSDNode>(Op);
18448     ExternalSym = ES->getSymbol();
18449   }
18450 
18451   // Calculate some flags for address lowering.
18452   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
18453   unsigned char OpFlags;
18454   if (ForCall)
18455     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
18456   else
18457     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
18458   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
18459   bool NeedsLoad = isGlobalStubReference(OpFlags);
18460 
18461   CodeModel::Model M = DAG.getTarget().getCodeModel();
18462   auto PtrVT = getPointerTy(DAG.getDataLayout());
18463   SDValue Result;
18464 
18465   if (GV) {
18466     // Create a target global address if this is a global. If possible, fold the
18467     // offset into the global address reference. Otherwise, ADD it on later.
18468     // Suppress the folding if Offset is negative: movl foo-1, %eax is not
18469     // allowed because if the address of foo is 0, the ELF R_X86_64_32
18470     // relocation will compute to a negative value, which is invalid.
18471     int64_t GlobalOffset = 0;
18472     if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
18473         X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
18474       std::swap(GlobalOffset, Offset);
18475     }
18476     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
18477   } else {
18478     // If this is not a global address, this must be an external symbol.
18479     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
18480   }
18481 
18482   // If this is a direct call, avoid the wrapper if we don't need to do any
18483   // loads or adds. This allows SDAG ISel to match direct calls.
18484   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
18485     return Result;
18486 
18487   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
18488 
18489   // With PIC, the address is actually $g + Offset.
18490   if (HasPICReg) {
18491     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18492                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18493   }
18494 
18495   // For globals that require a load from a stub to get the address, emit the
18496   // load.
18497   if (NeedsLoad)
18498     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
18499                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18500 
18501   // If there was a non-zero offset that we didn't fold, create an explicit
18502   // addition for it.
18503   if (Offset != 0)
18504     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
18505                          DAG.getConstant(Offset, dl, PtrVT));
18506 
18507   return Result;
18508 }
18509 
18510 SDValue
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const18511 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
18512   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18513 }
18514 
18515 static SDValue
GetTLSADDR(SelectionDAG & DAG,SDValue Chain,GlobalAddressSDNode * GA,SDValue * InGlue,const EVT PtrVT,unsigned ReturnReg,unsigned char OperandFlags,bool LocalDynamic=false)18516 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
18517            SDValue *InGlue, const EVT PtrVT, unsigned ReturnReg,
18518            unsigned char OperandFlags, bool LocalDynamic = false) {
18519   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18520   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18521   SDLoc dl(GA);
18522   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18523                                            GA->getValueType(0),
18524                                            GA->getOffset(),
18525                                            OperandFlags);
18526 
18527   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
18528                                            : X86ISD::TLSADDR;
18529 
18530   if (InGlue) {
18531     SDValue Ops[] = { Chain,  TGA, *InGlue };
18532     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
18533   } else {
18534     SDValue Ops[]  = { Chain, TGA };
18535     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
18536   }
18537 
18538   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
18539   MFI.setAdjustsStack(true);
18540   MFI.setHasCalls(true);
18541 
18542   SDValue Glue = Chain.getValue(1);
18543   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Glue);
18544 }
18545 
18546 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
18547 static SDValue
LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18548 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18549                                 const EVT PtrVT) {
18550   SDValue InGlue;
18551   SDLoc dl(GA);  // ? function entry point might be better
18552   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
18553                                    DAG.getNode(X86ISD::GlobalBaseReg,
18554                                                SDLoc(), PtrVT), InGlue);
18555   InGlue = Chain.getValue(1);
18556 
18557   return GetTLSADDR(DAG, Chain, GA, &InGlue, PtrVT, X86::EAX, X86II::MO_TLSGD);
18558 }
18559 
18560 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
18561 static SDValue
LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18562 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18563                                 const EVT PtrVT) {
18564   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
18565                     X86::RAX, X86II::MO_TLSGD);
18566 }
18567 
18568 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
18569 static SDValue
LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18570 LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18571                                  const EVT PtrVT) {
18572   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
18573                     X86::EAX, X86II::MO_TLSGD);
18574 }
18575 
LowerToTLSLocalDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,bool Is64Bit,bool Is64BitLP64)18576 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
18577                                            SelectionDAG &DAG, const EVT PtrVT,
18578                                            bool Is64Bit, bool Is64BitLP64) {
18579   SDLoc dl(GA);
18580 
18581   // Get the start address of the TLS block for this module.
18582   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
18583       .getInfo<X86MachineFunctionInfo>();
18584   MFI->incNumLocalDynamicTLSAccesses();
18585 
18586   SDValue Base;
18587   if (Is64Bit) {
18588     unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
18589     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, ReturnReg,
18590                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
18591   } else {
18592     SDValue InGlue;
18593     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
18594         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InGlue);
18595     InGlue = Chain.getValue(1);
18596     Base = GetTLSADDR(DAG, Chain, GA, &InGlue, PtrVT, X86::EAX,
18597                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
18598   }
18599 
18600   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
18601   // of Base.
18602 
18603   // Build x@dtpoff.
18604   unsigned char OperandFlags = X86II::MO_DTPOFF;
18605   unsigned WrapperKind = X86ISD::Wrapper;
18606   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18607                                            GA->getValueType(0),
18608                                            GA->getOffset(), OperandFlags);
18609   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
18610 
18611   // Add x@dtpoff with the base.
18612   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
18613 }
18614 
18615 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
LowerToTLSExecModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,TLSModel::Model model,bool is64Bit,bool isPIC)18616 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18617                                    const EVT PtrVT, TLSModel::Model model,
18618                                    bool is64Bit, bool isPIC) {
18619   SDLoc dl(GA);
18620 
18621   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
18622   Value *Ptr = Constant::getNullValue(
18623       PointerType::get(*DAG.getContext(), is64Bit ? 257 : 256));
18624 
18625   SDValue ThreadPointer =
18626       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
18627                   MachinePointerInfo(Ptr));
18628 
18629   unsigned char OperandFlags = 0;
18630   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
18631   // initialexec.
18632   unsigned WrapperKind = X86ISD::Wrapper;
18633   if (model == TLSModel::LocalExec) {
18634     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
18635   } else if (model == TLSModel::InitialExec) {
18636     if (is64Bit) {
18637       OperandFlags = X86II::MO_GOTTPOFF;
18638       WrapperKind = X86ISD::WrapperRIP;
18639     } else {
18640       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
18641     }
18642   } else {
18643     llvm_unreachable("Unexpected model");
18644   }
18645 
18646   // emit "addl x@ntpoff,%eax" (local exec)
18647   // or "addl x@indntpoff,%eax" (initial exec)
18648   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
18649   SDValue TGA =
18650       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
18651                                  GA->getOffset(), OperandFlags);
18652   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
18653 
18654   if (model == TLSModel::InitialExec) {
18655     if (isPIC && !is64Bit) {
18656       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
18657                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
18658                            Offset);
18659     }
18660 
18661     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
18662                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18663   }
18664 
18665   // The address of the thread local variable is the add of the thread
18666   // pointer with the offset of the variable.
18667   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
18668 }
18669 
18670 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const18671 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
18672 
18673   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
18674 
18675   if (DAG.getTarget().useEmulatedTLS())
18676     return LowerToTLSEmulatedModel(GA, DAG);
18677 
18678   const GlobalValue *GV = GA->getGlobal();
18679   auto PtrVT = getPointerTy(DAG.getDataLayout());
18680   bool PositionIndependent = isPositionIndependent();
18681 
18682   if (Subtarget.isTargetELF()) {
18683     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
18684     switch (model) {
18685       case TLSModel::GeneralDynamic:
18686         if (Subtarget.is64Bit()) {
18687           if (Subtarget.isTarget64BitLP64())
18688             return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
18689           return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
18690         }
18691         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
18692       case TLSModel::LocalDynamic:
18693         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
18694                                            Subtarget.isTarget64BitLP64());
18695       case TLSModel::InitialExec:
18696       case TLSModel::LocalExec:
18697         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
18698                                    PositionIndependent);
18699     }
18700     llvm_unreachable("Unknown TLS model.");
18701   }
18702 
18703   if (Subtarget.isTargetDarwin()) {
18704     // Darwin only has one model of TLS.  Lower to that.
18705     unsigned char OpFlag = 0;
18706     unsigned WrapperKind = 0;
18707 
18708     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18709     // global base reg.
18710     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
18711     if (PIC32) {
18712       OpFlag = X86II::MO_TLVP_PIC_BASE;
18713       WrapperKind = X86ISD::Wrapper;
18714     } else {
18715       OpFlag = X86II::MO_TLVP;
18716       WrapperKind = X86ISD::WrapperRIP;
18717     }
18718     SDLoc DL(Op);
18719     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
18720                                                 GA->getValueType(0),
18721                                                 GA->getOffset(), OpFlag);
18722     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
18723 
18724     // With PIC32, the address is actually $g + Offset.
18725     if (PIC32)
18726       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
18727                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
18728                            Offset);
18729 
18730     // Lowering the machine isd will make sure everything is in the right
18731     // location.
18732     SDValue Chain = DAG.getEntryNode();
18733     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18734     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
18735     SDValue Args[] = { Chain, Offset };
18736     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
18737     Chain = DAG.getCALLSEQ_END(Chain, 0, 0, Chain.getValue(1), DL);
18738 
18739     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
18740     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18741     MFI.setAdjustsStack(true);
18742 
18743     // And our return value (tls address) is in the standard call return value
18744     // location.
18745     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
18746     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
18747   }
18748 
18749   if (Subtarget.isOSWindows()) {
18750     // Just use the implicit TLS architecture
18751     // Need to generate something similar to:
18752     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
18753     //                                  ; from TEB
18754     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
18755     //   mov     rcx, qword [rdx+rcx*8]
18756     //   mov     eax, .tls$:tlsvar
18757     //   [rax+rcx] contains the address
18758     // Windows 64bit: gs:0x58
18759     // Windows 32bit: fs:__tls_array
18760 
18761     SDLoc dl(GA);
18762     SDValue Chain = DAG.getEntryNode();
18763 
18764     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
18765     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
18766     // use its literal value of 0x2C.
18767     Value *Ptr = Constant::getNullValue(
18768         Subtarget.is64Bit() ? PointerType::get(*DAG.getContext(), 256)
18769                             : PointerType::get(*DAG.getContext(), 257));
18770 
18771     SDValue TlsArray = Subtarget.is64Bit()
18772                            ? DAG.getIntPtrConstant(0x58, dl)
18773                            : (Subtarget.isTargetWindowsGNU()
18774                                   ? DAG.getIntPtrConstant(0x2C, dl)
18775                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
18776 
18777     SDValue ThreadPointer =
18778         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
18779 
18780     SDValue res;
18781     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
18782       res = ThreadPointer;
18783     } else {
18784       // Load the _tls_index variable
18785       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
18786       if (Subtarget.is64Bit())
18787         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
18788                              MachinePointerInfo(), MVT::i32);
18789       else
18790         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
18791 
18792       const DataLayout &DL = DAG.getDataLayout();
18793       SDValue Scale =
18794           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
18795       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
18796 
18797       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
18798     }
18799 
18800     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
18801 
18802     // Get the offset of start of .tls section
18803     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18804                                              GA->getValueType(0),
18805                                              GA->getOffset(), X86II::MO_SECREL);
18806     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
18807 
18808     // The address of the thread local variable is the add of the thread
18809     // pointer with the offset of the variable.
18810     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
18811   }
18812 
18813   llvm_unreachable("TLS not implemented for this target.");
18814 }
18815 
18816 /// Lower SRA_PARTS and friends, which return two i32 values
18817 /// and take a 2 x i32 value to shift plus a shift amount.
18818 /// TODO: Can this be moved to general expansion code?
LowerShiftParts(SDValue Op,SelectionDAG & DAG)18819 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
18820   SDValue Lo, Hi;
18821   DAG.getTargetLoweringInfo().expandShiftParts(Op.getNode(), Lo, Hi, DAG);
18822   return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
18823 }
18824 
18825 // Try to use a packed vector operation to handle i64 on 32-bit targets when
18826 // AVX512DQ is enabled.
LowerI64IntToFP_AVX512DQ(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18827 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
18828                                         const X86Subtarget &Subtarget) {
18829   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
18830           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
18831           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
18832           Op.getOpcode() == ISD::UINT_TO_FP) &&
18833          "Unexpected opcode!");
18834   bool IsStrict = Op->isStrictFPOpcode();
18835   unsigned OpNo = IsStrict ? 1 : 0;
18836   SDValue Src = Op.getOperand(OpNo);
18837   MVT SrcVT = Src.getSimpleValueType();
18838   MVT VT = Op.getSimpleValueType();
18839 
18840    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
18841        (VT != MVT::f32 && VT != MVT::f64))
18842     return SDValue();
18843 
18844   // Pack the i64 into a vector, do the operation and extract.
18845 
18846   // Using 256-bit to ensure result is 128-bits for f32 case.
18847   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
18848   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
18849   MVT VecVT = MVT::getVectorVT(VT, NumElts);
18850 
18851   SDLoc dl(Op);
18852   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
18853   if (IsStrict) {
18854     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
18855                                  {Op.getOperand(0), InVec});
18856     SDValue Chain = CvtVec.getValue(1);
18857     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
18858                                 DAG.getIntPtrConstant(0, dl));
18859     return DAG.getMergeValues({Value, Chain}, dl);
18860   }
18861 
18862   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
18863 
18864   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
18865                      DAG.getIntPtrConstant(0, dl));
18866 }
18867 
18868 // Try to use a packed vector operation to handle i64 on 32-bit targets.
LowerI64IntToFP16(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18869 static SDValue LowerI64IntToFP16(SDValue Op, SelectionDAG &DAG,
18870                                  const X86Subtarget &Subtarget) {
18871   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
18872           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
18873           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
18874           Op.getOpcode() == ISD::UINT_TO_FP) &&
18875          "Unexpected opcode!");
18876   bool IsStrict = Op->isStrictFPOpcode();
18877   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
18878   MVT SrcVT = Src.getSimpleValueType();
18879   MVT VT = Op.getSimpleValueType();
18880 
18881   if (SrcVT != MVT::i64 || Subtarget.is64Bit() || VT != MVT::f16)
18882     return SDValue();
18883 
18884   // Pack the i64 into a vector, do the operation and extract.
18885 
18886   assert(Subtarget.hasFP16() && "Expected FP16");
18887 
18888   SDLoc dl(Op);
18889   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
18890   if (IsStrict) {
18891     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {MVT::v2f16, MVT::Other},
18892                                  {Op.getOperand(0), InVec});
18893     SDValue Chain = CvtVec.getValue(1);
18894     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
18895                                 DAG.getIntPtrConstant(0, dl));
18896     return DAG.getMergeValues({Value, Chain}, dl);
18897   }
18898 
18899   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, MVT::v2f16, InVec);
18900 
18901   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
18902                      DAG.getIntPtrConstant(0, dl));
18903 }
18904 
useVectorCast(unsigned Opcode,MVT FromVT,MVT ToVT,const X86Subtarget & Subtarget)18905 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
18906                           const X86Subtarget &Subtarget) {
18907   switch (Opcode) {
18908     case ISD::SINT_TO_FP:
18909       // TODO: Handle wider types with AVX/AVX512.
18910       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
18911         return false;
18912       // CVTDQ2PS or (V)CVTDQ2PD
18913       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
18914 
18915     case ISD::UINT_TO_FP:
18916       // TODO: Handle wider types and i64 elements.
18917       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
18918         return false;
18919       // VCVTUDQ2PS or VCVTUDQ2PD
18920       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
18921 
18922     default:
18923       return false;
18924   }
18925 }
18926 
18927 /// Given a scalar cast operation that is extracted from a vector, try to
18928 /// vectorize the cast op followed by extraction. This will avoid an expensive
18929 /// round-trip between XMM and GPR.
vectorizeExtractedCast(SDValue Cast,SelectionDAG & DAG,const X86Subtarget & Subtarget)18930 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
18931                                       const X86Subtarget &Subtarget) {
18932   // TODO: This could be enhanced to handle smaller integer types by peeking
18933   // through an extend.
18934   SDValue Extract = Cast.getOperand(0);
18935   MVT DestVT = Cast.getSimpleValueType();
18936   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
18937       !isa<ConstantSDNode>(Extract.getOperand(1)))
18938     return SDValue();
18939 
18940   // See if we have a 128-bit vector cast op for this type of cast.
18941   SDValue VecOp = Extract.getOperand(0);
18942   MVT FromVT = VecOp.getSimpleValueType();
18943   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
18944   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
18945   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
18946   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
18947     return SDValue();
18948 
18949   // If we are extracting from a non-zero element, first shuffle the source
18950   // vector to allow extracting from element zero.
18951   SDLoc DL(Cast);
18952   if (!isNullConstant(Extract.getOperand(1))) {
18953     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
18954     Mask[0] = Extract.getConstantOperandVal(1);
18955     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
18956   }
18957   // If the source vector is wider than 128-bits, extract the low part. Do not
18958   // create an unnecessarily wide vector cast op.
18959   if (FromVT != Vec128VT)
18960     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
18961 
18962   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
18963   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
18964   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
18965   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
18966                      DAG.getIntPtrConstant(0, DL));
18967 }
18968 
18969 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
18970 /// try to vectorize the cast ops. This will avoid an expensive round-trip
18971 /// between XMM and GPR.
lowerFPToIntToFP(SDValue CastToFP,SelectionDAG & DAG,const X86Subtarget & Subtarget)18972 static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
18973                                 const X86Subtarget &Subtarget) {
18974   // TODO: Allow FP_TO_UINT.
18975   SDValue CastToInt = CastToFP.getOperand(0);
18976   MVT VT = CastToFP.getSimpleValueType();
18977   if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
18978     return SDValue();
18979 
18980   MVT IntVT = CastToInt.getSimpleValueType();
18981   SDValue X = CastToInt.getOperand(0);
18982   MVT SrcVT = X.getSimpleValueType();
18983   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
18984     return SDValue();
18985 
18986   // See if we have 128-bit vector cast instructions for this type of cast.
18987   // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
18988   if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
18989       IntVT != MVT::i32)
18990     return SDValue();
18991 
18992   unsigned SrcSize = SrcVT.getSizeInBits();
18993   unsigned IntSize = IntVT.getSizeInBits();
18994   unsigned VTSize = VT.getSizeInBits();
18995   MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
18996   MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
18997   MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
18998 
18999   // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
19000   unsigned ToIntOpcode =
19001       SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
19002   unsigned ToFPOpcode =
19003       IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
19004 
19005   // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
19006   //
19007   // We are not defining the high elements (for example, zero them) because
19008   // that could nullify any performance advantage that we hoped to gain from
19009   // this vector op hack. We do not expect any adverse effects (like denorm
19010   // penalties) with cast ops.
19011   SDLoc DL(CastToFP);
19012   SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
19013   SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
19014   SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
19015   SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
19016   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
19017 }
19018 
lowerINT_TO_FP_vXi64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19019 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
19020                                     const X86Subtarget &Subtarget) {
19021   SDLoc DL(Op);
19022   bool IsStrict = Op->isStrictFPOpcode();
19023   MVT VT = Op->getSimpleValueType(0);
19024   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
19025 
19026   if (Subtarget.hasDQI()) {
19027     assert(!Subtarget.hasVLX() && "Unexpected features");
19028 
19029     assert((Src.getSimpleValueType() == MVT::v2i64 ||
19030             Src.getSimpleValueType() == MVT::v4i64) &&
19031            "Unsupported custom type");
19032 
19033     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
19034     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
19035            "Unexpected VT!");
19036     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
19037 
19038     // Need to concat with zero vector for strict fp to avoid spurious
19039     // exceptions.
19040     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
19041                            : DAG.getUNDEF(MVT::v8i64);
19042     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
19043                       DAG.getIntPtrConstant(0, DL));
19044     SDValue Res, Chain;
19045     if (IsStrict) {
19046       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
19047                         {Op->getOperand(0), Src});
19048       Chain = Res.getValue(1);
19049     } else {
19050       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
19051     }
19052 
19053     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19054                       DAG.getIntPtrConstant(0, DL));
19055 
19056     if (IsStrict)
19057       return DAG.getMergeValues({Res, Chain}, DL);
19058     return Res;
19059   }
19060 
19061   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
19062                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
19063   if (VT != MVT::v4f32 || IsSigned)
19064     return SDValue();
19065 
19066   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
19067   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
19068   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
19069                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
19070                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
19071   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
19072   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
19073   SmallVector<SDValue, 4> SignCvts(4);
19074   SmallVector<SDValue, 4> Chains(4);
19075   for (int i = 0; i != 4; ++i) {
19076     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
19077                               DAG.getIntPtrConstant(i, DL));
19078     if (IsStrict) {
19079       SignCvts[i] =
19080           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
19081                       {Op.getOperand(0), Elt});
19082       Chains[i] = SignCvts[i].getValue(1);
19083     } else {
19084       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
19085     }
19086   }
19087   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
19088 
19089   SDValue Slow, Chain;
19090   if (IsStrict) {
19091     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19092     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
19093                        {Chain, SignCvt, SignCvt});
19094     Chain = Slow.getValue(1);
19095   } else {
19096     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
19097   }
19098 
19099   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
19100   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
19101 
19102   if (IsStrict)
19103     return DAG.getMergeValues({Cvt, Chain}, DL);
19104 
19105   return Cvt;
19106 }
19107 
promoteXINT_TO_FP(SDValue Op,SelectionDAG & DAG)19108 static SDValue promoteXINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
19109   bool IsStrict = Op->isStrictFPOpcode();
19110   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
19111   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
19112   MVT VT = Op.getSimpleValueType();
19113   MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
19114   SDLoc dl(Op);
19115 
19116   SDValue Rnd = DAG.getIntPtrConstant(0, dl);
19117   if (IsStrict)
19118     return DAG.getNode(
19119         ISD::STRICT_FP_ROUND, dl, {VT, MVT::Other},
19120         {Chain,
19121          DAG.getNode(Op.getOpcode(), dl, {NVT, MVT::Other}, {Chain, Src}),
19122          Rnd});
19123   return DAG.getNode(ISD::FP_ROUND, dl, VT,
19124                      DAG.getNode(Op.getOpcode(), dl, NVT, Src), Rnd);
19125 }
19126 
isLegalConversion(MVT VT,bool IsSigned,const X86Subtarget & Subtarget)19127 static bool isLegalConversion(MVT VT, bool IsSigned,
19128                               const X86Subtarget &Subtarget) {
19129   if (VT == MVT::v4i32 && Subtarget.hasSSE2() && IsSigned)
19130     return true;
19131   if (VT == MVT::v8i32 && Subtarget.hasAVX() && IsSigned)
19132     return true;
19133   if (Subtarget.hasVLX() && (VT == MVT::v4i32 || VT == MVT::v8i32))
19134     return true;
19135   if (Subtarget.useAVX512Regs()) {
19136     if (VT == MVT::v16i32)
19137       return true;
19138     if (VT == MVT::v8i64 && Subtarget.hasDQI())
19139       return true;
19140   }
19141   if (Subtarget.hasDQI() && Subtarget.hasVLX() &&
19142       (VT == MVT::v2i64 || VT == MVT::v4i64))
19143     return true;
19144   return false;
19145 }
19146 
LowerSINT_TO_FP(SDValue Op,SelectionDAG & DAG) const19147 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
19148                                            SelectionDAG &DAG) const {
19149   bool IsStrict = Op->isStrictFPOpcode();
19150   unsigned OpNo = IsStrict ? 1 : 0;
19151   SDValue Src = Op.getOperand(OpNo);
19152   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
19153   MVT SrcVT = Src.getSimpleValueType();
19154   MVT VT = Op.getSimpleValueType();
19155   SDLoc dl(Op);
19156 
19157   if (isSoftF16(VT, Subtarget))
19158     return promoteXINT_TO_FP(Op, DAG);
19159   else if (isLegalConversion(SrcVT, true, Subtarget))
19160     return Op;
19161 
19162   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
19163     return LowerWin64_INT128_TO_FP(Op, DAG);
19164 
19165   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
19166     return Extract;
19167 
19168   if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
19169     return R;
19170 
19171   if (SrcVT.isVector()) {
19172     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
19173       // Note: Since v2f64 is a legal type. We don't need to zero extend the
19174       // source for strict FP.
19175       if (IsStrict)
19176         return DAG.getNode(
19177             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
19178             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19179                                 DAG.getUNDEF(SrcVT))});
19180       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
19181                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19182                                      DAG.getUNDEF(SrcVT)));
19183     }
19184     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
19185       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
19186 
19187     return SDValue();
19188   }
19189 
19190   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
19191          "Unknown SINT_TO_FP to lower!");
19192 
19193   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
19194 
19195   // These are really Legal; return the operand so the caller accepts it as
19196   // Legal.
19197   if (SrcVT == MVT::i32 && UseSSEReg)
19198     return Op;
19199   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
19200     return Op;
19201 
19202   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
19203     return V;
19204   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
19205     return V;
19206 
19207   // SSE doesn't have an i16 conversion so we need to promote.
19208   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
19209     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
19210     if (IsStrict)
19211       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
19212                          {Chain, Ext});
19213 
19214     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
19215   }
19216 
19217   if (VT == MVT::f128 || !Subtarget.hasX87())
19218     return SDValue();
19219 
19220   SDValue ValueToStore = Src;
19221   if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
19222     // Bitcasting to f64 here allows us to do a single 64-bit store from
19223     // an SSE register, avoiding the store forwarding penalty that would come
19224     // with two 32-bit stores.
19225     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19226 
19227   unsigned Size = SrcVT.getStoreSize();
19228   Align Alignment(Size);
19229   MachineFunction &MF = DAG.getMachineFunction();
19230   auto PtrVT = getPointerTy(MF.getDataLayout());
19231   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
19232   MachinePointerInfo MPI =
19233       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
19234   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19235   Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
19236   std::pair<SDValue, SDValue> Tmp =
19237       BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
19238 
19239   if (IsStrict)
19240     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19241 
19242   return Tmp.first;
19243 }
19244 
BuildFILD(EVT DstVT,EVT SrcVT,const SDLoc & DL,SDValue Chain,SDValue Pointer,MachinePointerInfo PtrInfo,Align Alignment,SelectionDAG & DAG) const19245 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
19246     EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
19247     MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
19248   // Build the FILD
19249   SDVTList Tys;
19250   bool useSSE = isScalarFPTypeInSSEReg(DstVT);
19251   if (useSSE)
19252     Tys = DAG.getVTList(MVT::f80, MVT::Other);
19253   else
19254     Tys = DAG.getVTList(DstVT, MVT::Other);
19255 
19256   SDValue FILDOps[] = {Chain, Pointer};
19257   SDValue Result =
19258       DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
19259                               Alignment, MachineMemOperand::MOLoad);
19260   Chain = Result.getValue(1);
19261 
19262   if (useSSE) {
19263     MachineFunction &MF = DAG.getMachineFunction();
19264     unsigned SSFISize = DstVT.getStoreSize();
19265     int SSFI =
19266         MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
19267     auto PtrVT = getPointerTy(MF.getDataLayout());
19268     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19269     Tys = DAG.getVTList(MVT::Other);
19270     SDValue FSTOps[] = {Chain, Result, StackSlot};
19271     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
19272         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
19273         MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
19274 
19275     Chain =
19276         DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
19277     Result = DAG.getLoad(
19278         DstVT, DL, Chain, StackSlot,
19279         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
19280     Chain = Result.getValue(1);
19281   }
19282 
19283   return { Result, Chain };
19284 }
19285 
19286 /// Horizontal vector math instructions may be slower than normal math with
19287 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
19288 /// implementation, and likely shuffle complexity of the alternate sequence.
shouldUseHorizontalOp(bool IsSingleSource,SelectionDAG & DAG,const X86Subtarget & Subtarget)19289 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
19290                                   const X86Subtarget &Subtarget) {
19291   bool IsOptimizingSize = DAG.shouldOptForSize();
19292   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
19293   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
19294 }
19295 
19296 /// 64-bit unsigned integer to double expansion.
LowerUINT_TO_FP_i64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19297 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
19298                                    const X86Subtarget &Subtarget) {
19299   // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
19300   // when converting 0 when rounding toward negative infinity. Caller will
19301   // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
19302   assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
19303   // This algorithm is not obvious. Here it is what we're trying to output:
19304   /*
19305      movq       %rax,  %xmm0
19306      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
19307      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
19308      #ifdef __SSE3__
19309        haddpd   %xmm0, %xmm0
19310      #else
19311        pshufd   $0x4e, %xmm0, %xmm1
19312        addpd    %xmm1, %xmm0
19313      #endif
19314   */
19315 
19316   SDLoc dl(Op);
19317   LLVMContext *Context = DAG.getContext();
19318 
19319   // Build some magic constants.
19320   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
19321   Constant *C0 = ConstantDataVector::get(*Context, CV0);
19322   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19323   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
19324 
19325   SmallVector<Constant*,2> CV1;
19326   CV1.push_back(
19327     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
19328                                       APInt(64, 0x4330000000000000ULL))));
19329   CV1.push_back(
19330     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
19331                                       APInt(64, 0x4530000000000000ULL))));
19332   Constant *C1 = ConstantVector::get(CV1);
19333   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
19334 
19335   // Load the 64-bit value into an XMM register.
19336   SDValue XR1 =
19337       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
19338   SDValue CLod0 = DAG.getLoad(
19339       MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
19340       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
19341   SDValue Unpck1 =
19342       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
19343 
19344   SDValue CLod1 = DAG.getLoad(
19345       MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
19346       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
19347   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
19348   // TODO: Are there any fast-math-flags to propagate here?
19349   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
19350   SDValue Result;
19351 
19352   if (Subtarget.hasSSE3() &&
19353       shouldUseHorizontalOp(true, DAG, Subtarget)) {
19354     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
19355   } else {
19356     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
19357     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
19358   }
19359   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
19360                        DAG.getIntPtrConstant(0, dl));
19361   return Result;
19362 }
19363 
19364 /// 32-bit unsigned integer to float expansion.
LowerUINT_TO_FP_i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19365 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
19366                                    const X86Subtarget &Subtarget) {
19367   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19368   SDLoc dl(Op);
19369   // FP constant to bias correct the final result.
19370   SDValue Bias = DAG.getConstantFP(
19371       llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::f64);
19372 
19373   // Load the 32-bit value into an XMM register.
19374   SDValue Load =
19375       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
19376 
19377   // Zero out the upper parts of the register.
19378   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
19379 
19380   // Or the load with the bias.
19381   SDValue Or = DAG.getNode(
19382       ISD::OR, dl, MVT::v2i64,
19383       DAG.getBitcast(MVT::v2i64, Load),
19384       DAG.getBitcast(MVT::v2i64,
19385                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
19386   Or =
19387       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
19388                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
19389 
19390   if (Op.getNode()->isStrictFPOpcode()) {
19391     // Subtract the bias.
19392     // TODO: Are there any fast-math-flags to propagate here?
19393     SDValue Chain = Op.getOperand(0);
19394     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
19395                               {Chain, Or, Bias});
19396 
19397     if (Op.getValueType() == Sub.getValueType())
19398       return Sub;
19399 
19400     // Handle final rounding.
19401     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
19402         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
19403 
19404     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
19405   }
19406 
19407   // Subtract the bias.
19408   // TODO: Are there any fast-math-flags to propagate here?
19409   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
19410 
19411   // Handle final rounding.
19412   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
19413 }
19414 
lowerUINT_TO_FP_v2i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)19415 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
19416                                      const X86Subtarget &Subtarget,
19417                                      const SDLoc &DL) {
19418   if (Op.getSimpleValueType() != MVT::v2f64)
19419     return SDValue();
19420 
19421   bool IsStrict = Op->isStrictFPOpcode();
19422 
19423   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
19424   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
19425 
19426   if (Subtarget.hasAVX512()) {
19427     if (!Subtarget.hasVLX()) {
19428       // Let generic type legalization widen this.
19429       if (!IsStrict)
19430         return SDValue();
19431       // Otherwise pad the integer input with 0s and widen the operation.
19432       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19433                        DAG.getConstant(0, DL, MVT::v2i32));
19434       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
19435                                 {Op.getOperand(0), N0});
19436       SDValue Chain = Res.getValue(1);
19437       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
19438                         DAG.getIntPtrConstant(0, DL));
19439       return DAG.getMergeValues({Res, Chain}, DL);
19440     }
19441 
19442     // Legalize to v4i32 type.
19443     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19444                      DAG.getUNDEF(MVT::v2i32));
19445     if (IsStrict)
19446       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
19447                          {Op.getOperand(0), N0});
19448     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
19449   }
19450 
19451   // Zero extend to 2i64, OR with the floating point representation of 2^52.
19452   // This gives us the floating point equivalent of 2^52 + the i32 integer
19453   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
19454   // point leaving just our i32 integers in double format.
19455   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
19456   SDValue VBias = DAG.getConstantFP(
19457       llvm::bit_cast<double>(0x4330000000000000ULL), DL, MVT::v2f64);
19458   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
19459                            DAG.getBitcast(MVT::v2i64, VBias));
19460   Or = DAG.getBitcast(MVT::v2f64, Or);
19461 
19462   if (IsStrict)
19463     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
19464                        {Op.getOperand(0), Or, VBias});
19465   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
19466 }
19467 
lowerUINT_TO_FP_vXi32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19468 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
19469                                      const X86Subtarget &Subtarget) {
19470   SDLoc DL(Op);
19471   bool IsStrict = Op->isStrictFPOpcode();
19472   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
19473   MVT VecIntVT = V.getSimpleValueType();
19474   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
19475          "Unsupported custom type");
19476 
19477   if (Subtarget.hasAVX512()) {
19478     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
19479     assert(!Subtarget.hasVLX() && "Unexpected features");
19480     MVT VT = Op->getSimpleValueType(0);
19481 
19482     // v8i32->v8f64 is legal with AVX512 so just return it.
19483     if (VT == MVT::v8f64)
19484       return Op;
19485 
19486     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
19487            "Unexpected VT!");
19488     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
19489     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
19490     // Need to concat with zero vector for strict fp to avoid spurious
19491     // exceptions.
19492     SDValue Tmp =
19493         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
19494     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
19495                     DAG.getIntPtrConstant(0, DL));
19496     SDValue Res, Chain;
19497     if (IsStrict) {
19498       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
19499                         {Op->getOperand(0), V});
19500       Chain = Res.getValue(1);
19501     } else {
19502       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
19503     }
19504 
19505     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19506                       DAG.getIntPtrConstant(0, DL));
19507 
19508     if (IsStrict)
19509       return DAG.getMergeValues({Res, Chain}, DL);
19510     return Res;
19511   }
19512 
19513   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
19514       Op->getSimpleValueType(0) == MVT::v4f64) {
19515     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
19516     Constant *Bias = ConstantFP::get(
19517         *DAG.getContext(),
19518         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
19519     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19520     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
19521     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
19522     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
19523     SDValue VBias = DAG.getMemIntrinsicNode(
19524         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
19525         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
19526         MachineMemOperand::MOLoad);
19527 
19528     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
19529                              DAG.getBitcast(MVT::v4i64, VBias));
19530     Or = DAG.getBitcast(MVT::v4f64, Or);
19531 
19532     if (IsStrict)
19533       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
19534                          {Op.getOperand(0), Or, VBias});
19535     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
19536   }
19537 
19538   // The algorithm is the following:
19539   // #ifdef __SSE4_1__
19540   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
19541   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
19542   //                                 (uint4) 0x53000000, 0xaa);
19543   // #else
19544   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
19545   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
19546   // #endif
19547   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
19548   //     return (float4) lo + fhi;
19549 
19550   bool Is128 = VecIntVT == MVT::v4i32;
19551   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
19552   // If we convert to something else than the supported type, e.g., to v4f64,
19553   // abort early.
19554   if (VecFloatVT != Op->getSimpleValueType(0))
19555     return SDValue();
19556 
19557   // In the #idef/#else code, we have in common:
19558   // - The vector of constants:
19559   // -- 0x4b000000
19560   // -- 0x53000000
19561   // - A shift:
19562   // -- v >> 16
19563 
19564   // Create the splat vector for 0x4b000000.
19565   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
19566   // Create the splat vector for 0x53000000.
19567   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
19568 
19569   // Create the right shift.
19570   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
19571   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
19572 
19573   SDValue Low, High;
19574   if (Subtarget.hasSSE41()) {
19575     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
19576     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
19577     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
19578     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
19579     // Low will be bitcasted right away, so do not bother bitcasting back to its
19580     // original type.
19581     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
19582                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
19583     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
19584     //                                 (uint4) 0x53000000, 0xaa);
19585     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
19586     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
19587     // High will be bitcasted right away, so do not bother bitcasting back to
19588     // its original type.
19589     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
19590                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
19591   } else {
19592     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
19593     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
19594     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
19595     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
19596 
19597     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
19598     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
19599   }
19600 
19601   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
19602   SDValue VecCstFSub = DAG.getConstantFP(
19603       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
19604 
19605   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
19606   // NOTE: By using fsub of a positive constant instead of fadd of a negative
19607   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
19608   // enabled. See PR24512.
19609   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
19610   // TODO: Are there any fast-math-flags to propagate here?
19611   //     (float4) lo;
19612   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
19613   //     return (float4) lo + fhi;
19614   if (IsStrict) {
19615     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
19616                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
19617     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
19618                        {FHigh.getValue(1), LowBitcast, FHigh});
19619   }
19620 
19621   SDValue FHigh =
19622       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
19623   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
19624 }
19625 
lowerUINT_TO_FP_vec(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19626 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
19627                                    const X86Subtarget &Subtarget) {
19628   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19629   SDValue N0 = Op.getOperand(OpNo);
19630   MVT SrcVT = N0.getSimpleValueType();
19631   SDLoc dl(Op);
19632 
19633   switch (SrcVT.SimpleTy) {
19634   default:
19635     llvm_unreachable("Custom UINT_TO_FP is not supported!");
19636   case MVT::v2i32:
19637     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
19638   case MVT::v4i32:
19639   case MVT::v8i32:
19640     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
19641   case MVT::v2i64:
19642   case MVT::v4i64:
19643     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
19644   }
19645 }
19646 
LowerUINT_TO_FP(SDValue Op,SelectionDAG & DAG) const19647 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
19648                                            SelectionDAG &DAG) const {
19649   bool IsStrict = Op->isStrictFPOpcode();
19650   unsigned OpNo = IsStrict ? 1 : 0;
19651   SDValue Src = Op.getOperand(OpNo);
19652   SDLoc dl(Op);
19653   auto PtrVT = getPointerTy(DAG.getDataLayout());
19654   MVT SrcVT = Src.getSimpleValueType();
19655   MVT DstVT = Op->getSimpleValueType(0);
19656   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
19657 
19658   // Bail out when we don't have native conversion instructions.
19659   if (DstVT == MVT::f128)
19660     return SDValue();
19661 
19662   if (isSoftF16(DstVT, Subtarget))
19663     return promoteXINT_TO_FP(Op, DAG);
19664   else if (isLegalConversion(SrcVT, false, Subtarget))
19665     return Op;
19666 
19667   if (DstVT.isVector())
19668     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
19669 
19670   if (Subtarget.isTargetWin64() && SrcVT == MVT::i128)
19671     return LowerWin64_INT128_TO_FP(Op, DAG);
19672 
19673   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
19674     return Extract;
19675 
19676   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
19677       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
19678     // Conversions from unsigned i32 to f32/f64 are legal,
19679     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
19680     return Op;
19681   }
19682 
19683   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
19684   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
19685     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
19686     if (IsStrict)
19687       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
19688                          {Chain, Src});
19689     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
19690   }
19691 
19692   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
19693     return V;
19694   if (SDValue V = LowerI64IntToFP16(Op, DAG, Subtarget))
19695     return V;
19696 
19697   // The transform for i64->f64 isn't correct for 0 when rounding to negative
19698   // infinity. It produces -0.0, so disable under strictfp.
19699   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && Subtarget.hasSSE2() &&
19700       !IsStrict)
19701     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
19702   // The transform for i32->f64/f32 isn't correct for 0 when rounding to
19703   // negative infinity. So disable under strictfp. Using FILD instead.
19704   if (SrcVT == MVT::i32 && Subtarget.hasSSE2() && DstVT != MVT::f80 &&
19705       !IsStrict)
19706     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
19707   if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
19708       (DstVT == MVT::f32 || DstVT == MVT::f64))
19709     return SDValue();
19710 
19711   // Make a 64-bit buffer, and use it to build an FILD.
19712   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
19713   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
19714   Align SlotAlign(8);
19715   MachinePointerInfo MPI =
19716     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
19717   if (SrcVT == MVT::i32) {
19718     SDValue OffsetSlot =
19719         DAG.getMemBasePlusOffset(StackSlot, TypeSize::getFixed(4), dl);
19720     SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
19721     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
19722                                   OffsetSlot, MPI.getWithOffset(4), SlotAlign);
19723     std::pair<SDValue, SDValue> Tmp =
19724         BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
19725     if (IsStrict)
19726       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19727 
19728     return Tmp.first;
19729   }
19730 
19731   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
19732   SDValue ValueToStore = Src;
19733   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
19734     // Bitcasting to f64 here allows us to do a single 64-bit store from
19735     // an SSE register, avoiding the store forwarding penalty that would come
19736     // with two 32-bit stores.
19737     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19738   }
19739   SDValue Store =
19740       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
19741   // For i64 source, we need to add the appropriate power of 2 if the input
19742   // was negative. We must be careful to do the computation in x87 extended
19743   // precision, not in SSE.
19744   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
19745   SDValue Ops[] = { Store, StackSlot };
19746   SDValue Fild =
19747       DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
19748                               SlotAlign, MachineMemOperand::MOLoad);
19749   Chain = Fild.getValue(1);
19750 
19751 
19752   // Check whether the sign bit is set.
19753   SDValue SignSet = DAG.getSetCC(
19754       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
19755       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
19756 
19757   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
19758   APInt FF(64, 0x5F80000000000000ULL);
19759   SDValue FudgePtr = DAG.getConstantPool(
19760       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
19761   Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
19762 
19763   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
19764   SDValue Zero = DAG.getIntPtrConstant(0, dl);
19765   SDValue Four = DAG.getIntPtrConstant(4, dl);
19766   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
19767   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
19768 
19769   // Load the value out, extending it from f32 to f80.
19770   SDValue Fudge = DAG.getExtLoad(
19771       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
19772       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
19773       CPAlignment);
19774   Chain = Fudge.getValue(1);
19775   // Extend everything to 80 bits to force it to be done on x87.
19776   // TODO: Are there any fast-math-flags to propagate here?
19777   if (IsStrict) {
19778     unsigned Opc = ISD::STRICT_FADD;
19779     // Windows needs the precision control changed to 80bits around this add.
19780     if (Subtarget.isOSWindows() && DstVT == MVT::f32)
19781       Opc = X86ISD::STRICT_FP80_ADD;
19782 
19783     SDValue Add =
19784         DAG.getNode(Opc, dl, {MVT::f80, MVT::Other}, {Chain, Fild, Fudge});
19785     // STRICT_FP_ROUND can't handle equal types.
19786     if (DstVT == MVT::f80)
19787       return Add;
19788     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
19789                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
19790   }
19791   unsigned Opc = ISD::FADD;
19792   // Windows needs the precision control changed to 80bits around this add.
19793   if (Subtarget.isOSWindows() && DstVT == MVT::f32)
19794     Opc = X86ISD::FP80_ADD;
19795 
19796   SDValue Add = DAG.getNode(Opc, dl, MVT::f80, Fild, Fudge);
19797   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
19798                      DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
19799 }
19800 
19801 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
19802 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
19803 // just return an SDValue().
19804 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
19805 // to i16, i32 or i64, and we lower it to a legal sequence and return the
19806 // result.
19807 SDValue
FP_TO_INTHelper(SDValue Op,SelectionDAG & DAG,bool IsSigned,SDValue & Chain) const19808 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
19809                                    bool IsSigned, SDValue &Chain) const {
19810   bool IsStrict = Op->isStrictFPOpcode();
19811   SDLoc DL(Op);
19812 
19813   EVT DstTy = Op.getValueType();
19814   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
19815   EVT TheVT = Value.getValueType();
19816   auto PtrVT = getPointerTy(DAG.getDataLayout());
19817 
19818   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
19819     // f16 must be promoted before using the lowering in this routine.
19820     // fp128 does not use this lowering.
19821     return SDValue();
19822   }
19823 
19824   // If using FIST to compute an unsigned i64, we'll need some fixup
19825   // to handle values above the maximum signed i64.  A FIST is always
19826   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
19827   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
19828 
19829   // FIXME: This does not generate an invalid exception if the input does not
19830   // fit in i32. PR44019
19831   if (!IsSigned && DstTy != MVT::i64) {
19832     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
19833     // The low 32 bits of the fist result will have the correct uint32 result.
19834     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
19835     DstTy = MVT::i64;
19836   }
19837 
19838   assert(DstTy.getSimpleVT() <= MVT::i64 &&
19839          DstTy.getSimpleVT() >= MVT::i16 &&
19840          "Unknown FP_TO_INT to lower!");
19841 
19842   // We lower FP->int64 into FISTP64 followed by a load from a temporary
19843   // stack slot.
19844   MachineFunction &MF = DAG.getMachineFunction();
19845   unsigned MemSize = DstTy.getStoreSize();
19846   int SSFI =
19847       MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
19848   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19849 
19850   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
19851 
19852   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
19853 
19854   if (UnsignedFixup) {
19855     //
19856     // Conversion to unsigned i64 is implemented with a select,
19857     // depending on whether the source value fits in the range
19858     // of a signed i64.  Let Thresh be the FP equivalent of
19859     // 0x8000000000000000ULL.
19860     //
19861     //  Adjust = (Value >= Thresh) ? 0x80000000 : 0;
19862     //  FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
19863     //  FistSrc = (Value - FltOfs);
19864     //  Fist-to-mem64 FistSrc
19865     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
19866     //  to XOR'ing the high 32 bits with Adjust.
19867     //
19868     // Being a power of 2, Thresh is exactly representable in all FP formats.
19869     // For X87 we'd like to use the smallest FP type for this constant, but
19870     // for DAG type consistency we have to match the FP operand type.
19871 
19872     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
19873     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
19874     bool LosesInfo = false;
19875     if (TheVT == MVT::f64)
19876       // The rounding mode is irrelevant as the conversion should be exact.
19877       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
19878                               &LosesInfo);
19879     else if (TheVT == MVT::f80)
19880       Status = Thresh.convert(APFloat::x87DoubleExtended(),
19881                               APFloat::rmNearestTiesToEven, &LosesInfo);
19882 
19883     assert(Status == APFloat::opOK && !LosesInfo &&
19884            "FP conversion should have been exact");
19885 
19886     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
19887 
19888     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
19889                                    *DAG.getContext(), TheVT);
19890     SDValue Cmp;
19891     if (IsStrict) {
19892       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
19893                          /*IsSignaling*/ true);
19894       Chain = Cmp.getValue(1);
19895     } else {
19896       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
19897     }
19898 
19899     // Our preferred lowering of
19900     //
19901     // (Value >= Thresh) ? 0x8000000000000000ULL : 0
19902     //
19903     // is
19904     //
19905     // (Value >= Thresh) << 63
19906     //
19907     // but since we can get here after LegalOperations, DAGCombine might do the
19908     // wrong thing if we create a select. So, directly create the preferred
19909     // version.
19910     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
19911     SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
19912     Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
19913 
19914     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
19915                                    DAG.getConstantFP(0.0, DL, TheVT));
19916 
19917     if (IsStrict) {
19918       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
19919                           { Chain, Value, FltOfs });
19920       Chain = Value.getValue(1);
19921     } else
19922       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
19923   }
19924 
19925   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
19926 
19927   // FIXME This causes a redundant load/store if the SSE-class value is already
19928   // in memory, such as if it is on the callstack.
19929   if (isScalarFPTypeInSSEReg(TheVT)) {
19930     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
19931     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
19932     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
19933     SDValue Ops[] = { Chain, StackSlot };
19934 
19935     unsigned FLDSize = TheVT.getStoreSize();
19936     assert(FLDSize <= MemSize && "Stack slot not big enough");
19937     MachineMemOperand *MMO = MF.getMachineMemOperand(
19938         MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
19939     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
19940     Chain = Value.getValue(1);
19941   }
19942 
19943   // Build the FP_TO_INT*_IN_MEM
19944   MachineMemOperand *MMO = MF.getMachineMemOperand(
19945       MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
19946   SDValue Ops[] = { Chain, Value, StackSlot };
19947   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
19948                                          DAG.getVTList(MVT::Other),
19949                                          Ops, DstTy, MMO);
19950 
19951   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
19952   Chain = Res.getValue(1);
19953 
19954   // If we need an unsigned fixup, XOR the result with adjust.
19955   if (UnsignedFixup)
19956     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
19957 
19958   return Res;
19959 }
19960 
LowerAVXExtend(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19961 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
19962                               const X86Subtarget &Subtarget) {
19963   MVT VT = Op.getSimpleValueType();
19964   SDValue In = Op.getOperand(0);
19965   MVT InVT = In.getSimpleValueType();
19966   SDLoc dl(Op);
19967   unsigned Opc = Op.getOpcode();
19968 
19969   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
19970   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
19971          "Unexpected extension opcode");
19972   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
19973          "Expected same number of elements");
19974   assert((VT.getVectorElementType() == MVT::i16 ||
19975           VT.getVectorElementType() == MVT::i32 ||
19976           VT.getVectorElementType() == MVT::i64) &&
19977          "Unexpected element type");
19978   assert((InVT.getVectorElementType() == MVT::i8 ||
19979           InVT.getVectorElementType() == MVT::i16 ||
19980           InVT.getVectorElementType() == MVT::i32) &&
19981          "Unexpected element type");
19982 
19983   unsigned ExtendInVecOpc = DAG.getOpcode_EXTEND_VECTOR_INREG(Opc);
19984 
19985   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
19986     assert(InVT == MVT::v32i8 && "Unexpected VT!");
19987     return splitVectorIntUnary(Op, DAG);
19988   }
19989 
19990   if (Subtarget.hasInt256())
19991     return Op;
19992 
19993   // Optimize vectors in AVX mode:
19994   //
19995   //   v8i16 -> v8i32
19996   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
19997   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
19998   //   Concat upper and lower parts.
19999   //
20000   //   v4i32 -> v4i64
20001   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
20002   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
20003   //   Concat upper and lower parts.
20004   //
20005   MVT HalfVT = VT.getHalfNumVectorElementsVT();
20006   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
20007 
20008   // Short-circuit if we can determine that each 128-bit half is the same value.
20009   // Otherwise, this is difficult to match and optimize.
20010   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
20011     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
20012       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
20013 
20014   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
20015   SDValue Undef = DAG.getUNDEF(InVT);
20016   bool NeedZero = Opc == ISD::ZERO_EXTEND;
20017   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
20018   OpHi = DAG.getBitcast(HalfVT, OpHi);
20019 
20020   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
20021 }
20022 
20023 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
SplitAndExtendv16i1(unsigned ExtOpc,MVT VT,SDValue In,const SDLoc & dl,SelectionDAG & DAG)20024 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
20025                                    const SDLoc &dl, SelectionDAG &DAG) {
20026   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
20027   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20028                            DAG.getIntPtrConstant(0, dl));
20029   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20030                            DAG.getIntPtrConstant(8, dl));
20031   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
20032   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
20033   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
20034   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20035 }
20036 
LowerZERO_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20037 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
20038                                       const X86Subtarget &Subtarget,
20039                                       SelectionDAG &DAG) {
20040   MVT VT = Op->getSimpleValueType(0);
20041   SDValue In = Op->getOperand(0);
20042   MVT InVT = In.getSimpleValueType();
20043   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
20044   SDLoc DL(Op);
20045   unsigned NumElts = VT.getVectorNumElements();
20046 
20047   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
20048   // avoids a constant pool load.
20049   if (VT.getVectorElementType() != MVT::i8) {
20050     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
20051     return DAG.getNode(ISD::SRL, DL, VT, Extend,
20052                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
20053   }
20054 
20055   // Extend VT if BWI is not supported.
20056   MVT ExtVT = VT;
20057   if (!Subtarget.hasBWI()) {
20058     // If v16i32 is to be avoided, we'll need to split and concatenate.
20059     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20060       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
20061 
20062     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20063   }
20064 
20065   // Widen to 512-bits if VLX is not supported.
20066   MVT WideVT = ExtVT;
20067   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20068     NumElts *= 512 / ExtVT.getSizeInBits();
20069     InVT = MVT::getVectorVT(MVT::i1, NumElts);
20070     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
20071                      In, DAG.getIntPtrConstant(0, DL));
20072     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
20073                               NumElts);
20074   }
20075 
20076   SDValue One = DAG.getConstant(1, DL, WideVT);
20077   SDValue Zero = DAG.getConstant(0, DL, WideVT);
20078 
20079   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
20080 
20081   // Truncate if we had to extend above.
20082   if (VT != ExtVT) {
20083     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
20084     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
20085   }
20086 
20087   // Extract back to 128/256-bit if we widened.
20088   if (WideVT != VT)
20089     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
20090                               DAG.getIntPtrConstant(0, DL));
20091 
20092   return SelectedVal;
20093 }
20094 
LowerZERO_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20095 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20096                                 SelectionDAG &DAG) {
20097   SDValue In = Op.getOperand(0);
20098   MVT SVT = In.getSimpleValueType();
20099 
20100   if (SVT.getVectorElementType() == MVT::i1)
20101     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
20102 
20103   assert(Subtarget.hasAVX() && "Expected AVX support");
20104   return LowerAVXExtend(Op, DAG, Subtarget);
20105 }
20106 
20107 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
20108 /// It makes use of the fact that vectors with enough leading sign/zero bits
20109 /// prevent the PACKSS/PACKUS from saturating the results.
20110 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
20111 /// within each 128-bit lane.
truncateVectorWithPACK(unsigned Opcode,EVT DstVT,SDValue In,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)20112 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
20113                                       const SDLoc &DL, SelectionDAG &DAG,
20114                                       const X86Subtarget &Subtarget) {
20115   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
20116          "Unexpected PACK opcode");
20117   assert(DstVT.isVector() && "VT not a vector?");
20118 
20119   // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
20120   if (!Subtarget.hasSSE2())
20121     return SDValue();
20122 
20123   EVT SrcVT = In.getValueType();
20124 
20125   // No truncation required, we might get here due to recursive calls.
20126   if (SrcVT == DstVT)
20127     return In;
20128 
20129   unsigned NumElems = SrcVT.getVectorNumElements();
20130   if (NumElems < 2 || !isPowerOf2_32(NumElems) )
20131     return SDValue();
20132 
20133   unsigned DstSizeInBits = DstVT.getSizeInBits();
20134   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
20135   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
20136   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
20137 
20138   LLVMContext &Ctx = *DAG.getContext();
20139   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
20140   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
20141 
20142   // Pack to the largest type possible:
20143   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
20144   EVT InVT = MVT::i16, OutVT = MVT::i8;
20145   if (SrcVT.getScalarSizeInBits() > 16 &&
20146       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
20147     InVT = MVT::i32;
20148     OutVT = MVT::i16;
20149   }
20150 
20151   // Sub-128-bit truncation - widen to 128-bit src and pack in the lower half.
20152   // On pre-AVX512, pack the src in both halves to help value tracking.
20153   if (SrcSizeInBits <= 128) {
20154     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
20155     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
20156     In = widenSubVector(In, false, Subtarget, DAG, DL, 128);
20157     SDValue LHS = DAG.getBitcast(InVT, In);
20158     SDValue RHS = Subtarget.hasAVX512() ? DAG.getUNDEF(InVT) : LHS;
20159     SDValue Res = DAG.getNode(Opcode, DL, OutVT, LHS, RHS);
20160     Res = extractSubVector(Res, 0, DAG, DL, SrcSizeInBits / 2);
20161     Res = DAG.getBitcast(PackedVT, Res);
20162     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20163   }
20164 
20165   // Split lower/upper subvectors.
20166   SDValue Lo, Hi;
20167   std::tie(Lo, Hi) = splitVector(In, DAG, DL);
20168 
20169   // If Hi is undef, then don't bother packing it and widen the result instead.
20170   if (Hi.isUndef()) {
20171     EVT DstHalfVT = DstVT.getHalfNumVectorElementsVT(Ctx);
20172     if (SDValue Res =
20173             truncateVectorWithPACK(Opcode, DstHalfVT, Lo, DL, DAG, Subtarget))
20174       return widenSubVector(Res, false, Subtarget, DAG, DL, DstSizeInBits);
20175   }
20176 
20177   unsigned SubSizeInBits = SrcSizeInBits / 2;
20178   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
20179   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
20180 
20181   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
20182   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
20183     Lo = DAG.getBitcast(InVT, Lo);
20184     Hi = DAG.getBitcast(InVT, Hi);
20185     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20186     return DAG.getBitcast(DstVT, Res);
20187   }
20188 
20189   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
20190   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
20191   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
20192     Lo = DAG.getBitcast(InVT, Lo);
20193     Hi = DAG.getBitcast(InVT, Hi);
20194     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20195 
20196     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
20197     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
20198     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
20199     SmallVector<int, 64> Mask;
20200     int Scale = 64 / OutVT.getScalarSizeInBits();
20201     narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
20202     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
20203 
20204     if (DstVT.is256BitVector())
20205       return DAG.getBitcast(DstVT, Res);
20206 
20207     // If 512bit -> 128bit truncate another stage.
20208     Res = DAG.getBitcast(PackedVT, Res);
20209     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20210   }
20211 
20212   // Recursively pack lower/upper subvectors, concat result and pack again.
20213   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
20214 
20215   if (PackedVT.is128BitVector()) {
20216     // Avoid CONCAT_VECTORS on sub-128bit nodes as these can fail after
20217     // type legalization.
20218     SDValue Res =
20219         truncateVectorWithPACK(Opcode, PackedVT, In, DL, DAG, Subtarget);
20220     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20221   }
20222 
20223   EVT HalfPackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
20224   Lo = truncateVectorWithPACK(Opcode, HalfPackedVT, Lo, DL, DAG, Subtarget);
20225   Hi = truncateVectorWithPACK(Opcode, HalfPackedVT, Hi, DL, DAG, Subtarget);
20226   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
20227   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20228 }
20229 
20230 /// Truncate using inreg zero extension (AND mask) and X86ISD::PACKUS.
20231 /// e.g. trunc <8 x i32> X to <8 x i16> -->
20232 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
20233 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
truncateVectorWithPACKUS(EVT DstVT,SDValue In,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)20234 static SDValue truncateVectorWithPACKUS(EVT DstVT, SDValue In, const SDLoc &DL,
20235                                         const X86Subtarget &Subtarget,
20236                                         SelectionDAG &DAG) {
20237   In = DAG.getZeroExtendInReg(In, DL, DstVT);
20238   return truncateVectorWithPACK(X86ISD::PACKUS, DstVT, In, DL, DAG, Subtarget);
20239 }
20240 
20241 /// Truncate using inreg sign extension and X86ISD::PACKSS.
truncateVectorWithPACKSS(EVT DstVT,SDValue In,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)20242 static SDValue truncateVectorWithPACKSS(EVT DstVT, SDValue In, const SDLoc &DL,
20243                                         const X86Subtarget &Subtarget,
20244                                         SelectionDAG &DAG) {
20245   EVT SrcVT = In.getValueType();
20246   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, SrcVT, In,
20247                    DAG.getValueType(DstVT));
20248   return truncateVectorWithPACK(X86ISD::PACKSS, DstVT, In, DL, DAG, Subtarget);
20249 }
20250 
20251 /// Helper to determine if \p In truncated to \p DstVT has the necessary
20252 /// signbits / leading zero bits to be truncated with PACKSS / PACKUS,
20253 /// possibly by converting a SRL node to SRA for sign extension.
matchTruncateWithPACK(unsigned & PackOpcode,EVT DstVT,SDValue In,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)20254 static SDValue matchTruncateWithPACK(unsigned &PackOpcode, EVT DstVT,
20255                                      SDValue In, const SDLoc &DL,
20256                                      SelectionDAG &DAG,
20257                                      const X86Subtarget &Subtarget) {
20258   // Requires SSE2.
20259   if (!Subtarget.hasSSE2())
20260     return SDValue();
20261 
20262   EVT SrcVT = In.getValueType();
20263   EVT DstSVT = DstVT.getVectorElementType();
20264   EVT SrcSVT = SrcVT.getVectorElementType();
20265 
20266   // Check we have a truncation suited for PACKSS/PACKUS.
20267   if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
20268         (DstSVT == MVT::i8 || DstSVT == MVT::i16 || DstSVT == MVT::i32)))
20269     return SDValue();
20270 
20271   assert(SrcSVT.getSizeInBits() > DstSVT.getSizeInBits() && "Bad truncation");
20272   unsigned NumStages = Log2_32(SrcSVT.getSizeInBits() / DstSVT.getSizeInBits());
20273 
20274   // Truncation from 128-bit to vXi32 can be better handled with PSHUFD.
20275   // Truncation to sub-64-bit vXi16 can be better handled with PSHUFD/PSHUFLW.
20276   // Truncation from v2i64 to v2i8 can be better handled with PSHUFB.
20277   if ((DstSVT == MVT::i32 && SrcVT.getSizeInBits() <= 128) ||
20278       (DstSVT == MVT::i16 && SrcVT.getSizeInBits() <= (64 * NumStages)) ||
20279       (DstVT == MVT::v2i8 && SrcVT == MVT::v2i64 && Subtarget.hasSSSE3()))
20280     return SDValue();
20281 
20282   // Prefer to lower v4i64 -> v4i32 as a shuffle unless we can cheaply
20283   // split this for packing.
20284   if (SrcVT == MVT::v4i64 && DstVT == MVT::v4i32 &&
20285       !isFreeToSplitVector(In.getNode(), DAG) &&
20286       (!Subtarget.hasAVX() || DAG.ComputeNumSignBits(In) != 64))
20287     return SDValue();
20288 
20289   // Don't truncate AVX512 targets as multiple PACK nodes stages.
20290   if (Subtarget.hasAVX512() && NumStages > 1)
20291     return SDValue();
20292 
20293   unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
20294   unsigned NumPackedSignBits = std::min<unsigned>(DstSVT.getSizeInBits(), 16);
20295   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
20296 
20297   // Truncate with PACKUS if we are truncating a vector with leading zero
20298   // bits that extend all the way to the packed/truncated value.
20299   // e.g. Masks, zext_in_reg, etc.
20300   // Pre-SSE41 we can only use PACKUSWB.
20301   KnownBits Known = DAG.computeKnownBits(In);
20302   if ((NumSrcEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros()) {
20303     PackOpcode = X86ISD::PACKUS;
20304     return In;
20305   }
20306 
20307   // Truncate with PACKSS if we are truncating a vector with sign-bits
20308   // that extend all the way to the packed/truncated value.
20309   // e.g. Comparison result, sext_in_reg, etc.
20310   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
20311 
20312   // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
20313   // a sign splat (or AVX512 VPSRAQ support). ComputeNumSignBits struggles to
20314   // see through BITCASTs later on and combines/simplifications can't then use
20315   // it.
20316   if (DstSVT == MVT::i32 && NumSignBits != SrcSVT.getSizeInBits() &&
20317       !Subtarget.hasAVX512())
20318     return SDValue();
20319 
20320   unsigned MinSignBits = NumSrcEltBits - NumPackedSignBits;
20321   if (MinSignBits < NumSignBits) {
20322     PackOpcode = X86ISD::PACKSS;
20323     return In;
20324   }
20325 
20326   // If we have a srl that only generates signbits that we will discard in
20327   // the truncation then we can use PACKSS by converting the srl to a sra.
20328   // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
20329   if (In.getOpcode() == ISD::SRL && In->hasOneUse())
20330     if (const APInt *ShAmt = DAG.getValidShiftAmountConstant(
20331             In, APInt::getAllOnes(SrcVT.getVectorNumElements()))) {
20332       if (*ShAmt == MinSignBits) {
20333         PackOpcode = X86ISD::PACKSS;
20334         return DAG.getNode(ISD::SRA, DL, SrcVT, In->ops());
20335       }
20336     }
20337 
20338   return SDValue();
20339 }
20340 
20341 /// This function lowers a vector truncation of 'extended sign-bits' or
20342 /// 'extended zero-bits' values.
20343 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
LowerTruncateVecPackWithSignBits(MVT DstVT,SDValue In,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)20344 static SDValue LowerTruncateVecPackWithSignBits(MVT DstVT, SDValue In,
20345                                                 const SDLoc &DL,
20346                                                 const X86Subtarget &Subtarget,
20347                                                 SelectionDAG &DAG) {
20348   MVT SrcVT = In.getSimpleValueType();
20349   MVT DstSVT = DstVT.getVectorElementType();
20350   MVT SrcSVT = SrcVT.getVectorElementType();
20351   if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
20352         (DstSVT == MVT::i8 || DstSVT == MVT::i16 || DstSVT == MVT::i32)))
20353     return SDValue();
20354 
20355   // If the upper half of the source is undef, then attempt to split and
20356   // only truncate the lower half.
20357   if (DstVT.getSizeInBits() >= 128) {
20358     SmallVector<SDValue> LowerOps;
20359     if (SDValue Lo = isUpperSubvectorUndef(In, DL, DAG)) {
20360       MVT DstHalfVT = DstVT.getHalfNumVectorElementsVT();
20361       if (SDValue Res = LowerTruncateVecPackWithSignBits(DstHalfVT, Lo, DL,
20362                                                          Subtarget, DAG))
20363         return widenSubVector(Res, false, Subtarget, DAG, DL,
20364                               DstVT.getSizeInBits());
20365     }
20366   }
20367 
20368   unsigned PackOpcode;
20369   if (SDValue Src =
20370           matchTruncateWithPACK(PackOpcode, DstVT, In, DL, DAG, Subtarget))
20371     return truncateVectorWithPACK(PackOpcode, DstVT, Src, DL, DAG, Subtarget);
20372 
20373   return SDValue();
20374 }
20375 
20376 /// This function lowers a vector truncation from vXi32/vXi64 to vXi8/vXi16 into
20377 /// X86ISD::PACKUS/X86ISD::PACKSS operations.
LowerTruncateVecPack(MVT DstVT,SDValue In,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)20378 static SDValue LowerTruncateVecPack(MVT DstVT, SDValue In, const SDLoc &DL,
20379                                     const X86Subtarget &Subtarget,
20380                                     SelectionDAG &DAG) {
20381   MVT SrcVT = In.getSimpleValueType();
20382   MVT DstSVT = DstVT.getVectorElementType();
20383   MVT SrcSVT = SrcVT.getVectorElementType();
20384   unsigned NumElems = DstVT.getVectorNumElements();
20385   if (!((SrcSVT == MVT::i16 || SrcSVT == MVT::i32 || SrcSVT == MVT::i64) &&
20386         (DstSVT == MVT::i8 || DstSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
20387         NumElems >= 8))
20388     return SDValue();
20389 
20390   // SSSE3's pshufb results in less instructions in the cases below.
20391   if (Subtarget.hasSSSE3() && NumElems == 8) {
20392     if (SrcSVT == MVT::i16)
20393       return SDValue();
20394     if (SrcSVT == MVT::i32 && (DstSVT == MVT::i8 || !Subtarget.hasSSE41()))
20395       return SDValue();
20396   }
20397 
20398   // If the upper half of the source is undef, then attempt to split and
20399   // only truncate the lower half.
20400   if (DstVT.getSizeInBits() >= 128) {
20401     SmallVector<SDValue> LowerOps;
20402     if (SDValue Lo = isUpperSubvectorUndef(In, DL, DAG)) {
20403       MVT DstHalfVT = DstVT.getHalfNumVectorElementsVT();
20404       if (SDValue Res = LowerTruncateVecPack(DstHalfVT, Lo, DL, Subtarget, DAG))
20405         return widenSubVector(Res, false, Subtarget, DAG, DL,
20406                               DstVT.getSizeInBits());
20407     }
20408   }
20409 
20410   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
20411   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
20412   // truncate 2 x v4i32 to v8i16.
20413   if (Subtarget.hasSSE41() || DstSVT == MVT::i8)
20414     return truncateVectorWithPACKUS(DstVT, In, DL, Subtarget, DAG);
20415 
20416   if (SrcSVT == MVT::i16 || SrcSVT == MVT::i32)
20417     return truncateVectorWithPACKSS(DstVT, In, DL, Subtarget, DAG);
20418 
20419   // Special case vXi64 -> vXi16, shuffle to vXi32 and then use PACKSS.
20420   if (DstSVT == MVT::i16 && SrcSVT == MVT::i64) {
20421     MVT TruncVT = MVT::getVectorVT(MVT::i32, NumElems);
20422     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, In);
20423     return truncateVectorWithPACKSS(DstVT, Trunc, DL, Subtarget, DAG);
20424   }
20425 
20426   return SDValue();
20427 }
20428 
LowerTruncateVecI1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)20429 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
20430                                   const X86Subtarget &Subtarget) {
20431 
20432   SDLoc DL(Op);
20433   MVT VT = Op.getSimpleValueType();
20434   SDValue In = Op.getOperand(0);
20435   MVT InVT = In.getSimpleValueType();
20436 
20437   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
20438 
20439   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
20440   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
20441   if (InVT.getScalarSizeInBits() <= 16) {
20442     if (Subtarget.hasBWI()) {
20443       // legal, will go to VPMOVB2M, VPMOVW2M
20444       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20445         // We need to shift to get the lsb into sign position.
20446         // Shift packed bytes not supported natively, bitcast to word
20447         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
20448         In = DAG.getNode(ISD::SHL, DL, ExtVT,
20449                          DAG.getBitcast(ExtVT, In),
20450                          DAG.getConstant(ShiftInx, DL, ExtVT));
20451         In = DAG.getBitcast(InVT, In);
20452       }
20453       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
20454                           In, ISD::SETGT);
20455     }
20456     // Use TESTD/Q, extended vector to packed dword/qword.
20457     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
20458            "Unexpected vector type.");
20459     unsigned NumElts = InVT.getVectorNumElements();
20460     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
20461     // We need to change to a wider element type that we have support for.
20462     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
20463     // For 16 element vectors we extend to v16i32 unless we are explicitly
20464     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
20465     // we need to split into two 8 element vectors which we can extend to v8i32,
20466     // truncate and concat the results. There's an additional complication if
20467     // the original type is v16i8. In that case we can't split the v16i8
20468     // directly, so we need to shuffle high elements to low and use
20469     // sign_extend_vector_inreg.
20470     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
20471       SDValue Lo, Hi;
20472       if (InVT == MVT::v16i8) {
20473         Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
20474         Hi = DAG.getVectorShuffle(
20475             InVT, DL, In, In,
20476             {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
20477         Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
20478       } else {
20479         assert(InVT == MVT::v16i16 && "Unexpected VT!");
20480         Lo = extract128BitVector(In, 0, DAG, DL);
20481         Hi = extract128BitVector(In, 8, DAG, DL);
20482       }
20483       // We're split now, just emit two truncates and a concat. The two
20484       // truncates will trigger legalization to come back to this function.
20485       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
20486       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
20487       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20488     }
20489     // We either have 8 elements or we're allowed to use 512-bit vectors.
20490     // If we have VLX, we want to use the narrowest vector that can get the
20491     // job done so we use vXi32.
20492     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
20493     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
20494     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
20495     InVT = ExtVT;
20496     ShiftInx = InVT.getScalarSizeInBits() - 1;
20497   }
20498 
20499   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20500     // We need to shift to get the lsb into sign position.
20501     In = DAG.getNode(ISD::SHL, DL, InVT, In,
20502                      DAG.getConstant(ShiftInx, DL, InVT));
20503   }
20504   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
20505   if (Subtarget.hasDQI())
20506     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
20507   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
20508 }
20509 
LowerTRUNCATE(SDValue Op,SelectionDAG & DAG) const20510 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
20511   SDLoc DL(Op);
20512   MVT VT = Op.getSimpleValueType();
20513   SDValue In = Op.getOperand(0);
20514   MVT InVT = In.getSimpleValueType();
20515   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
20516          "Invalid TRUNCATE operation");
20517 
20518   // If we're called by the type legalizer, handle a few cases.
20519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20520   if (!TLI.isTypeLegal(VT) || !TLI.isTypeLegal(InVT)) {
20521     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
20522         VT.is128BitVector() && Subtarget.hasAVX512()) {
20523       assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
20524              "Unexpected subtarget!");
20525       // The default behavior is to truncate one step, concatenate, and then
20526       // truncate the remainder. We'd rather produce two 64-bit results and
20527       // concatenate those.
20528       SDValue Lo, Hi;
20529       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
20530 
20531       EVT LoVT, HiVT;
20532       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
20533 
20534       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
20535       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
20536       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20537     }
20538 
20539     // Pre-AVX512 (or prefer-256bit) see if we can make use of PACKSS/PACKUS.
20540     if (!Subtarget.hasAVX512() ||
20541         (InVT.is512BitVector() && VT.is256BitVector()))
20542       if (SDValue SignPack =
20543               LowerTruncateVecPackWithSignBits(VT, In, DL, Subtarget, DAG))
20544         return SignPack;
20545 
20546     // Pre-AVX512 see if we can make use of PACKSS/PACKUS.
20547     if (!Subtarget.hasAVX512())
20548       return LowerTruncateVecPack(VT, In, DL, Subtarget, DAG);
20549 
20550     // Otherwise let default legalization handle it.
20551     return SDValue();
20552   }
20553 
20554   if (VT.getVectorElementType() == MVT::i1)
20555     return LowerTruncateVecI1(Op, DAG, Subtarget);
20556 
20557   // Attempt to truncate with PACKUS/PACKSS even on AVX512 if we'd have to
20558   // concat from subvectors to use VPTRUNC etc.
20559   if (!Subtarget.hasAVX512() || isFreeToSplitVector(In.getNode(), DAG))
20560     if (SDValue SignPack =
20561             LowerTruncateVecPackWithSignBits(VT, In, DL, Subtarget, DAG))
20562       return SignPack;
20563 
20564   // vpmovqb/w/d, vpmovdb/w, vpmovwb
20565   if (Subtarget.hasAVX512()) {
20566     if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
20567       assert(VT == MVT::v32i8 && "Unexpected VT!");
20568       return splitVectorIntUnary(Op, DAG);
20569     }
20570 
20571     // word to byte only under BWI. Otherwise we have to promoted to v16i32
20572     // and then truncate that. But we should only do that if we haven't been
20573     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
20574     // handled by isel patterns.
20575     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
20576         Subtarget.canExtendTo512DQ())
20577       return Op;
20578   }
20579 
20580   // Handle truncation of V256 to V128 using shuffles.
20581   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
20582 
20583   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
20584     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
20585     if (Subtarget.hasInt256()) {
20586       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
20587       In = DAG.getBitcast(MVT::v8i32, In);
20588       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
20589       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
20590                          DAG.getIntPtrConstant(0, DL));
20591     }
20592 
20593     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20594                                DAG.getIntPtrConstant(0, DL));
20595     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20596                                DAG.getIntPtrConstant(2, DL));
20597     static const int ShufMask[] = {0, 2, 4, 6};
20598     return DAG.getVectorShuffle(VT, DL, DAG.getBitcast(MVT::v4i32, OpLo),
20599                                 DAG.getBitcast(MVT::v4i32, OpHi), ShufMask);
20600   }
20601 
20602   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
20603     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
20604     if (Subtarget.hasInt256()) {
20605       // The PSHUFB mask:
20606       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
20607                                       -1, -1, -1, -1, -1, -1, -1, -1,
20608                                       16, 17, 20, 21, 24, 25, 28, 29,
20609                                       -1, -1, -1, -1, -1, -1, -1, -1 };
20610       In = DAG.getBitcast(MVT::v32i8, In);
20611       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
20612       In = DAG.getBitcast(MVT::v4i64, In);
20613 
20614       static const int ShufMask2[] = {0, 2, -1, -1};
20615       In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
20616       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20617                        DAG.getIntPtrConstant(0, DL));
20618       return DAG.getBitcast(MVT::v8i16, In);
20619     }
20620 
20621     return Subtarget.hasSSE41()
20622                ? truncateVectorWithPACKUS(VT, In, DL, Subtarget, DAG)
20623                : truncateVectorWithPACKSS(VT, In, DL, Subtarget, DAG);
20624   }
20625 
20626   if (VT == MVT::v16i8 && InVT == MVT::v16i16)
20627     return truncateVectorWithPACKUS(VT, In, DL, Subtarget, DAG);
20628 
20629   llvm_unreachable("All 256->128 cases should have been handled above!");
20630 }
20631 
20632 // We can leverage the specific way the "cvttps2dq/cvttpd2dq" instruction
20633 // behaves on out of range inputs to generate optimized conversions.
expandFP_TO_UINT_SSE(MVT VT,SDValue Src,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)20634 static SDValue expandFP_TO_UINT_SSE(MVT VT, SDValue Src, const SDLoc &dl,
20635                                     SelectionDAG &DAG,
20636                                     const X86Subtarget &Subtarget) {
20637   MVT SrcVT = Src.getSimpleValueType();
20638   unsigned DstBits = VT.getScalarSizeInBits();
20639   assert(DstBits == 32 && "expandFP_TO_UINT_SSE - only vXi32 supported");
20640 
20641   // Calculate the converted result for values in the range 0 to
20642   // 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
20643   SDValue Small = DAG.getNode(X86ISD::CVTTP2SI, dl, VT, Src);
20644   SDValue Big =
20645       DAG.getNode(X86ISD::CVTTP2SI, dl, VT,
20646                   DAG.getNode(ISD::FSUB, dl, SrcVT, Src,
20647                               DAG.getConstantFP(2147483648.0f, dl, SrcVT)));
20648 
20649   // The "CVTTP2SI" instruction conveniently sets the sign bit if
20650   // and only if the value was out of range. So we can use that
20651   // as our indicator that we rather use "Big" instead of "Small".
20652   //
20653   // Use "Small" if "IsOverflown" has all bits cleared
20654   // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
20655 
20656   // AVX1 can't use the signsplat masking for 256-bit vectors - we have to
20657   // use the slightly slower blendv select instead.
20658   if (VT == MVT::v8i32 && !Subtarget.hasAVX2()) {
20659     SDValue Overflow = DAG.getNode(ISD::OR, dl, VT, Small, Big);
20660     return DAG.getNode(X86ISD::BLENDV, dl, VT, Small, Overflow, Small);
20661   }
20662 
20663   SDValue IsOverflown =
20664       DAG.getNode(X86ISD::VSRAI, dl, VT, Small,
20665                   DAG.getTargetConstant(DstBits - 1, dl, MVT::i8));
20666   return DAG.getNode(ISD::OR, dl, VT, Small,
20667                      DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
20668 }
20669 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const20670 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
20671   bool IsStrict = Op->isStrictFPOpcode();
20672   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
20673                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
20674   MVT VT = Op->getSimpleValueType(0);
20675   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20676   SDValue Chain = IsStrict ? Op->getOperand(0) : SDValue();
20677   MVT SrcVT = Src.getSimpleValueType();
20678   SDLoc dl(Op);
20679 
20680   SDValue Res;
20681   if (isSoftF16(SrcVT, Subtarget)) {
20682     MVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
20683     if (IsStrict)
20684       return DAG.getNode(Op.getOpcode(), dl, {VT, MVT::Other},
20685                          {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
20686                                              {NVT, MVT::Other}, {Chain, Src})});
20687     return DAG.getNode(Op.getOpcode(), dl, VT,
20688                        DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
20689   } else if (isTypeLegal(SrcVT) && isLegalConversion(VT, IsSigned, Subtarget)) {
20690     return Op;
20691   }
20692 
20693   if (VT.isVector()) {
20694     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
20695       MVT ResVT = MVT::v4i32;
20696       MVT TruncVT = MVT::v4i1;
20697       unsigned Opc;
20698       if (IsStrict)
20699         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
20700       else
20701         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
20702 
20703       if (!IsSigned && !Subtarget.hasVLX()) {
20704         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
20705         // Widen to 512-bits.
20706         ResVT = MVT::v8i32;
20707         TruncVT = MVT::v8i1;
20708         Opc = Op.getOpcode();
20709         // Need to concat with zero vector for strict fp to avoid spurious
20710         // exceptions.
20711         // TODO: Should we just do this for non-strict as well?
20712         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
20713                                : DAG.getUNDEF(MVT::v8f64);
20714         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
20715                           DAG.getIntPtrConstant(0, dl));
20716       }
20717       if (IsStrict) {
20718         Res = DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Chain, Src});
20719         Chain = Res.getValue(1);
20720       } else {
20721         Res = DAG.getNode(Opc, dl, ResVT, Src);
20722       }
20723 
20724       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
20725       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
20726                         DAG.getIntPtrConstant(0, dl));
20727       if (IsStrict)
20728         return DAG.getMergeValues({Res, Chain}, dl);
20729       return Res;
20730     }
20731 
20732     if (Subtarget.hasFP16() && SrcVT.getVectorElementType() == MVT::f16) {
20733       if (VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16)
20734         return Op;
20735 
20736       MVT ResVT = VT;
20737       MVT EleVT = VT.getVectorElementType();
20738       if (EleVT != MVT::i64)
20739         ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
20740 
20741       if (SrcVT != MVT::v8f16) {
20742         SDValue Tmp =
20743             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
20744         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
20745         Ops[0] = Src;
20746         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
20747       }
20748 
20749       if (IsStrict) {
20750         Res = DAG.getNode(IsSigned ? X86ISD::STRICT_CVTTP2SI
20751                                    : X86ISD::STRICT_CVTTP2UI,
20752                           dl, {ResVT, MVT::Other}, {Chain, Src});
20753         Chain = Res.getValue(1);
20754       } else {
20755         Res = DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl,
20756                           ResVT, Src);
20757       }
20758 
20759       // TODO: Need to add exception check code for strict FP.
20760       if (EleVT.getSizeInBits() < 16) {
20761         ResVT = MVT::getVectorVT(EleVT, 8);
20762         Res = DAG.getNode(ISD::TRUNCATE, dl, ResVT, Res);
20763       }
20764 
20765       if (ResVT != VT)
20766         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20767                           DAG.getIntPtrConstant(0, dl));
20768 
20769       if (IsStrict)
20770         return DAG.getMergeValues({Res, Chain}, dl);
20771       return Res;
20772     }
20773 
20774     // v8f32/v16f32/v8f64->v8i16/v16i16 need to widen first.
20775     if (VT.getVectorElementType() == MVT::i16) {
20776       assert((SrcVT.getVectorElementType() == MVT::f32 ||
20777               SrcVT.getVectorElementType() == MVT::f64) &&
20778              "Expected f32/f64 vector!");
20779       MVT NVT = VT.changeVectorElementType(MVT::i32);
20780       if (IsStrict) {
20781         Res = DAG.getNode(IsSigned ? ISD::STRICT_FP_TO_SINT
20782                                    : ISD::STRICT_FP_TO_UINT,
20783                           dl, {NVT, MVT::Other}, {Chain, Src});
20784         Chain = Res.getValue(1);
20785       } else {
20786         Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl,
20787                           NVT, Src);
20788       }
20789 
20790       // TODO: Need to add exception check code for strict FP.
20791       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20792 
20793       if (IsStrict)
20794         return DAG.getMergeValues({Res, Chain}, dl);
20795       return Res;
20796     }
20797 
20798     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
20799     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
20800       assert(!IsSigned && "Expected unsigned conversion!");
20801       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
20802       return Op;
20803     }
20804 
20805     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
20806     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
20807         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32) &&
20808         Subtarget.useAVX512Regs()) {
20809       assert(!IsSigned && "Expected unsigned conversion!");
20810       assert(!Subtarget.hasVLX() && "Unexpected features!");
20811       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
20812       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
20813       // Need to concat with zero vector for strict fp to avoid spurious
20814       // exceptions.
20815       // TODO: Should we just do this for non-strict as well?
20816       SDValue Tmp =
20817           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
20818       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
20819                         DAG.getIntPtrConstant(0, dl));
20820 
20821       if (IsStrict) {
20822         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
20823                           {Chain, Src});
20824         Chain = Res.getValue(1);
20825       } else {
20826         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
20827       }
20828 
20829       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20830                         DAG.getIntPtrConstant(0, dl));
20831 
20832       if (IsStrict)
20833         return DAG.getMergeValues({Res, Chain}, dl);
20834       return Res;
20835     }
20836 
20837     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
20838     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
20839         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32) &&
20840         Subtarget.useAVX512Regs() && Subtarget.hasDQI()) {
20841       assert(!Subtarget.hasVLX() && "Unexpected features!");
20842       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20843       // Need to concat with zero vector for strict fp to avoid spurious
20844       // exceptions.
20845       // TODO: Should we just do this for non-strict as well?
20846       SDValue Tmp =
20847           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
20848       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
20849                         DAG.getIntPtrConstant(0, dl));
20850 
20851       if (IsStrict) {
20852         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
20853                           {Chain, Src});
20854         Chain = Res.getValue(1);
20855       } else {
20856         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
20857       }
20858 
20859       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20860                         DAG.getIntPtrConstant(0, dl));
20861 
20862       if (IsStrict)
20863         return DAG.getMergeValues({Res, Chain}, dl);
20864       return Res;
20865     }
20866 
20867     if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
20868       if (!Subtarget.hasVLX()) {
20869         // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
20870         // legalizer and then widened again by vector op legalization.
20871         if (!IsStrict)
20872           return SDValue();
20873 
20874         SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
20875         SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
20876                                   {Src, Zero, Zero, Zero});
20877         Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
20878                           {Chain, Tmp});
20879         SDValue Chain = Tmp.getValue(1);
20880         Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
20881                           DAG.getIntPtrConstant(0, dl));
20882         return DAG.getMergeValues({Tmp, Chain}, dl);
20883       }
20884 
20885       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
20886       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
20887                                 DAG.getUNDEF(MVT::v2f32));
20888       if (IsStrict) {
20889         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
20890                                 : X86ISD::STRICT_CVTTP2UI;
20891         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
20892       }
20893       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
20894       return DAG.getNode(Opc, dl, VT, Tmp);
20895     }
20896 
20897     // Generate optimized instructions for pre AVX512 unsigned conversions from
20898     // vXf32 to vXi32.
20899     if ((VT == MVT::v4i32 && SrcVT == MVT::v4f32) ||
20900         (VT == MVT::v4i32 && SrcVT == MVT::v4f64) ||
20901         (VT == MVT::v8i32 && SrcVT == MVT::v8f32)) {
20902       assert(!IsSigned && "Expected unsigned conversion!");
20903       return expandFP_TO_UINT_SSE(VT, Src, dl, DAG, Subtarget);
20904     }
20905 
20906     return SDValue();
20907   }
20908 
20909   assert(!VT.isVector());
20910 
20911   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
20912 
20913   if (!IsSigned && UseSSEReg) {
20914     // Conversions from f32/f64 with AVX512 should be legal.
20915     if (Subtarget.hasAVX512())
20916       return Op;
20917 
20918     // We can leverage the specific way the "cvttss2si/cvttsd2si" instruction
20919     // behaves on out of range inputs to generate optimized conversions.
20920     if (!IsStrict && ((VT == MVT::i32 && !Subtarget.is64Bit()) ||
20921                       (VT == MVT::i64 && Subtarget.is64Bit()))) {
20922       unsigned DstBits = VT.getScalarSizeInBits();
20923       APInt UIntLimit = APInt::getSignMask(DstBits);
20924       SDValue FloatOffset = DAG.getNode(ISD::UINT_TO_FP, dl, SrcVT,
20925                                         DAG.getConstant(UIntLimit, dl, VT));
20926       MVT SrcVecVT = MVT::getVectorVT(SrcVT, 128 / SrcVT.getScalarSizeInBits());
20927 
20928       // Calculate the converted result for values in the range:
20929       // (i32) 0 to 2^31-1 ("Small") and from 2^31 to 2^32-1 ("Big").
20930       // (i64) 0 to 2^63-1 ("Small") and from 2^63 to 2^64-1 ("Big").
20931       SDValue Small =
20932           DAG.getNode(X86ISD::CVTTS2SI, dl, VT,
20933                       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT, Src));
20934       SDValue Big = DAG.getNode(
20935           X86ISD::CVTTS2SI, dl, VT,
20936           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, SrcVecVT,
20937                       DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FloatOffset)));
20938 
20939       // The "CVTTS2SI" instruction conveniently sets the sign bit if
20940       // and only if the value was out of range. So we can use that
20941       // as our indicator that we rather use "Big" instead of "Small".
20942       //
20943       // Use "Small" if "IsOverflown" has all bits cleared
20944       // and "0x80000000 | Big" if all bits in "IsOverflown" are set.
20945       SDValue IsOverflown = DAG.getNode(
20946           ISD::SRA, dl, VT, Small, DAG.getConstant(DstBits - 1, dl, MVT::i8));
20947       return DAG.getNode(ISD::OR, dl, VT, Small,
20948                          DAG.getNode(ISD::AND, dl, VT, Big, IsOverflown));
20949     }
20950 
20951     // Use default expansion for i64.
20952     if (VT == MVT::i64)
20953       return SDValue();
20954 
20955     assert(VT == MVT::i32 && "Unexpected VT!");
20956 
20957     // Promote i32 to i64 and use a signed operation on 64-bit targets.
20958     // FIXME: This does not generate an invalid exception if the input does not
20959     // fit in i32. PR44019
20960     if (Subtarget.is64Bit()) {
20961       if (IsStrict) {
20962         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i64, MVT::Other},
20963                           {Chain, Src});
20964         Chain = Res.getValue(1);
20965       } else
20966         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
20967 
20968       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20969       if (IsStrict)
20970         return DAG.getMergeValues({Res, Chain}, dl);
20971       return Res;
20972     }
20973 
20974     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
20975     // use fisttp which will be handled later.
20976     if (!Subtarget.hasSSE3())
20977       return SDValue();
20978   }
20979 
20980   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
20981   // FIXME: This does not generate an invalid exception if the input does not
20982   // fit in i16. PR44019
20983   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
20984     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
20985     if (IsStrict) {
20986       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {MVT::i32, MVT::Other},
20987                         {Chain, Src});
20988       Chain = Res.getValue(1);
20989     } else
20990       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
20991 
20992     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20993     if (IsStrict)
20994       return DAG.getMergeValues({Res, Chain}, dl);
20995     return Res;
20996   }
20997 
20998   // If this is a FP_TO_SINT using SSEReg we're done.
20999   if (UseSSEReg && IsSigned)
21000     return Op;
21001 
21002   // fp128 needs to use a libcall.
21003   if (SrcVT == MVT::f128) {
21004     RTLIB::Libcall LC;
21005     if (IsSigned)
21006       LC = RTLIB::getFPTOSINT(SrcVT, VT);
21007     else
21008       LC = RTLIB::getFPTOUINT(SrcVT, VT);
21009 
21010     MakeLibCallOptions CallOptions;
21011     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
21012                                                   SDLoc(Op), Chain);
21013 
21014     if (IsStrict)
21015       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
21016 
21017     return Tmp.first;
21018   }
21019 
21020   // Fall back to X87.
21021   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
21022     if (IsStrict)
21023       return DAG.getMergeValues({V, Chain}, dl);
21024     return V;
21025   }
21026 
21027   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
21028 }
21029 
LowerLRINT_LLRINT(SDValue Op,SelectionDAG & DAG) const21030 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
21031                                              SelectionDAG &DAG) const {
21032   SDValue Src = Op.getOperand(0);
21033   MVT SrcVT = Src.getSimpleValueType();
21034 
21035   if (SrcVT == MVT::f16)
21036     return SDValue();
21037 
21038   // If the source is in an SSE register, the node is Legal.
21039   if (isScalarFPTypeInSSEReg(SrcVT))
21040     return Op;
21041 
21042   return LRINT_LLRINTHelper(Op.getNode(), DAG);
21043 }
21044 
LRINT_LLRINTHelper(SDNode * N,SelectionDAG & DAG) const21045 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
21046                                               SelectionDAG &DAG) const {
21047   EVT DstVT = N->getValueType(0);
21048   SDValue Src = N->getOperand(0);
21049   EVT SrcVT = Src.getValueType();
21050 
21051   if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
21052     // f16 must be promoted before using the lowering in this routine.
21053     // fp128 does not use this lowering.
21054     return SDValue();
21055   }
21056 
21057   SDLoc DL(N);
21058   SDValue Chain = DAG.getEntryNode();
21059 
21060   bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
21061 
21062   // If we're converting from SSE, the stack slot needs to hold both types.
21063   // Otherwise it only needs to hold the DstVT.
21064   EVT OtherVT = UseSSE ? SrcVT : DstVT;
21065   SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
21066   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
21067   MachinePointerInfo MPI =
21068       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
21069 
21070   if (UseSSE) {
21071     assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
21072     Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
21073     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21074     SDValue Ops[] = { Chain, StackPtr };
21075 
21076     Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
21077                                   /*Align*/ std::nullopt,
21078                                   MachineMemOperand::MOLoad);
21079     Chain = Src.getValue(1);
21080   }
21081 
21082   SDValue StoreOps[] = { Chain, Src, StackPtr };
21083   Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
21084                                   StoreOps, DstVT, MPI, /*Align*/ std::nullopt,
21085                                   MachineMemOperand::MOStore);
21086 
21087   return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
21088 }
21089 
21090 SDValue
LowerFP_TO_INT_SAT(SDValue Op,SelectionDAG & DAG) const21091 X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
21092   // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
21093   // but making use of X86 specifics to produce better instruction sequences.
21094   SDNode *Node = Op.getNode();
21095   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
21096   unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
21097   SDLoc dl(SDValue(Node, 0));
21098   SDValue Src = Node->getOperand(0);
21099 
21100   // There are three types involved here: SrcVT is the source floating point
21101   // type, DstVT is the type of the result, and TmpVT is the result of the
21102   // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
21103   // DstVT).
21104   EVT SrcVT = Src.getValueType();
21105   EVT DstVT = Node->getValueType(0);
21106   EVT TmpVT = DstVT;
21107 
21108   // This code is only for floats and doubles. Fall back to generic code for
21109   // anything else.
21110   if (!isScalarFPTypeInSSEReg(SrcVT) || isSoftF16(SrcVT, Subtarget))
21111     return SDValue();
21112 
21113   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
21114   unsigned SatWidth = SatVT.getScalarSizeInBits();
21115   unsigned DstWidth = DstVT.getScalarSizeInBits();
21116   unsigned TmpWidth = TmpVT.getScalarSizeInBits();
21117   assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&
21118          "Expected saturation width smaller than result width");
21119 
21120   // Promote result of FP_TO_*INT to at least 32 bits.
21121   if (TmpWidth < 32) {
21122     TmpVT = MVT::i32;
21123     TmpWidth = 32;
21124   }
21125 
21126   // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
21127   // us to use a native signed conversion instead.
21128   if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
21129     TmpVT = MVT::i64;
21130     TmpWidth = 64;
21131   }
21132 
21133   // If the saturation width is smaller than the size of the temporary result,
21134   // we can always use signed conversion, which is native.
21135   if (SatWidth < TmpWidth)
21136     FpToIntOpcode = ISD::FP_TO_SINT;
21137 
21138   // Determine minimum and maximum integer values and their corresponding
21139   // floating-point values.
21140   APInt MinInt, MaxInt;
21141   if (IsSigned) {
21142     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
21143     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
21144   } else {
21145     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
21146     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
21147   }
21148 
21149   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
21150   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
21151 
21152   APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
21153     MinInt, IsSigned, APFloat::rmTowardZero);
21154   APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
21155     MaxInt, IsSigned, APFloat::rmTowardZero);
21156   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
21157                           && !(MaxStatus & APFloat::opStatus::opInexact);
21158 
21159   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
21160   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
21161 
21162   // If the integer bounds are exactly representable as floats, emit a
21163   // min+max+fptoi sequence. Otherwise use comparisons and selects.
21164   if (AreExactFloatBounds) {
21165     if (DstVT != TmpVT) {
21166       // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
21167       SDValue MinClamped = DAG.getNode(
21168         X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
21169       // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
21170       SDValue BothClamped = DAG.getNode(
21171         X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
21172       // Convert clamped value to integer.
21173       SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
21174 
21175       // NaN will become INDVAL, with the top bit set and the rest zero.
21176       // Truncation will discard the top bit, resulting in zero.
21177       return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21178     }
21179 
21180     // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
21181     SDValue MinClamped = DAG.getNode(
21182       X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
21183     // Clamp by MaxFloat from above. NaN cannot occur.
21184     SDValue BothClamped = DAG.getNode(
21185       X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
21186     // Convert clamped value to integer.
21187     SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
21188 
21189     if (!IsSigned) {
21190       // In the unsigned case we're done, because we mapped NaN to MinFloat,
21191       // which is zero.
21192       return FpToInt;
21193     }
21194 
21195     // Otherwise, select zero if Src is NaN.
21196     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21197     return DAG.getSelectCC(
21198       dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
21199   }
21200 
21201   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
21202   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
21203 
21204   // Result of direct conversion, which may be selected away.
21205   SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
21206 
21207   if (DstVT != TmpVT) {
21208     // NaN will become INDVAL, with the top bit set and the rest zero.
21209     // Truncation will discard the top bit, resulting in zero.
21210     FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21211   }
21212 
21213   SDValue Select = FpToInt;
21214   // For signed conversions where we saturate to the same size as the
21215   // result type of the fptoi instructions, INDVAL coincides with integer
21216   // minimum, so we don't need to explicitly check it.
21217   if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
21218     // If Src ULT MinFloat, select MinInt. In particular, this also selects
21219     // MinInt if Src is NaN.
21220     Select = DAG.getSelectCC(
21221       dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
21222   }
21223 
21224   // If Src OGT MaxFloat, select MaxInt.
21225   Select = DAG.getSelectCC(
21226     dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
21227 
21228   // In the unsigned case we are done, because we mapped NaN to MinInt, which
21229   // is already zero. The promoted case was already handled above.
21230   if (!IsSigned || DstVT != TmpVT) {
21231     return Select;
21232   }
21233 
21234   // Otherwise, select 0 if Src is NaN.
21235   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21236   return DAG.getSelectCC(
21237     dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
21238 }
21239 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const21240 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
21241   bool IsStrict = Op->isStrictFPOpcode();
21242 
21243   SDLoc DL(Op);
21244   MVT VT = Op.getSimpleValueType();
21245   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21246   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21247   MVT SVT = In.getSimpleValueType();
21248 
21249   // Let f16->f80 get lowered to a libcall, except for darwin, where we should
21250   // lower it to an fp_extend via f32 (as only f16<>f32 libcalls are available)
21251   if (VT == MVT::f128 || (SVT == MVT::f16 && VT == MVT::f80 &&
21252                           !Subtarget.getTargetTriple().isOSDarwin()))
21253     return SDValue();
21254 
21255   if ((SVT == MVT::v8f16 && Subtarget.hasF16C()) ||
21256       (SVT == MVT::v16f16 && Subtarget.useAVX512Regs()))
21257     return Op;
21258 
21259   if (SVT == MVT::f16) {
21260     if (Subtarget.hasFP16())
21261       return Op;
21262 
21263     if (VT != MVT::f32) {
21264       if (IsStrict)
21265         return DAG.getNode(
21266             ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other},
21267             {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, DL,
21268                                 {MVT::f32, MVT::Other}, {Chain, In})});
21269 
21270       return DAG.getNode(ISD::FP_EXTEND, DL, VT,
21271                          DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, In));
21272     }
21273 
21274     if (!Subtarget.hasF16C()) {
21275       if (!Subtarget.getTargetTriple().isOSDarwin())
21276         return SDValue();
21277 
21278       assert(VT == MVT::f32 && SVT == MVT::f16 && "unexpected extend libcall");
21279 
21280       // Need a libcall, but ABI for f16 is soft-float on MacOS.
21281       TargetLowering::CallLoweringInfo CLI(DAG);
21282       Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21283 
21284       In = DAG.getBitcast(MVT::i16, In);
21285       TargetLowering::ArgListTy Args;
21286       TargetLowering::ArgListEntry Entry;
21287       Entry.Node = In;
21288       Entry.Ty = EVT(MVT::i16).getTypeForEVT(*DAG.getContext());
21289       Entry.IsSExt = false;
21290       Entry.IsZExt = true;
21291       Args.push_back(Entry);
21292 
21293       SDValue Callee = DAG.getExternalSymbol(
21294           getLibcallName(RTLIB::FPEXT_F16_F32),
21295           getPointerTy(DAG.getDataLayout()));
21296       CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
21297           CallingConv::C, EVT(VT).getTypeForEVT(*DAG.getContext()), Callee,
21298           std::move(Args));
21299 
21300       SDValue Res;
21301       std::tie(Res,Chain) = LowerCallTo(CLI);
21302       if (IsStrict)
21303         Res = DAG.getMergeValues({Res, Chain}, DL);
21304 
21305       return Res;
21306     }
21307 
21308     In = DAG.getBitcast(MVT::i16, In);
21309     In = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v8i16,
21310                      getZeroVector(MVT::v8i16, Subtarget, DAG, DL), In,
21311                      DAG.getIntPtrConstant(0, DL));
21312     SDValue Res;
21313     if (IsStrict) {
21314       Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, DL, {MVT::v4f32, MVT::Other},
21315                         {Chain, In});
21316       Chain = Res.getValue(1);
21317     } else {
21318       Res = DAG.getNode(X86ISD::CVTPH2PS, DL, MVT::v4f32, In,
21319                         DAG.getTargetConstant(4, DL, MVT::i32));
21320     }
21321     Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, Res,
21322                       DAG.getIntPtrConstant(0, DL));
21323     if (IsStrict)
21324       return DAG.getMergeValues({Res, Chain}, DL);
21325     return Res;
21326   }
21327 
21328   if (!SVT.isVector())
21329     return Op;
21330 
21331   if (SVT.getVectorElementType() == MVT::bf16) {
21332     // FIXME: Do we need to support strict FP?
21333     assert(!IsStrict && "Strict FP doesn't support BF16");
21334     if (VT.getVectorElementType() == MVT::f64) {
21335       MVT TmpVT = VT.changeVectorElementType(MVT::f32);
21336       return DAG.getNode(ISD::FP_EXTEND, DL, VT,
21337                          DAG.getNode(ISD::FP_EXTEND, DL, TmpVT, In));
21338     }
21339     assert(VT.getVectorElementType() == MVT::f32 && "Unexpected fpext");
21340     MVT NVT = SVT.changeVectorElementType(MVT::i32);
21341     In = DAG.getBitcast(SVT.changeTypeToInteger(), In);
21342     In = DAG.getNode(ISD::ZERO_EXTEND, DL, NVT, In);
21343     In = DAG.getNode(ISD::SHL, DL, NVT, In, DAG.getConstant(16, DL, NVT));
21344     return DAG.getBitcast(VT, In);
21345   }
21346 
21347   if (SVT.getVectorElementType() == MVT::f16) {
21348     if (Subtarget.hasFP16() && isTypeLegal(SVT))
21349       return Op;
21350     assert(Subtarget.hasF16C() && "Unexpected features!");
21351     if (SVT == MVT::v2f16)
21352       In = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f16, In,
21353                        DAG.getUNDEF(MVT::v2f16));
21354     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f16, In,
21355                               DAG.getUNDEF(MVT::v4f16));
21356     if (IsStrict)
21357       return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21358                          {Op->getOperand(0), Res});
21359     return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21360   } else if (VT == MVT::v4f64 || VT == MVT::v8f64) {
21361     return Op;
21362   }
21363 
21364   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
21365 
21366   SDValue Res =
21367       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
21368   if (IsStrict)
21369     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21370                        {Op->getOperand(0), Res});
21371   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21372 }
21373 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const21374 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21375   bool IsStrict = Op->isStrictFPOpcode();
21376 
21377   SDLoc DL(Op);
21378   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21379   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21380   MVT VT = Op.getSimpleValueType();
21381   MVT SVT = In.getSimpleValueType();
21382 
21383   if (SVT == MVT::f128 || (VT == MVT::f16 && SVT == MVT::f80))
21384     return SDValue();
21385 
21386   if (VT == MVT::f16 && (SVT == MVT::f64 || SVT == MVT::f32) &&
21387       !Subtarget.hasFP16() && (SVT == MVT::f64 || !Subtarget.hasF16C())) {
21388     if (!Subtarget.getTargetTriple().isOSDarwin())
21389       return SDValue();
21390 
21391     // We need a libcall but the ABI for f16 libcalls on MacOS is soft.
21392     TargetLowering::CallLoweringInfo CLI(DAG);
21393     Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
21394 
21395     TargetLowering::ArgListTy Args;
21396     TargetLowering::ArgListEntry Entry;
21397     Entry.Node = In;
21398     Entry.Ty = EVT(SVT).getTypeForEVT(*DAG.getContext());
21399     Entry.IsSExt = false;
21400     Entry.IsZExt = true;
21401     Args.push_back(Entry);
21402 
21403     SDValue Callee = DAG.getExternalSymbol(
21404         getLibcallName(SVT == MVT::f64 ? RTLIB::FPROUND_F64_F16
21405                                        : RTLIB::FPROUND_F32_F16),
21406         getPointerTy(DAG.getDataLayout()));
21407     CLI.setDebugLoc(DL).setChain(Chain).setLibCallee(
21408         CallingConv::C, EVT(MVT::i16).getTypeForEVT(*DAG.getContext()), Callee,
21409         std::move(Args));
21410 
21411     SDValue Res;
21412     std::tie(Res, Chain) = LowerCallTo(CLI);
21413 
21414     Res = DAG.getBitcast(MVT::f16, Res);
21415 
21416     if (IsStrict)
21417       Res = DAG.getMergeValues({Res, Chain}, DL);
21418 
21419     return Res;
21420   }
21421 
21422   if (VT.getScalarType() == MVT::bf16) {
21423     if (SVT.getScalarType() == MVT::f32 &&
21424         ((Subtarget.hasBF16() && Subtarget.hasVLX()) ||
21425          Subtarget.hasAVXNECONVERT()))
21426       return Op;
21427     return SDValue();
21428   }
21429 
21430   if (VT.getScalarType() == MVT::f16 && !Subtarget.hasFP16()) {
21431     if (!Subtarget.hasF16C() || SVT.getScalarType() != MVT::f32)
21432       return SDValue();
21433 
21434     if (VT.isVector())
21435       return Op;
21436 
21437     SDValue Res;
21438     SDValue Rnd = DAG.getTargetConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, DL,
21439                                         MVT::i32);
21440     if (IsStrict) {
21441       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4f32,
21442                         DAG.getConstantFP(0, DL, MVT::v4f32), In,
21443                         DAG.getIntPtrConstant(0, DL));
21444       Res = DAG.getNode(X86ISD::STRICT_CVTPS2PH, DL, {MVT::v8i16, MVT::Other},
21445                         {Chain, Res, Rnd});
21446       Chain = Res.getValue(1);
21447     } else {
21448       // FIXME: Should we use zeros for upper elements for non-strict?
21449       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, In);
21450       Res = DAG.getNode(X86ISD::CVTPS2PH, DL, MVT::v8i16, Res, Rnd);
21451     }
21452 
21453     Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i16, Res,
21454                       DAG.getIntPtrConstant(0, DL));
21455     Res = DAG.getBitcast(MVT::f16, Res);
21456 
21457     if (IsStrict)
21458       return DAG.getMergeValues({Res, Chain}, DL);
21459 
21460     return Res;
21461   }
21462 
21463   return Op;
21464 }
21465 
LowerFP16_TO_FP(SDValue Op,SelectionDAG & DAG)21466 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
21467   bool IsStrict = Op->isStrictFPOpcode();
21468   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21469   assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
21470          "Unexpected VT!");
21471 
21472   SDLoc dl(Op);
21473   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
21474                             DAG.getConstant(0, dl, MVT::v8i16), Src,
21475                             DAG.getIntPtrConstant(0, dl));
21476 
21477   SDValue Chain;
21478   if (IsStrict) {
21479     Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
21480                       {Op.getOperand(0), Res});
21481     Chain = Res.getValue(1);
21482   } else {
21483     Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
21484   }
21485 
21486   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
21487                     DAG.getIntPtrConstant(0, dl));
21488 
21489   if (IsStrict)
21490     return DAG.getMergeValues({Res, Chain}, dl);
21491 
21492   return Res;
21493 }
21494 
LowerFP_TO_FP16(SDValue Op,SelectionDAG & DAG)21495 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
21496   bool IsStrict = Op->isStrictFPOpcode();
21497   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21498   assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
21499          "Unexpected VT!");
21500 
21501   SDLoc dl(Op);
21502   SDValue Res, Chain;
21503   if (IsStrict) {
21504     Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
21505                       DAG.getConstantFP(0, dl, MVT::v4f32), Src,
21506                       DAG.getIntPtrConstant(0, dl));
21507     Res = DAG.getNode(
21508         X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
21509         {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
21510     Chain = Res.getValue(1);
21511   } else {
21512     // FIXME: Should we use zeros for upper elements for non-strict?
21513     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
21514     Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
21515                       DAG.getTargetConstant(4, dl, MVT::i32));
21516   }
21517 
21518   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
21519                     DAG.getIntPtrConstant(0, dl));
21520 
21521   if (IsStrict)
21522     return DAG.getMergeValues({Res, Chain}, dl);
21523 
21524   return Res;
21525 }
21526 
LowerFP_TO_BF16(SDValue Op,SelectionDAG & DAG) const21527 SDValue X86TargetLowering::LowerFP_TO_BF16(SDValue Op,
21528                                            SelectionDAG &DAG) const {
21529   SDLoc DL(Op);
21530 
21531   MVT SVT = Op.getOperand(0).getSimpleValueType();
21532   if (SVT == MVT::f32 && ((Subtarget.hasBF16() && Subtarget.hasVLX()) ||
21533                           Subtarget.hasAVXNECONVERT())) {
21534     SDValue Res;
21535     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, Op.getOperand(0));
21536     Res = DAG.getNode(X86ISD::CVTNEPS2BF16, DL, MVT::v8bf16, Res);
21537     Res = DAG.getBitcast(MVT::v8i16, Res);
21538     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i16, Res,
21539                        DAG.getIntPtrConstant(0, DL));
21540   }
21541 
21542   MakeLibCallOptions CallOptions;
21543   RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, MVT::bf16);
21544   SDValue Res =
21545       makeLibCall(DAG, LC, MVT::f16, Op.getOperand(0), CallOptions, DL).first;
21546   return DAG.getBitcast(MVT::i16, Res);
21547 }
21548 
21549 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21550 /// vector operation in place of the typical scalar operation.
lowerAddSubToHorizontalOp(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)21551 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
21552                                          const X86Subtarget &Subtarget) {
21553   // If both operands have other uses, this is probably not profitable.
21554   SDValue LHS = Op.getOperand(0);
21555   SDValue RHS = Op.getOperand(1);
21556   if (!LHS.hasOneUse() && !RHS.hasOneUse())
21557     return Op;
21558 
21559   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
21560   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
21561   if (IsFP && !Subtarget.hasSSE3())
21562     return Op;
21563   if (!IsFP && !Subtarget.hasSSSE3())
21564     return Op;
21565 
21566   // Extract from a common vector.
21567   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21568       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21569       LHS.getOperand(0) != RHS.getOperand(0) ||
21570       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
21571       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
21572       !shouldUseHorizontalOp(true, DAG, Subtarget))
21573     return Op;
21574 
21575   // Allow commuted 'hadd' ops.
21576   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
21577   unsigned HOpcode;
21578   switch (Op.getOpcode()) {
21579     case ISD::ADD: HOpcode = X86ISD::HADD; break;
21580     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
21581     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
21582     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
21583     default:
21584       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
21585   }
21586   unsigned LExtIndex = LHS.getConstantOperandVal(1);
21587   unsigned RExtIndex = RHS.getConstantOperandVal(1);
21588   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
21589       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
21590     std::swap(LExtIndex, RExtIndex);
21591 
21592   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
21593     return Op;
21594 
21595   SDValue X = LHS.getOperand(0);
21596   EVT VecVT = X.getValueType();
21597   unsigned BitWidth = VecVT.getSizeInBits();
21598   unsigned NumLanes = BitWidth / 128;
21599   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
21600   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
21601          "Not expecting illegal vector widths here");
21602 
21603   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
21604   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
21605   SDLoc DL(Op);
21606   if (BitWidth == 256 || BitWidth == 512) {
21607     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
21608     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
21609     LExtIndex %= NumEltsPerLane;
21610   }
21611 
21612   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
21613   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
21614   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
21615   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
21616   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
21617   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
21618                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
21619 }
21620 
21621 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21622 /// vector operation in place of the typical scalar operation.
lowerFaddFsub(SDValue Op,SelectionDAG & DAG) const21623 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
21624   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
21625          "Only expecting float/double");
21626   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
21627 }
21628 
21629 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
21630 /// This mode isn't supported in hardware on X86. But as long as we aren't
21631 /// compiling with trapping math, we can emulate this with
21632 /// trunc(X + copysign(nextafter(0.5, 0.0), X)).
LowerFROUND(SDValue Op,SelectionDAG & DAG)21633 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
21634   SDValue N0 = Op.getOperand(0);
21635   SDLoc dl(Op);
21636   MVT VT = Op.getSimpleValueType();
21637 
21638   // N0 += copysign(nextafter(0.5, 0.0), N0)
21639   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21640   bool Ignored;
21641   APFloat Point5Pred = APFloat(0.5f);
21642   Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
21643   Point5Pred.next(/*nextDown*/true);
21644 
21645   SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
21646                               DAG.getConstantFP(Point5Pred, dl, VT), N0);
21647   N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
21648 
21649   // Truncate the result to remove fraction.
21650   return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
21651 }
21652 
21653 /// The only differences between FABS and FNEG are the mask and the logic op.
21654 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
LowerFABSorFNEG(SDValue Op,SelectionDAG & DAG)21655 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
21656   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
21657          "Wrong opcode for lowering FABS or FNEG.");
21658 
21659   bool IsFABS = (Op.getOpcode() == ISD::FABS);
21660 
21661   // If this is a FABS and it has an FNEG user, bail out to fold the combination
21662   // into an FNABS. We'll lower the FABS after that if it is still in use.
21663   if (IsFABS)
21664     for (SDNode *User : Op->uses())
21665       if (User->getOpcode() == ISD::FNEG)
21666         return Op;
21667 
21668   SDLoc dl(Op);
21669   MVT VT = Op.getSimpleValueType();
21670 
21671   bool IsF128 = (VT == MVT::f128);
21672   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
21673          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
21674          "Unexpected type in LowerFABSorFNEG");
21675 
21676   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOptLevel to
21677   // decide if we should generate a 16-byte constant mask when we only need 4 or
21678   // 8 bytes for the scalar case.
21679 
21680   // There are no scalar bitwise logical SSE/AVX instructions, so we
21681   // generate a 16-byte vector constant and logic op even for the scalar case.
21682   // Using a 16-byte mask allows folding the load of the mask with
21683   // the logic op, so it can save (~4 bytes) on code size.
21684   bool IsFakeVector = !VT.isVector() && !IsF128;
21685   MVT LogicVT = VT;
21686   if (IsFakeVector)
21687     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
21688               : (VT == MVT::f32) ? MVT::v4f32
21689                                  : MVT::v8f16;
21690 
21691   unsigned EltBits = VT.getScalarSizeInBits();
21692   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
21693   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
21694                            APInt::getSignMask(EltBits);
21695   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21696   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
21697 
21698   SDValue Op0 = Op.getOperand(0);
21699   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
21700   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
21701                      IsFNABS ? X86ISD::FOR  :
21702                                X86ISD::FXOR;
21703   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
21704 
21705   if (VT.isVector() || IsF128)
21706     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
21707 
21708   // For the scalar case extend to a 128-bit vector, perform the logic op,
21709   // and extract the scalar result back out.
21710   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
21711   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
21712   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
21713                      DAG.getIntPtrConstant(0, dl));
21714 }
21715 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG)21716 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
21717   SDValue Mag = Op.getOperand(0);
21718   SDValue Sign = Op.getOperand(1);
21719   SDLoc dl(Op);
21720 
21721   // If the sign operand is smaller, extend it first.
21722   MVT VT = Op.getSimpleValueType();
21723   if (Sign.getSimpleValueType().bitsLT(VT))
21724     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
21725 
21726   // And if it is bigger, shrink it first.
21727   if (Sign.getSimpleValueType().bitsGT(VT))
21728     Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign,
21729                        DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
21730 
21731   // At this point the operands and the result should have the same
21732   // type, and that won't be f80 since that is not custom lowered.
21733   bool IsF128 = (VT == MVT::f128);
21734   assert(VT.isFloatingPoint() && VT != MVT::f80 &&
21735          DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
21736          "Unexpected type in LowerFCOPYSIGN");
21737 
21738   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21739 
21740   // Perform all scalar logic operations as 16-byte vectors because there are no
21741   // scalar FP logic instructions in SSE.
21742   // TODO: This isn't necessary. If we used scalar types, we might avoid some
21743   // unnecessary splats, but we might miss load folding opportunities. Should
21744   // this decision be based on OptimizeForSize?
21745   bool IsFakeVector = !VT.isVector() && !IsF128;
21746   MVT LogicVT = VT;
21747   if (IsFakeVector)
21748     LogicVT = (VT == MVT::f64)   ? MVT::v2f64
21749               : (VT == MVT::f32) ? MVT::v4f32
21750                                  : MVT::v8f16;
21751 
21752   // The mask constants are automatically splatted for vector types.
21753   unsigned EltSizeInBits = VT.getScalarSizeInBits();
21754   SDValue SignMask = DAG.getConstantFP(
21755       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
21756   SDValue MagMask = DAG.getConstantFP(
21757       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
21758 
21759   // First, clear all bits but the sign bit from the second operand (sign).
21760   if (IsFakeVector)
21761     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
21762   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
21763 
21764   // Next, clear the sign bit from the first operand (magnitude).
21765   // TODO: If we had general constant folding for FP logic ops, this check
21766   // wouldn't be necessary.
21767   SDValue MagBits;
21768   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
21769     APFloat APF = Op0CN->getValueAPF();
21770     APF.clearSign();
21771     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
21772   } else {
21773     // If the magnitude operand wasn't a constant, we need to AND out the sign.
21774     if (IsFakeVector)
21775       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
21776     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
21777   }
21778 
21779   // OR the magnitude value with the sign bit.
21780   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
21781   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
21782                                           DAG.getIntPtrConstant(0, dl));
21783 }
21784 
LowerFGETSIGN(SDValue Op,SelectionDAG & DAG)21785 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
21786   SDValue N0 = Op.getOperand(0);
21787   SDLoc dl(Op);
21788   MVT VT = Op.getSimpleValueType();
21789 
21790   MVT OpVT = N0.getSimpleValueType();
21791   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
21792          "Unexpected type for FGETSIGN");
21793 
21794   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
21795   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
21796   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
21797   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
21798   Res = DAG.getZExtOrTrunc(Res, dl, VT);
21799   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
21800   return Res;
21801 }
21802 
21803 /// Helper for attempting to create a X86ISD::BT node.
getBT(SDValue Src,SDValue BitNo,const SDLoc & DL,SelectionDAG & DAG)21804 static SDValue getBT(SDValue Src, SDValue BitNo, const SDLoc &DL, SelectionDAG &DAG) {
21805   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
21806   // instruction.  Since the shift amount is in-range-or-undefined, we know
21807   // that doing a bittest on the i32 value is ok.  We extend to i32 because
21808   // the encoding for the i16 version is larger than the i32 version.
21809   // Also promote i16 to i32 for performance / code size reason.
21810   if (Src.getValueType().getScalarSizeInBits() < 32)
21811     Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
21812 
21813   // No legal type found, give up.
21814   if (!DAG.getTargetLoweringInfo().isTypeLegal(Src.getValueType()))
21815     return SDValue();
21816 
21817   // See if we can use the 32-bit instruction instead of the 64-bit one for a
21818   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
21819   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
21820   // known to be zero.
21821   if (Src.getValueType() == MVT::i64 &&
21822       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
21823     Src = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Src);
21824 
21825   // If the operand types disagree, extend the shift amount to match.  Since
21826   // BT ignores high bits (like shifts) we can use anyextend.
21827   if (Src.getValueType() != BitNo.getValueType()) {
21828     // Peek through a mask/modulo operation.
21829     // TODO: DAGCombine fails to do this as it just checks isTruncateFree, but
21830     // we probably need a better IsDesirableToPromoteOp to handle this as well.
21831     if (BitNo.getOpcode() == ISD::AND && BitNo->hasOneUse())
21832       BitNo = DAG.getNode(ISD::AND, DL, Src.getValueType(),
21833                           DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
21834                                       BitNo.getOperand(0)),
21835                           DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(),
21836                                       BitNo.getOperand(1)));
21837     else
21838       BitNo = DAG.getNode(ISD::ANY_EXTEND, DL, Src.getValueType(), BitNo);
21839   }
21840 
21841   return DAG.getNode(X86ISD::BT, DL, MVT::i32, Src, BitNo);
21842 }
21843 
21844 /// Helper for creating a X86ISD::SETCC node.
getSETCC(X86::CondCode Cond,SDValue EFLAGS,const SDLoc & dl,SelectionDAG & DAG)21845 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
21846                         SelectionDAG &DAG) {
21847   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
21848                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
21849 }
21850 
21851 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
21852 /// recognizable memcmp expansion.
isOrXorXorTree(SDValue X,bool Root=true)21853 static bool isOrXorXorTree(SDValue X, bool Root = true) {
21854   if (X.getOpcode() == ISD::OR)
21855     return isOrXorXorTree(X.getOperand(0), false) &&
21856            isOrXorXorTree(X.getOperand(1), false);
21857   if (Root)
21858     return false;
21859   return X.getOpcode() == ISD::XOR;
21860 }
21861 
21862 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
21863 /// expansion.
21864 template <typename F>
emitOrXorXorTree(SDValue X,const SDLoc & DL,SelectionDAG & DAG,EVT VecVT,EVT CmpVT,bool HasPT,F SToV)21865 static SDValue emitOrXorXorTree(SDValue X, const SDLoc &DL, SelectionDAG &DAG,
21866                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
21867   SDValue Op0 = X.getOperand(0);
21868   SDValue Op1 = X.getOperand(1);
21869   if (X.getOpcode() == ISD::OR) {
21870     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
21871     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
21872     if (VecVT != CmpVT)
21873       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
21874     if (HasPT)
21875       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
21876     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
21877   }
21878   if (X.getOpcode() == ISD::XOR) {
21879     SDValue A = SToV(Op0);
21880     SDValue B = SToV(Op1);
21881     if (VecVT != CmpVT)
21882       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
21883     if (HasPT)
21884       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
21885     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
21886   }
21887   llvm_unreachable("Impossible");
21888 }
21889 
21890 /// Try to map a 128-bit or larger integer comparison to vector instructions
21891 /// before type legalization splits it up into chunks.
combineVectorSizedSetCCEquality(EVT VT,SDValue X,SDValue Y,ISD::CondCode CC,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)21892 static SDValue combineVectorSizedSetCCEquality(EVT VT, SDValue X, SDValue Y,
21893                                                ISD::CondCode CC,
21894                                                const SDLoc &DL,
21895                                                SelectionDAG &DAG,
21896                                                const X86Subtarget &Subtarget) {
21897   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
21898 
21899   // We're looking for an oversized integer equality comparison.
21900   EVT OpVT = X.getValueType();
21901   unsigned OpSize = OpVT.getSizeInBits();
21902   if (!OpVT.isScalarInteger() || OpSize < 128)
21903     return SDValue();
21904 
21905   // Ignore a comparison with zero because that gets special treatment in
21906   // EmitTest(). But make an exception for the special case of a pair of
21907   // logically-combined vector-sized operands compared to zero. This pattern may
21908   // be generated by the memcmp expansion pass with oversized integer compares
21909   // (see PR33325).
21910   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
21911   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
21912     return SDValue();
21913 
21914   // Don't perform this combine if constructing the vector will be expensive.
21915   auto IsVectorBitCastCheap = [](SDValue X) {
21916     X = peekThroughBitcasts(X);
21917     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
21918            X.getOpcode() == ISD::LOAD;
21919   };
21920   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
21921       !IsOrXorXorTreeCCZero)
21922     return SDValue();
21923 
21924   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
21925   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
21926   // Otherwise use PCMPEQ (plus AND) and mask testing.
21927   bool NoImplicitFloatOps =
21928       DAG.getMachineFunction().getFunction().hasFnAttribute(
21929           Attribute::NoImplicitFloat);
21930   if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
21931       ((OpSize == 128 && Subtarget.hasSSE2()) ||
21932        (OpSize == 256 && Subtarget.hasAVX()) ||
21933        (OpSize == 512 && Subtarget.useAVX512Regs()))) {
21934     bool HasPT = Subtarget.hasSSE41();
21935 
21936     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
21937     // vector registers are essentially free. (Technically, widening registers
21938     // prevents load folding, but the tradeoff is worth it.)
21939     bool PreferKOT = Subtarget.preferMaskRegisters();
21940     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
21941 
21942     EVT VecVT = MVT::v16i8;
21943     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
21944     if (OpSize == 256) {
21945       VecVT = MVT::v32i8;
21946       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
21947     }
21948     EVT CastVT = VecVT;
21949     bool NeedsAVX512FCast = false;
21950     if (OpSize == 512 || NeedZExt) {
21951       if (Subtarget.hasBWI()) {
21952         VecVT = MVT::v64i8;
21953         CmpVT = MVT::v64i1;
21954         if (OpSize == 512)
21955           CastVT = VecVT;
21956       } else {
21957         VecVT = MVT::v16i32;
21958         CmpVT = MVT::v16i1;
21959         CastVT = OpSize == 512   ? VecVT
21960                  : OpSize == 256 ? MVT::v8i32
21961                                  : MVT::v4i32;
21962         NeedsAVX512FCast = true;
21963       }
21964     }
21965 
21966     auto ScalarToVector = [&](SDValue X) -> SDValue {
21967       bool TmpZext = false;
21968       EVT TmpCastVT = CastVT;
21969       if (X.getOpcode() == ISD::ZERO_EXTEND) {
21970         SDValue OrigX = X.getOperand(0);
21971         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
21972         if (OrigSize < OpSize) {
21973           if (OrigSize == 128) {
21974             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
21975             X = OrigX;
21976             TmpZext = true;
21977           } else if (OrigSize == 256) {
21978             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
21979             X = OrigX;
21980             TmpZext = true;
21981           }
21982         }
21983       }
21984       X = DAG.getBitcast(TmpCastVT, X);
21985       if (!NeedZExt && !TmpZext)
21986         return X;
21987       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
21988                          DAG.getConstant(0, DL, VecVT), X,
21989                          DAG.getVectorIdxConstant(0, DL));
21990     };
21991 
21992     SDValue Cmp;
21993     if (IsOrXorXorTreeCCZero) {
21994       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
21995       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
21996       // Use 2 vector equality compares and 'and' the results before doing a
21997       // MOVMSK.
21998       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
21999     } else {
22000       SDValue VecX = ScalarToVector(X);
22001       SDValue VecY = ScalarToVector(Y);
22002       if (VecVT != CmpVT) {
22003         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
22004       } else if (HasPT) {
22005         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
22006       } else {
22007         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
22008       }
22009     }
22010     // AVX512 should emit a setcc that will lower to kortest.
22011     if (VecVT != CmpVT) {
22012       EVT KRegVT = CmpVT == MVT::v64i1   ? MVT::i64
22013                    : CmpVT == MVT::v32i1 ? MVT::i32
22014                                          : MVT::i16;
22015       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
22016                           DAG.getConstant(0, DL, KRegVT), CC);
22017     }
22018     if (HasPT) {
22019       SDValue BCCmp =
22020           DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64, Cmp);
22021       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
22022       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
22023       SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
22024       return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
22025     }
22026     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
22027     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
22028     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
22029     assert(Cmp.getValueType() == MVT::v16i8 &&
22030            "Non 128-bit vector on pre-SSE41 target");
22031     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
22032     SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
22033     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
22034   }
22035 
22036   return SDValue();
22037 }
22038 
22039 /// Helper for matching BINOP(EXTRACTELT(X,0),BINOP(EXTRACTELT(X,1),...))
22040 /// style scalarized (associative) reduction patterns. Partial reductions
22041 /// are supported when the pointer SrcMask is non-null.
22042 /// TODO - move this to SelectionDAG?
matchScalarReduction(SDValue Op,ISD::NodeType BinOp,SmallVectorImpl<SDValue> & SrcOps,SmallVectorImpl<APInt> * SrcMask=nullptr)22043 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
22044                                  SmallVectorImpl<SDValue> &SrcOps,
22045                                  SmallVectorImpl<APInt> *SrcMask = nullptr) {
22046   SmallVector<SDValue, 8> Opnds;
22047   DenseMap<SDValue, APInt> SrcOpMap;
22048   EVT VT = MVT::Other;
22049 
22050   // Recognize a special case where a vector is casted into wide integer to
22051   // test all 0s.
22052   assert(Op.getOpcode() == unsigned(BinOp) &&
22053          "Unexpected bit reduction opcode");
22054   Opnds.push_back(Op.getOperand(0));
22055   Opnds.push_back(Op.getOperand(1));
22056 
22057   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
22058     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
22059     // BFS traverse all BinOp operands.
22060     if (I->getOpcode() == unsigned(BinOp)) {
22061       Opnds.push_back(I->getOperand(0));
22062       Opnds.push_back(I->getOperand(1));
22063       // Re-evaluate the number of nodes to be traversed.
22064       e += 2; // 2 more nodes (LHS and RHS) are pushed.
22065       continue;
22066     }
22067 
22068     // Quit if a non-EXTRACT_VECTOR_ELT
22069     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22070       return false;
22071 
22072     // Quit if without a constant index.
22073     auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
22074     if (!Idx)
22075       return false;
22076 
22077     SDValue Src = I->getOperand(0);
22078     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
22079     if (M == SrcOpMap.end()) {
22080       VT = Src.getValueType();
22081       // Quit if not the same type.
22082       if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
22083         return false;
22084       unsigned NumElts = VT.getVectorNumElements();
22085       APInt EltCount = APInt::getZero(NumElts);
22086       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
22087       SrcOps.push_back(Src);
22088     }
22089 
22090     // Quit if element already used.
22091     unsigned CIdx = Idx->getZExtValue();
22092     if (M->second[CIdx])
22093       return false;
22094     M->second.setBit(CIdx);
22095   }
22096 
22097   if (SrcMask) {
22098     // Collect the source partial masks.
22099     for (SDValue &SrcOp : SrcOps)
22100       SrcMask->push_back(SrcOpMap[SrcOp]);
22101   } else {
22102     // Quit if not all elements are used.
22103     for (const auto &I : SrcOpMap)
22104       if (!I.second.isAllOnes())
22105         return false;
22106   }
22107 
22108   return true;
22109 }
22110 
22111 // Helper function for comparing all bits of two vectors.
LowerVectorAllEqual(const SDLoc & DL,SDValue LHS,SDValue RHS,ISD::CondCode CC,const APInt & OriginalMask,const X86Subtarget & Subtarget,SelectionDAG & DAG,X86::CondCode & X86CC)22112 static SDValue LowerVectorAllEqual(const SDLoc &DL, SDValue LHS, SDValue RHS,
22113                                    ISD::CondCode CC, const APInt &OriginalMask,
22114                                    const X86Subtarget &Subtarget,
22115                                    SelectionDAG &DAG, X86::CondCode &X86CC) {
22116   EVT VT = LHS.getValueType();
22117   unsigned ScalarSize = VT.getScalarSizeInBits();
22118   if (OriginalMask.getBitWidth() != ScalarSize) {
22119     assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch");
22120     return SDValue();
22121   }
22122 
22123   // Quit if not convertable to legal scalar or 128/256-bit vector.
22124   if (!llvm::has_single_bit<uint32_t>(VT.getSizeInBits()))
22125     return SDValue();
22126 
22127   // FCMP may use ISD::SETNE when nnan - early out if we manage to get here.
22128   if (VT.isFloatingPoint())
22129     return SDValue();
22130 
22131   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22132   X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
22133 
22134   APInt Mask = OriginalMask;
22135 
22136   auto MaskBits = [&](SDValue Src) {
22137     if (Mask.isAllOnes())
22138       return Src;
22139     EVT SrcVT = Src.getValueType();
22140     SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
22141     return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
22142   };
22143 
22144   // For sub-128-bit vector, cast to (legal) integer and compare with zero.
22145   if (VT.getSizeInBits() < 128) {
22146     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
22147     if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT)) {
22148       if (IntVT != MVT::i64)
22149         return SDValue();
22150       auto SplitLHS = DAG.SplitScalar(DAG.getBitcast(IntVT, MaskBits(LHS)), DL,
22151                                       MVT::i32, MVT::i32);
22152       auto SplitRHS = DAG.SplitScalar(DAG.getBitcast(IntVT, MaskBits(RHS)), DL,
22153                                       MVT::i32, MVT::i32);
22154       SDValue Lo =
22155           DAG.getNode(ISD::XOR, DL, MVT::i32, SplitLHS.first, SplitRHS.first);
22156       SDValue Hi =
22157           DAG.getNode(ISD::XOR, DL, MVT::i32, SplitLHS.second, SplitRHS.second);
22158       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22159                          DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi),
22160                          DAG.getConstant(0, DL, MVT::i32));
22161     }
22162     return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22163                        DAG.getBitcast(IntVT, MaskBits(LHS)),
22164                        DAG.getBitcast(IntVT, MaskBits(RHS)));
22165   }
22166 
22167   // Without PTEST, a masked v2i64 or-reduction is not faster than
22168   // scalarization.
22169   bool UseKORTEST = Subtarget.useAVX512Regs();
22170   bool UsePTEST = Subtarget.hasSSE41();
22171   if (!UsePTEST && !Mask.isAllOnes() && ScalarSize > 32)
22172     return SDValue();
22173 
22174   // Split down to 128/256/512-bit vector.
22175   unsigned TestSize = UseKORTEST ? 512 : (Subtarget.hasAVX() ? 256 : 128);
22176 
22177   // If the input vector has vector elements wider than the target test size,
22178   // then cast to <X x i64> so it will safely split.
22179   if (ScalarSize > TestSize) {
22180     if (!Mask.isAllOnes())
22181       return SDValue();
22182     VT = EVT::getVectorVT(*DAG.getContext(), MVT::i64, VT.getSizeInBits() / 64);
22183     LHS = DAG.getBitcast(VT, LHS);
22184     RHS = DAG.getBitcast(VT, RHS);
22185     Mask = APInt::getAllOnes(64);
22186   }
22187 
22188   if (VT.getSizeInBits() > TestSize) {
22189     KnownBits KnownRHS = DAG.computeKnownBits(RHS);
22190     if (KnownRHS.isConstant() && KnownRHS.getConstant() == Mask) {
22191       // If ICMP(AND(LHS,MASK),MASK) - reduce using AND splits.
22192       while (VT.getSizeInBits() > TestSize) {
22193         auto Split = DAG.SplitVector(LHS, DL);
22194         VT = Split.first.getValueType();
22195         LHS = DAG.getNode(ISD::AND, DL, VT, Split.first, Split.second);
22196       }
22197       RHS = DAG.getAllOnesConstant(DL, VT);
22198     } else if (!UsePTEST && !KnownRHS.isZero()) {
22199       // MOVMSK Special Case:
22200       // ALLOF(CMPEQ(X,Y)) -> AND(CMPEQ(X[0],Y[0]),CMPEQ(X[1],Y[1]),....)
22201       MVT SVT = ScalarSize >= 32 ? MVT::i32 : MVT::i8;
22202       VT = MVT::getVectorVT(SVT, VT.getSizeInBits() / SVT.getSizeInBits());
22203       LHS = DAG.getBitcast(VT, MaskBits(LHS));
22204       RHS = DAG.getBitcast(VT, MaskBits(RHS));
22205       EVT BoolVT = VT.changeVectorElementType(MVT::i1);
22206       SDValue V = DAG.getSetCC(DL, BoolVT, LHS, RHS, ISD::SETEQ);
22207       V = DAG.getSExtOrTrunc(V, DL, VT);
22208       while (VT.getSizeInBits() > TestSize) {
22209         auto Split = DAG.SplitVector(V, DL);
22210         VT = Split.first.getValueType();
22211         V = DAG.getNode(ISD::AND, DL, VT, Split.first, Split.second);
22212       }
22213       V = DAG.getNOT(DL, V, VT);
22214       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22215       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22216                          DAG.getConstant(0, DL, MVT::i32));
22217     } else {
22218       // Convert to a ICMP_EQ(XOR(LHS,RHS),0) pattern.
22219       SDValue V = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
22220       while (VT.getSizeInBits() > TestSize) {
22221         auto Split = DAG.SplitVector(V, DL);
22222         VT = Split.first.getValueType();
22223         V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
22224       }
22225       LHS = V;
22226       RHS = DAG.getConstant(0, DL, VT);
22227     }
22228   }
22229 
22230   if (UseKORTEST && VT.is512BitVector()) {
22231     MVT TestVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
22232     MVT BoolVT = TestVT.changeVectorElementType(MVT::i1);
22233     LHS = DAG.getBitcast(TestVT, MaskBits(LHS));
22234     RHS = DAG.getBitcast(TestVT, MaskBits(RHS));
22235     SDValue V = DAG.getSetCC(DL, BoolVT, LHS, RHS, ISD::SETNE);
22236     return DAG.getNode(X86ISD::KORTEST, DL, MVT::i32, V, V);
22237   }
22238 
22239   if (UsePTEST) {
22240     MVT TestVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
22241     LHS = DAG.getBitcast(TestVT, MaskBits(LHS));
22242     RHS = DAG.getBitcast(TestVT, MaskBits(RHS));
22243     SDValue V = DAG.getNode(ISD::XOR, DL, TestVT, LHS, RHS);
22244     return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
22245   }
22246 
22247   assert(VT.getSizeInBits() == 128 && "Failure to split to 128-bits");
22248   MVT MaskVT = ScalarSize >= 32 ? MVT::v4i32 : MVT::v16i8;
22249   LHS = DAG.getBitcast(MaskVT, MaskBits(LHS));
22250   RHS = DAG.getBitcast(MaskVT, MaskBits(RHS));
22251   SDValue V = DAG.getNode(X86ISD::PCMPEQ, DL, MaskVT, LHS, RHS);
22252   V = DAG.getNOT(DL, V, MaskVT);
22253   V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22254   return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22255                      DAG.getConstant(0, DL, MVT::i32));
22256 }
22257 
22258 // Check whether an AND/OR'd reduction tree is PTEST-able, or if we can fallback
22259 // to CMP(MOVMSK(PCMPEQB(X,Y))).
MatchVectorAllEqualTest(SDValue LHS,SDValue RHS,ISD::CondCode CC,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG,X86::CondCode & X86CC)22260 static SDValue MatchVectorAllEqualTest(SDValue LHS, SDValue RHS,
22261                                        ISD::CondCode CC, const SDLoc &DL,
22262                                        const X86Subtarget &Subtarget,
22263                                        SelectionDAG &DAG,
22264                                        X86::CondCode &X86CC) {
22265   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22266 
22267   bool CmpNull = isNullConstant(RHS);
22268   bool CmpAllOnes = isAllOnesConstant(RHS);
22269   if (!CmpNull && !CmpAllOnes)
22270     return SDValue();
22271 
22272   SDValue Op = LHS;
22273   if (!Subtarget.hasSSE2() || !Op->hasOneUse())
22274     return SDValue();
22275 
22276   // Check whether we're masking/truncating an OR-reduction result, in which
22277   // case track the masked bits.
22278   // TODO: Add CmpAllOnes support.
22279   APInt Mask = APInt::getAllOnes(Op.getScalarValueSizeInBits());
22280   if (CmpNull) {
22281     switch (Op.getOpcode()) {
22282     case ISD::TRUNCATE: {
22283       SDValue Src = Op.getOperand(0);
22284       Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
22285                                   Op.getScalarValueSizeInBits());
22286       Op = Src;
22287       break;
22288     }
22289     case ISD::AND: {
22290       if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22291         Mask = Cst->getAPIntValue();
22292         Op = Op.getOperand(0);
22293       }
22294       break;
22295     }
22296     }
22297   }
22298 
22299   ISD::NodeType LogicOp = CmpNull ? ISD::OR : ISD::AND;
22300 
22301   // Match icmp(or(extract(X,0),extract(X,1)),0) anyof reduction patterns.
22302   // Match icmp(and(extract(X,0),extract(X,1)),-1) allof reduction patterns.
22303   SmallVector<SDValue, 8> VecIns;
22304   if (Op.getOpcode() == LogicOp && matchScalarReduction(Op, LogicOp, VecIns)) {
22305     EVT VT = VecIns[0].getValueType();
22306     assert(llvm::all_of(VecIns,
22307                         [VT](SDValue V) { return VT == V.getValueType(); }) &&
22308            "Reduction source vector mismatch");
22309 
22310     // Quit if not splittable to scalar/128/256/512-bit vector.
22311     if (!llvm::has_single_bit<uint32_t>(VT.getSizeInBits()))
22312       return SDValue();
22313 
22314     // If more than one full vector is evaluated, AND/OR them first before
22315     // PTEST.
22316     for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
22317          Slot += 2, e += 1) {
22318       // Each iteration will AND/OR 2 nodes and append the result until there is
22319       // only 1 node left, i.e. the final value of all vectors.
22320       SDValue LHS = VecIns[Slot];
22321       SDValue RHS = VecIns[Slot + 1];
22322       VecIns.push_back(DAG.getNode(LogicOp, DL, VT, LHS, RHS));
22323     }
22324 
22325     return LowerVectorAllEqual(DL, VecIns.back(),
22326                                CmpNull ? DAG.getConstant(0, DL, VT)
22327                                        : DAG.getAllOnesConstant(DL, VT),
22328                                CC, Mask, Subtarget, DAG, X86CC);
22329   }
22330 
22331   // Match icmp(reduce_or(X),0) anyof reduction patterns.
22332   // Match icmp(reduce_and(X),-1) allof reduction patterns.
22333   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
22334     ISD::NodeType BinOp;
22335     if (SDValue Match =
22336             DAG.matchBinOpReduction(Op.getNode(), BinOp, {LogicOp})) {
22337       EVT MatchVT = Match.getValueType();
22338       return LowerVectorAllEqual(DL, Match,
22339                                  CmpNull ? DAG.getConstant(0, DL, MatchVT)
22340                                          : DAG.getAllOnesConstant(DL, MatchVT),
22341                                  CC, Mask, Subtarget, DAG, X86CC);
22342     }
22343   }
22344 
22345   if (Mask.isAllOnes()) {
22346     assert(!Op.getValueType().isVector() &&
22347            "Illegal vector type for reduction pattern");
22348     SDValue Src = peekThroughBitcasts(Op);
22349     if (Src.getValueType().isFixedLengthVector() &&
22350         Src.getValueType().getScalarType() == MVT::i1) {
22351       // Match icmp(bitcast(icmp_ne(X,Y)),0) reduction patterns.
22352       // Match icmp(bitcast(icmp_eq(X,Y)),-1) reduction patterns.
22353       if (Src.getOpcode() == ISD::SETCC) {
22354         SDValue LHS = Src.getOperand(0);
22355         SDValue RHS = Src.getOperand(1);
22356         EVT LHSVT = LHS.getValueType();
22357         ISD::CondCode SrcCC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
22358         if (SrcCC == (CmpNull ? ISD::SETNE : ISD::SETEQ) &&
22359             llvm::has_single_bit<uint32_t>(LHSVT.getSizeInBits())) {
22360           APInt SrcMask = APInt::getAllOnes(LHSVT.getScalarSizeInBits());
22361           return LowerVectorAllEqual(DL, LHS, RHS, CC, SrcMask, Subtarget, DAG,
22362                                      X86CC);
22363         }
22364       }
22365       // Match icmp(bitcast(vXi1 trunc(Y)),0) reduction patterns.
22366       // Match icmp(bitcast(vXi1 trunc(Y)),-1) reduction patterns.
22367       // Peek through truncation, mask the LSB and compare against zero/LSB.
22368       if (Src.getOpcode() == ISD::TRUNCATE) {
22369         SDValue Inner = Src.getOperand(0);
22370         EVT InnerVT = Inner.getValueType();
22371         if (llvm::has_single_bit<uint32_t>(InnerVT.getSizeInBits())) {
22372           unsigned BW = InnerVT.getScalarSizeInBits();
22373           APInt SrcMask = APInt(BW, 1);
22374           APInt Cmp = CmpNull ? APInt::getZero(BW) : SrcMask;
22375           return LowerVectorAllEqual(DL, Inner,
22376                                      DAG.getConstant(Cmp, DL, InnerVT), CC,
22377                                      SrcMask, Subtarget, DAG, X86CC);
22378         }
22379       }
22380     }
22381   }
22382 
22383   return SDValue();
22384 }
22385 
22386 /// return true if \c Op has a use that doesn't just read flags.
hasNonFlagsUse(SDValue Op)22387 static bool hasNonFlagsUse(SDValue Op) {
22388   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
22389        ++UI) {
22390     SDNode *User = *UI;
22391     unsigned UOpNo = UI.getOperandNo();
22392     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
22393       // Look pass truncate.
22394       UOpNo = User->use_begin().getOperandNo();
22395       User = *User->use_begin();
22396     }
22397 
22398     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
22399         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
22400       return true;
22401   }
22402   return false;
22403 }
22404 
22405 // Transform to an x86-specific ALU node with flags if there is a chance of
22406 // using an RMW op or only the flags are used. Otherwise, leave
22407 // the node alone and emit a 'cmp' or 'test' instruction.
isProfitableToUseFlagOp(SDValue Op)22408 static bool isProfitableToUseFlagOp(SDValue Op) {
22409   for (SDNode *U : Op->uses())
22410     if (U->getOpcode() != ISD::CopyToReg &&
22411         U->getOpcode() != ISD::SETCC &&
22412         U->getOpcode() != ISD::STORE)
22413       return false;
22414 
22415   return true;
22416 }
22417 
22418 /// Emit nodes that will be selected as "test Op0,Op0", or something
22419 /// equivalent.
EmitTest(SDValue Op,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)22420 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
22421                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
22422   // CF and OF aren't always set the way we want. Determine which
22423   // of these we need.
22424   bool NeedCF = false;
22425   bool NeedOF = false;
22426   switch (X86CC) {
22427   default: break;
22428   case X86::COND_A: case X86::COND_AE:
22429   case X86::COND_B: case X86::COND_BE:
22430     NeedCF = true;
22431     break;
22432   case X86::COND_G: case X86::COND_GE:
22433   case X86::COND_L: case X86::COND_LE:
22434   case X86::COND_O: case X86::COND_NO: {
22435     // Check if we really need to set the
22436     // Overflow flag. If NoSignedWrap is present
22437     // that is not actually needed.
22438     switch (Op->getOpcode()) {
22439     case ISD::ADD:
22440     case ISD::SUB:
22441     case ISD::MUL:
22442     case ISD::SHL:
22443       if (Op.getNode()->getFlags().hasNoSignedWrap())
22444         break;
22445       [[fallthrough]];
22446     default:
22447       NeedOF = true;
22448       break;
22449     }
22450     break;
22451   }
22452   }
22453   // See if we can use the EFLAGS value from the operand instead of
22454   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
22455   // we prove that the arithmetic won't overflow, we can't use OF or CF.
22456   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
22457     // Emit a CMP with 0, which is the TEST pattern.
22458     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22459                        DAG.getConstant(0, dl, Op.getValueType()));
22460   }
22461   unsigned Opcode = 0;
22462   unsigned NumOperands = 0;
22463 
22464   SDValue ArithOp = Op;
22465 
22466   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
22467   // which may be the result of a CAST.  We use the variable 'Op', which is the
22468   // non-casted variable when we check for possible users.
22469   switch (ArithOp.getOpcode()) {
22470   case ISD::AND:
22471     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
22472     // because a TEST instruction will be better.
22473     if (!hasNonFlagsUse(Op))
22474       break;
22475 
22476     [[fallthrough]];
22477   case ISD::ADD:
22478   case ISD::SUB:
22479   case ISD::OR:
22480   case ISD::XOR:
22481     if (!isProfitableToUseFlagOp(Op))
22482       break;
22483 
22484     // Otherwise use a regular EFLAGS-setting instruction.
22485     switch (ArithOp.getOpcode()) {
22486     default: llvm_unreachable("unexpected operator!");
22487     case ISD::ADD: Opcode = X86ISD::ADD; break;
22488     case ISD::SUB: Opcode = X86ISD::SUB; break;
22489     case ISD::XOR: Opcode = X86ISD::XOR; break;
22490     case ISD::AND: Opcode = X86ISD::AND; break;
22491     case ISD::OR:  Opcode = X86ISD::OR;  break;
22492     }
22493 
22494     NumOperands = 2;
22495     break;
22496   case X86ISD::ADD:
22497   case X86ISD::SUB:
22498   case X86ISD::OR:
22499   case X86ISD::XOR:
22500   case X86ISD::AND:
22501     return SDValue(Op.getNode(), 1);
22502   case ISD::SSUBO:
22503   case ISD::USUBO: {
22504     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
22505     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22506     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
22507                        Op->getOperand(1)).getValue(1);
22508   }
22509   default:
22510     break;
22511   }
22512 
22513   if (Opcode == 0) {
22514     // Emit a CMP with 0, which is the TEST pattern.
22515     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22516                        DAG.getConstant(0, dl, Op.getValueType()));
22517   }
22518   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22519   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
22520 
22521   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
22522   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
22523   return SDValue(New.getNode(), 1);
22524 }
22525 
22526 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
22527 /// equivalent.
EmitCmp(SDValue Op0,SDValue Op1,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)22528 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
22529                        const SDLoc &dl, SelectionDAG &DAG,
22530                        const X86Subtarget &Subtarget) {
22531   if (isNullConstant(Op1))
22532     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
22533 
22534   EVT CmpVT = Op0.getValueType();
22535 
22536   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
22537           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
22538 
22539   // Only promote the compare up to I32 if it is a 16 bit operation
22540   // with an immediate.  16 bit immediates are to be avoided.
22541   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
22542       !DAG.getMachineFunction().getFunction().hasMinSize()) {
22543     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
22544     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
22545     // Don't do this if the immediate can fit in 8-bits.
22546     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
22547         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
22548       unsigned ExtendOp =
22549           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
22550       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
22551         // For equality comparisons try to use SIGN_EXTEND if the input was
22552         // truncate from something with enough sign bits.
22553         if (Op0.getOpcode() == ISD::TRUNCATE) {
22554           if (DAG.ComputeMaxSignificantBits(Op0.getOperand(0)) <= 16)
22555             ExtendOp = ISD::SIGN_EXTEND;
22556         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
22557           if (DAG.ComputeMaxSignificantBits(Op1.getOperand(0)) <= 16)
22558             ExtendOp = ISD::SIGN_EXTEND;
22559         }
22560       }
22561 
22562       CmpVT = MVT::i32;
22563       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
22564       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
22565     }
22566   }
22567 
22568   // Try to shrink i64 compares if the input has enough zero bits.
22569   // FIXME: Do this for non-constant compares for constant on LHS?
22570   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
22571       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
22572       Op1->getAsAPIntVal().getActiveBits() <= 32 &&
22573       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
22574     CmpVT = MVT::i32;
22575     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
22576     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
22577   }
22578 
22579   // 0-x == y --> x+y == 0
22580   // 0-x != y --> x+y != 0
22581   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
22582       Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
22583     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22584     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
22585     return Add.getValue(1);
22586   }
22587 
22588   // x == 0-y --> x+y == 0
22589   // x != 0-y --> x+y != 0
22590   if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
22591       Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
22592     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22593     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
22594     return Add.getValue(1);
22595   }
22596 
22597   // Use SUB instead of CMP to enable CSE between SUB and CMP.
22598   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22599   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
22600   return Sub.getValue(1);
22601 }
22602 
isXAndYEqZeroPreferableToXAndYEqY(ISD::CondCode Cond,EVT VT) const22603 bool X86TargetLowering::isXAndYEqZeroPreferableToXAndYEqY(ISD::CondCode Cond,
22604                                                           EVT VT) const {
22605   return !VT.isVector() || Cond != ISD::CondCode::SETEQ;
22606 }
22607 
optimizeFMulOrFDivAsShiftAddBitcast(SDNode * N,SDValue,SDValue IntPow2) const22608 bool X86TargetLowering::optimizeFMulOrFDivAsShiftAddBitcast(
22609     SDNode *N, SDValue, SDValue IntPow2) const {
22610   if (N->getOpcode() == ISD::FDIV)
22611     return true;
22612 
22613   EVT FPVT = N->getValueType(0);
22614   EVT IntVT = IntPow2.getValueType();
22615 
22616   // This indicates a non-free bitcast.
22617   // TODO: This is probably overly conservative as we will need to scale the
22618   // integer vector anyways for the int->fp cast.
22619   if (FPVT.isVector() &&
22620       FPVT.getScalarSizeInBits() != IntVT.getScalarSizeInBits())
22621     return false;
22622 
22623   return true;
22624 }
22625 
22626 /// Check if replacement of SQRT with RSQRT should be disabled.
isFsqrtCheap(SDValue Op,SelectionDAG & DAG) const22627 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
22628   EVT VT = Op.getValueType();
22629 
22630   // We don't need to replace SQRT with RSQRT for half type.
22631   if (VT.getScalarType() == MVT::f16)
22632     return true;
22633 
22634   // We never want to use both SQRT and RSQRT instructions for the same input.
22635   if (DAG.doesNodeExist(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
22636     return false;
22637 
22638   if (VT.isVector())
22639     return Subtarget.hasFastVectorFSQRT();
22640   return Subtarget.hasFastScalarFSQRT();
22641 }
22642 
22643 /// The minimum architected relative accuracy is 2^-12. We need one
22644 /// Newton-Raphson step to have a good float result (24 bits of precision).
getSqrtEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps,bool & UseOneConstNR,bool Reciprocal) const22645 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
22646                                            SelectionDAG &DAG, int Enabled,
22647                                            int &RefinementSteps,
22648                                            bool &UseOneConstNR,
22649                                            bool Reciprocal) const {
22650   SDLoc DL(Op);
22651   EVT VT = Op.getValueType();
22652 
22653   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
22654   // It is likely not profitable to do this for f64 because a double-precision
22655   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
22656   // instructions: convert to single, rsqrtss, convert back to double, refine
22657   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
22658   // along with FMA, this could be a throughput win.
22659   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
22660   // after legalize types.
22661   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
22662       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
22663       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
22664       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
22665       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
22666     if (RefinementSteps == ReciprocalEstimate::Unspecified)
22667       RefinementSteps = 1;
22668 
22669     UseOneConstNR = false;
22670     // There is no FSQRT for 512-bits, but there is RSQRT14.
22671     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
22672     SDValue Estimate = DAG.getNode(Opcode, DL, VT, Op);
22673     if (RefinementSteps == 0 && !Reciprocal)
22674       Estimate = DAG.getNode(ISD::FMUL, DL, VT, Op, Estimate);
22675     return Estimate;
22676   }
22677 
22678   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
22679       Subtarget.hasFP16()) {
22680     assert(Reciprocal && "Don't replace SQRT with RSQRT for half type");
22681     if (RefinementSteps == ReciprocalEstimate::Unspecified)
22682       RefinementSteps = 0;
22683 
22684     if (VT == MVT::f16) {
22685       SDValue Zero = DAG.getIntPtrConstant(0, DL);
22686       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
22687       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
22688       Op = DAG.getNode(X86ISD::RSQRT14S, DL, MVT::v8f16, Undef, Op);
22689       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
22690     }
22691 
22692     return DAG.getNode(X86ISD::RSQRT14, DL, VT, Op);
22693   }
22694   return SDValue();
22695 }
22696 
22697 /// The minimum architected relative accuracy is 2^-12. We need one
22698 /// Newton-Raphson step to have a good float result (24 bits of precision).
getRecipEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps) const22699 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
22700                                             int Enabled,
22701                                             int &RefinementSteps) const {
22702   SDLoc DL(Op);
22703   EVT VT = Op.getValueType();
22704 
22705   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
22706   // It is likely not profitable to do this for f64 because a double-precision
22707   // reciprocal estimate with refinement on x86 prior to FMA requires
22708   // 15 instructions: convert to single, rcpss, convert back to double, refine
22709   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
22710   // along with FMA, this could be a throughput win.
22711 
22712   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
22713       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
22714       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
22715       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
22716     // Enable estimate codegen with 1 refinement step for vector division.
22717     // Scalar division estimates are disabled because they break too much
22718     // real-world code. These defaults are intended to match GCC behavior.
22719     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
22720       return SDValue();
22721 
22722     if (RefinementSteps == ReciprocalEstimate::Unspecified)
22723       RefinementSteps = 1;
22724 
22725     // There is no FSQRT for 512-bits, but there is RCP14.
22726     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
22727     return DAG.getNode(Opcode, DL, VT, Op);
22728   }
22729 
22730   if (VT.getScalarType() == MVT::f16 && isTypeLegal(VT) &&
22731       Subtarget.hasFP16()) {
22732     if (RefinementSteps == ReciprocalEstimate::Unspecified)
22733       RefinementSteps = 0;
22734 
22735     if (VT == MVT::f16) {
22736       SDValue Zero = DAG.getIntPtrConstant(0, DL);
22737       SDValue Undef = DAG.getUNDEF(MVT::v8f16);
22738       Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v8f16, Op);
22739       Op = DAG.getNode(X86ISD::RCP14S, DL, MVT::v8f16, Undef, Op);
22740       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f16, Op, Zero);
22741     }
22742 
22743     return DAG.getNode(X86ISD::RCP14, DL, VT, Op);
22744   }
22745   return SDValue();
22746 }
22747 
22748 /// If we have at least two divisions that use the same divisor, convert to
22749 /// multiplication by a reciprocal. This may need to be adjusted for a given
22750 /// CPU if a division's cost is not at least twice the cost of a multiplication.
22751 /// This is because we still need one division to calculate the reciprocal and
22752 /// then we need two multiplies by that reciprocal as replacements for the
22753 /// original divisions.
combineRepeatedFPDivisors() const22754 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
22755   return 2;
22756 }
22757 
22758 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const22759 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
22760                                  SelectionDAG &DAG,
22761                                  SmallVectorImpl<SDNode *> &Created) const {
22762   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
22763   if (isIntDivCheap(N->getValueType(0), Attr))
22764     return SDValue(N,0); // Lower SDIV as SDIV
22765 
22766   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
22767          "Unexpected divisor!");
22768 
22769   // Only perform this transform if CMOV is supported otherwise the select
22770   // below will become a branch.
22771   if (!Subtarget.canUseCMOV())
22772     return SDValue();
22773 
22774   // fold (sdiv X, pow2)
22775   EVT VT = N->getValueType(0);
22776   // FIXME: Support i8.
22777   if (VT != MVT::i16 && VT != MVT::i32 &&
22778       !(Subtarget.is64Bit() && VT == MVT::i64))
22779     return SDValue();
22780 
22781   // If the divisor is 2 or -2, the default expansion is better.
22782   if (Divisor == 2 ||
22783       Divisor == APInt(Divisor.getBitWidth(), -2, /*isSigned*/ true))
22784     return SDValue();
22785 
22786   return TargetLowering::buildSDIVPow2WithCMov(N, Divisor, DAG, Created);
22787 }
22788 
22789 /// Result of 'and' is compared against zero. Change to a BT node if possible.
22790 /// Returns the BT node and the condition code needed to use it.
LowerAndToBT(SDValue And,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,X86::CondCode & X86CC)22791 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC, const SDLoc &dl,
22792                             SelectionDAG &DAG, X86::CondCode &X86CC) {
22793   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
22794   SDValue Op0 = And.getOperand(0);
22795   SDValue Op1 = And.getOperand(1);
22796   if (Op0.getOpcode() == ISD::TRUNCATE)
22797     Op0 = Op0.getOperand(0);
22798   if (Op1.getOpcode() == ISD::TRUNCATE)
22799     Op1 = Op1.getOperand(0);
22800 
22801   SDValue Src, BitNo;
22802   if (Op1.getOpcode() == ISD::SHL)
22803     std::swap(Op0, Op1);
22804   if (Op0.getOpcode() == ISD::SHL) {
22805     if (isOneConstant(Op0.getOperand(0))) {
22806       // If we looked past a truncate, check that it's only truncating away
22807       // known zeros.
22808       unsigned BitWidth = Op0.getValueSizeInBits();
22809       unsigned AndBitWidth = And.getValueSizeInBits();
22810       if (BitWidth > AndBitWidth) {
22811         KnownBits Known = DAG.computeKnownBits(Op0);
22812         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
22813           return SDValue();
22814       }
22815       Src = Op1;
22816       BitNo = Op0.getOperand(1);
22817     }
22818   } else if (Op1.getOpcode() == ISD::Constant) {
22819     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
22820     uint64_t AndRHSVal = AndRHS->getZExtValue();
22821     SDValue AndLHS = Op0;
22822 
22823     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
22824       Src = AndLHS.getOperand(0);
22825       BitNo = AndLHS.getOperand(1);
22826     } else {
22827       // Use BT if the immediate can't be encoded in a TEST instruction or we
22828       // are optimizing for size and the immedaite won't fit in a byte.
22829       bool OptForSize = DAG.shouldOptForSize();
22830       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
22831           isPowerOf2_64(AndRHSVal)) {
22832         Src = AndLHS;
22833         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
22834                                 Src.getValueType());
22835       }
22836     }
22837   }
22838 
22839   // No patterns found, give up.
22840   if (!Src.getNode())
22841     return SDValue();
22842 
22843   // Remove any bit flip.
22844   if (isBitwiseNot(Src)) {
22845     Src = Src.getOperand(0);
22846     CC = CC == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
22847   }
22848 
22849   // Attempt to create the X86ISD::BT node.
22850   if (SDValue BT = getBT(Src, BitNo, dl, DAG)) {
22851     X86CC = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
22852     return BT;
22853   }
22854 
22855   return SDValue();
22856 }
22857 
22858 // Check if pre-AVX condcode can be performed by a single FCMP op.
cheapX86FSETCC_SSE(ISD::CondCode SetCCOpcode)22859 static bool cheapX86FSETCC_SSE(ISD::CondCode SetCCOpcode) {
22860   return (SetCCOpcode != ISD::SETONE) && (SetCCOpcode != ISD::SETUEQ);
22861 }
22862 
22863 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
22864 /// CMPs.
translateX86FSETCC(ISD::CondCode SetCCOpcode,SDValue & Op0,SDValue & Op1,bool & IsAlwaysSignaling)22865 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
22866                                    SDValue &Op1, bool &IsAlwaysSignaling) {
22867   unsigned SSECC;
22868   bool Swap = false;
22869 
22870   // SSE Condition code mapping:
22871   //  0 - EQ
22872   //  1 - LT
22873   //  2 - LE
22874   //  3 - UNORD
22875   //  4 - NEQ
22876   //  5 - NLT
22877   //  6 - NLE
22878   //  7 - ORD
22879   switch (SetCCOpcode) {
22880   default: llvm_unreachable("Unexpected SETCC condition");
22881   case ISD::SETOEQ:
22882   case ISD::SETEQ:  SSECC = 0; break;
22883   case ISD::SETOGT:
22884   case ISD::SETGT:  Swap = true; [[fallthrough]];
22885   case ISD::SETLT:
22886   case ISD::SETOLT: SSECC = 1; break;
22887   case ISD::SETOGE:
22888   case ISD::SETGE:  Swap = true; [[fallthrough]];
22889   case ISD::SETLE:
22890   case ISD::SETOLE: SSECC = 2; break;
22891   case ISD::SETUO:  SSECC = 3; break;
22892   case ISD::SETUNE:
22893   case ISD::SETNE:  SSECC = 4; break;
22894   case ISD::SETULE: Swap = true; [[fallthrough]];
22895   case ISD::SETUGE: SSECC = 5; break;
22896   case ISD::SETULT: Swap = true; [[fallthrough]];
22897   case ISD::SETUGT: SSECC = 6; break;
22898   case ISD::SETO:   SSECC = 7; break;
22899   case ISD::SETUEQ: SSECC = 8; break;
22900   case ISD::SETONE: SSECC = 12; break;
22901   }
22902   if (Swap)
22903     std::swap(Op0, Op1);
22904 
22905   switch (SetCCOpcode) {
22906   default:
22907     IsAlwaysSignaling = true;
22908     break;
22909   case ISD::SETEQ:
22910   case ISD::SETOEQ:
22911   case ISD::SETUEQ:
22912   case ISD::SETNE:
22913   case ISD::SETONE:
22914   case ISD::SETUNE:
22915   case ISD::SETO:
22916   case ISD::SETUO:
22917     IsAlwaysSignaling = false;
22918     break;
22919   }
22920 
22921   return SSECC;
22922 }
22923 
22924 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
22925 /// concatenate the result back.
splitIntVSETCC(EVT VT,SDValue LHS,SDValue RHS,ISD::CondCode Cond,SelectionDAG & DAG,const SDLoc & dl)22926 static SDValue splitIntVSETCC(EVT VT, SDValue LHS, SDValue RHS,
22927                               ISD::CondCode Cond, SelectionDAG &DAG,
22928                               const SDLoc &dl) {
22929   assert(VT.isInteger() && VT == LHS.getValueType() &&
22930          VT == RHS.getValueType() && "Unsupported VTs!");
22931 
22932   SDValue CC = DAG.getCondCode(Cond);
22933 
22934   // Extract the LHS Lo/Hi vectors
22935   SDValue LHS1, LHS2;
22936   std::tie(LHS1, LHS2) = splitVector(LHS, DAG, dl);
22937 
22938   // Extract the RHS Lo/Hi vectors
22939   SDValue RHS1, RHS2;
22940   std::tie(RHS1, RHS2) = splitVector(RHS, DAG, dl);
22941 
22942   // Issue the operation on the smaller types and concatenate the result back
22943   EVT LoVT, HiVT;
22944   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
22945   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
22946                      DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
22947                      DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
22948 }
22949 
LowerIntVSETCC_AVX512(SDValue Op,SelectionDAG & DAG)22950 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
22951 
22952   SDValue Op0 = Op.getOperand(0);
22953   SDValue Op1 = Op.getOperand(1);
22954   SDValue CC = Op.getOperand(2);
22955   MVT VT = Op.getSimpleValueType();
22956   SDLoc dl(Op);
22957 
22958   assert(VT.getVectorElementType() == MVT::i1 &&
22959          "Cannot set masked compare for this operation");
22960 
22961   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
22962 
22963   // Prefer SETGT over SETLT.
22964   if (SetCCOpcode == ISD::SETLT) {
22965     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
22966     std::swap(Op0, Op1);
22967   }
22968 
22969   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
22970 }
22971 
22972 /// Given a buildvector constant, return a new vector constant with each element
22973 /// incremented or decremented. If incrementing or decrementing would result in
22974 /// unsigned overflow or underflow or this is not a simple vector constant,
22975 /// return an empty value.
incDecVectorConstant(SDValue V,SelectionDAG & DAG,bool IsInc,bool NSW)22976 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc,
22977                                     bool NSW) {
22978   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
22979   if (!BV || !V.getValueType().isSimple())
22980     return SDValue();
22981 
22982   MVT VT = V.getSimpleValueType();
22983   MVT EltVT = VT.getVectorElementType();
22984   unsigned NumElts = VT.getVectorNumElements();
22985   SmallVector<SDValue, 8> NewVecC;
22986   SDLoc DL(V);
22987   for (unsigned i = 0; i < NumElts; ++i) {
22988     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
22989     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
22990       return SDValue();
22991 
22992     // Avoid overflow/underflow.
22993     const APInt &EltC = Elt->getAPIntValue();
22994     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isZero()))
22995       return SDValue();
22996     if (NSW && ((IsInc && EltC.isMaxSignedValue()) ||
22997                 (!IsInc && EltC.isMinSignedValue())))
22998       return SDValue();
22999 
23000     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
23001   }
23002 
23003   return DAG.getBuildVector(VT, DL, NewVecC);
23004 }
23005 
23006 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
23007 /// Op0 u<= Op1:
23008 ///   t = psubus Op0, Op1
23009 ///   pcmpeq t, <0..0>
LowerVSETCCWithSUBUS(SDValue Op0,SDValue Op1,MVT VT,ISD::CondCode Cond,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)23010 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
23011                                     ISD::CondCode Cond, const SDLoc &dl,
23012                                     const X86Subtarget &Subtarget,
23013                                     SelectionDAG &DAG) {
23014   if (!Subtarget.hasSSE2())
23015     return SDValue();
23016 
23017   MVT VET = VT.getVectorElementType();
23018   if (VET != MVT::i8 && VET != MVT::i16)
23019     return SDValue();
23020 
23021   switch (Cond) {
23022   default:
23023     return SDValue();
23024   case ISD::SETULT: {
23025     // If the comparison is against a constant we can turn this into a
23026     // setule.  With psubus, setule does not require a swap.  This is
23027     // beneficial because the constant in the register is no longer
23028     // destructed as the destination so it can be hoisted out of a loop.
23029     // Only do this pre-AVX since vpcmp* is no longer destructive.
23030     if (Subtarget.hasAVX())
23031       return SDValue();
23032     SDValue ULEOp1 =
23033         incDecVectorConstant(Op1, DAG, /*IsInc*/ false, /*NSW*/ false);
23034     if (!ULEOp1)
23035       return SDValue();
23036     Op1 = ULEOp1;
23037     break;
23038   }
23039   case ISD::SETUGT: {
23040     // If the comparison is against a constant, we can turn this into a setuge.
23041     // This is beneficial because materializing a constant 0 for the PCMPEQ is
23042     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
23043     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
23044     SDValue UGEOp1 =
23045         incDecVectorConstant(Op1, DAG, /*IsInc*/ true, /*NSW*/ false);
23046     if (!UGEOp1)
23047       return SDValue();
23048     Op1 = Op0;
23049     Op0 = UGEOp1;
23050     break;
23051   }
23052   // Psubus is better than flip-sign because it requires no inversion.
23053   case ISD::SETUGE:
23054     std::swap(Op0, Op1);
23055     break;
23056   case ISD::SETULE:
23057     break;
23058   }
23059 
23060   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
23061   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
23062                      DAG.getConstant(0, dl, VT));
23063 }
23064 
LowerVSETCC(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23065 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
23066                            SelectionDAG &DAG) {
23067   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23068                   Op.getOpcode() == ISD::STRICT_FSETCCS;
23069   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23070   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23071   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
23072   MVT VT = Op->getSimpleValueType(0);
23073   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
23074   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
23075   SDLoc dl(Op);
23076 
23077   if (isFP) {
23078     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
23079     assert(EltVT == MVT::f16 || EltVT == MVT::f32 || EltVT == MVT::f64);
23080     if (isSoftF16(EltVT, Subtarget))
23081       return SDValue();
23082 
23083     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23084     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23085 
23086     // If we have a strict compare with a vXi1 result and the input is 128/256
23087     // bits we can't use a masked compare unless we have VLX. If we use a wider
23088     // compare like we do for non-strict, we might trigger spurious exceptions
23089     // from the upper elements. Instead emit a AVX compare and convert to mask.
23090     unsigned Opc;
23091     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
23092         (!IsStrict || Subtarget.hasVLX() ||
23093          Op0.getSimpleValueType().is512BitVector())) {
23094 #ifndef NDEBUG
23095       unsigned Num = VT.getVectorNumElements();
23096       assert(Num <= 16 || (Num == 32 && EltVT == MVT::f16));
23097 #endif
23098       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
23099     } else {
23100       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
23101       // The SSE/AVX packed FP comparison nodes are defined with a
23102       // floating-point vector result that matches the operand type. This allows
23103       // them to work with an SSE1 target (integer vector types are not legal).
23104       VT = Op0.getSimpleValueType();
23105     }
23106 
23107     SDValue Cmp;
23108     bool IsAlwaysSignaling;
23109     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
23110     if (!Subtarget.hasAVX()) {
23111       // TODO: We could use following steps to handle a quiet compare with
23112       // signaling encodings.
23113       // 1. Get ordered masks from a quiet ISD::SETO
23114       // 2. Use the masks to mask potential unordered elements in operand A, B
23115       // 3. Get the compare results of masked A, B
23116       // 4. Calculating final result using the mask and result from 3
23117       // But currently, we just fall back to scalar operations.
23118       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
23119         return SDValue();
23120 
23121       // Insert an extra signaling instruction to raise exception.
23122       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
23123         SDValue SignalCmp = DAG.getNode(
23124             Opc, dl, {VT, MVT::Other},
23125             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
23126         // FIXME: It seems we need to update the flags of all new strict nodes.
23127         // Otherwise, mayRaiseFPException in MI will return false due to
23128         // NoFPExcept = false by default. However, I didn't find it in other
23129         // patches.
23130         SignalCmp->setFlags(Op->getFlags());
23131         Chain = SignalCmp.getValue(1);
23132       }
23133 
23134       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
23135       // emit two comparisons and a logic op to tie them together.
23136       if (!cheapX86FSETCC_SSE(Cond)) {
23137         // LLVM predicate is SETUEQ or SETONE.
23138         unsigned CC0, CC1;
23139         unsigned CombineOpc;
23140         if (Cond == ISD::SETUEQ) {
23141           CC0 = 3; // UNORD
23142           CC1 = 0; // EQ
23143           CombineOpc = X86ISD::FOR;
23144         } else {
23145           assert(Cond == ISD::SETONE);
23146           CC0 = 7; // ORD
23147           CC1 = 4; // NEQ
23148           CombineOpc = X86ISD::FAND;
23149         }
23150 
23151         SDValue Cmp0, Cmp1;
23152         if (IsStrict) {
23153           Cmp0 = DAG.getNode(
23154               Opc, dl, {VT, MVT::Other},
23155               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
23156           Cmp1 = DAG.getNode(
23157               Opc, dl, {VT, MVT::Other},
23158               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
23159           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
23160                               Cmp1.getValue(1));
23161         } else {
23162           Cmp0 = DAG.getNode(
23163               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
23164           Cmp1 = DAG.getNode(
23165               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
23166         }
23167         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
23168       } else {
23169         if (IsStrict) {
23170           Cmp = DAG.getNode(
23171               Opc, dl, {VT, MVT::Other},
23172               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23173           Chain = Cmp.getValue(1);
23174         } else
23175           Cmp = DAG.getNode(
23176               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23177       }
23178     } else {
23179       // Handle all other FP comparisons here.
23180       if (IsStrict) {
23181         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
23182         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
23183         Cmp = DAG.getNode(
23184             Opc, dl, {VT, MVT::Other},
23185             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
23186         Chain = Cmp.getValue(1);
23187       } else
23188         Cmp = DAG.getNode(
23189             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
23190     }
23191 
23192     if (VT.getFixedSizeInBits() >
23193         Op.getSimpleValueType().getFixedSizeInBits()) {
23194       // We emitted a compare with an XMM/YMM result. Finish converting to a
23195       // mask register using a vptestm.
23196       EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
23197       Cmp = DAG.getBitcast(CastVT, Cmp);
23198       Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
23199                          DAG.getConstant(0, dl, CastVT), ISD::SETNE);
23200     } else {
23201       // If this is SSE/AVX CMPP, bitcast the result back to integer to match
23202       // the result type of SETCC. The bitcast is expected to be optimized
23203       // away during combining/isel.
23204       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
23205     }
23206 
23207     if (IsStrict)
23208       return DAG.getMergeValues({Cmp, Chain}, dl);
23209 
23210     return Cmp;
23211   }
23212 
23213   assert(!IsStrict && "Strict SETCC only handles FP operands.");
23214 
23215   MVT VTOp0 = Op0.getSimpleValueType();
23216   (void)VTOp0;
23217   assert(VTOp0 == Op1.getSimpleValueType() &&
23218          "Expected operands with same type!");
23219   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
23220          "Invalid number of packed elements for source and destination!");
23221 
23222   // The non-AVX512 code below works under the assumption that source and
23223   // destination types are the same.
23224   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
23225          "Value types for source and destination must be the same!");
23226 
23227   // The result is boolean, but operands are int/float
23228   if (VT.getVectorElementType() == MVT::i1) {
23229     // In AVX-512 architecture setcc returns mask with i1 elements,
23230     // But there is no compare instruction for i8 and i16 elements in KNL.
23231     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
23232            "Unexpected operand type");
23233     return LowerIntVSETCC_AVX512(Op, DAG);
23234   }
23235 
23236   // Lower using XOP integer comparisons.
23237   if (VT.is128BitVector() && Subtarget.hasXOP()) {
23238     // Translate compare code to XOP PCOM compare mode.
23239     unsigned CmpMode = 0;
23240     switch (Cond) {
23241     default: llvm_unreachable("Unexpected SETCC condition");
23242     case ISD::SETULT:
23243     case ISD::SETLT: CmpMode = 0x00; break;
23244     case ISD::SETULE:
23245     case ISD::SETLE: CmpMode = 0x01; break;
23246     case ISD::SETUGT:
23247     case ISD::SETGT: CmpMode = 0x02; break;
23248     case ISD::SETUGE:
23249     case ISD::SETGE: CmpMode = 0x03; break;
23250     case ISD::SETEQ: CmpMode = 0x04; break;
23251     case ISD::SETNE: CmpMode = 0x05; break;
23252     }
23253 
23254     // Are we comparing unsigned or signed integers?
23255     unsigned Opc =
23256         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
23257 
23258     return DAG.getNode(Opc, dl, VT, Op0, Op1,
23259                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
23260   }
23261 
23262   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
23263   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
23264   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
23265     SDValue BC0 = peekThroughBitcasts(Op0);
23266     if (BC0.getOpcode() == ISD::AND) {
23267       APInt UndefElts;
23268       SmallVector<APInt, 64> EltBits;
23269       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
23270                                         VT.getScalarSizeInBits(), UndefElts,
23271                                         EltBits, false, false)) {
23272         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
23273           Cond = ISD::SETEQ;
23274           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
23275         }
23276       }
23277     }
23278   }
23279 
23280   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
23281   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
23282       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
23283     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
23284     if (C1 && C1->getAPIntValue().isPowerOf2()) {
23285       unsigned BitWidth = VT.getScalarSizeInBits();
23286       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
23287 
23288       SDValue Result = Op0.getOperand(0);
23289       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
23290                            DAG.getConstant(ShiftAmt, dl, VT));
23291       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
23292                            DAG.getConstant(BitWidth - 1, dl, VT));
23293       return Result;
23294     }
23295   }
23296 
23297   // Break 256-bit integer vector compare into smaller ones.
23298   if (VT.is256BitVector() && !Subtarget.hasInt256())
23299     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23300 
23301   // Break 512-bit integer vector compare into smaller ones.
23302   // TODO: Try harder to use VPCMPx + VPMOV2x?
23303   if (VT.is512BitVector())
23304     return splitIntVSETCC(VT, Op0, Op1, Cond, DAG, dl);
23305 
23306   // If we have a limit constant, try to form PCMPGT (signed cmp) to avoid
23307   // not-of-PCMPEQ:
23308   // X != INT_MIN --> X >s INT_MIN
23309   // X != INT_MAX --> X <s INT_MAX --> INT_MAX >s X
23310   // +X != 0 --> +X >s 0
23311   APInt ConstValue;
23312   if (Cond == ISD::SETNE &&
23313       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
23314     if (ConstValue.isMinSignedValue())
23315       Cond = ISD::SETGT;
23316     else if (ConstValue.isMaxSignedValue())
23317       Cond = ISD::SETLT;
23318     else if (ConstValue.isZero() && DAG.SignBitIsZero(Op0))
23319       Cond = ISD::SETGT;
23320   }
23321 
23322   // If both operands are known non-negative, then an unsigned compare is the
23323   // same as a signed compare and there's no need to flip signbits.
23324   // TODO: We could check for more general simplifications here since we're
23325   // computing known bits.
23326   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
23327                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
23328 
23329   // Special case: Use min/max operations for unsigned compares.
23330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23331   if (ISD::isUnsignedIntSetCC(Cond) &&
23332       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
23333       TLI.isOperationLegal(ISD::UMIN, VT)) {
23334     // If we have a constant operand, increment/decrement it and change the
23335     // condition to avoid an invert.
23336     if (Cond == ISD::SETUGT) {
23337       // X > C --> X >= (C+1) --> X == umax(X, C+1)
23338       if (SDValue UGTOp1 =
23339               incDecVectorConstant(Op1, DAG, /*IsInc*/ true, /*NSW*/ false)) {
23340         Op1 = UGTOp1;
23341         Cond = ISD::SETUGE;
23342       }
23343     }
23344     if (Cond == ISD::SETULT) {
23345       // X < C --> X <= (C-1) --> X == umin(X, C-1)
23346       if (SDValue ULTOp1 =
23347               incDecVectorConstant(Op1, DAG, /*IsInc*/ false, /*NSW*/ false)) {
23348         Op1 = ULTOp1;
23349         Cond = ISD::SETULE;
23350       }
23351     }
23352     bool Invert = false;
23353     unsigned Opc;
23354     switch (Cond) {
23355     default: llvm_unreachable("Unexpected condition code");
23356     case ISD::SETUGT: Invert = true; [[fallthrough]];
23357     case ISD::SETULE: Opc = ISD::UMIN; break;
23358     case ISD::SETULT: Invert = true; [[fallthrough]];
23359     case ISD::SETUGE: Opc = ISD::UMAX; break;
23360     }
23361 
23362     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23363     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
23364 
23365     // If the logical-not of the result is required, perform that now.
23366     if (Invert)
23367       Result = DAG.getNOT(dl, Result, VT);
23368 
23369     return Result;
23370   }
23371 
23372   // Try to use SUBUS and PCMPEQ.
23373   if (FlipSigns)
23374     if (SDValue V =
23375             LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
23376       return V;
23377 
23378   // We are handling one of the integer comparisons here. Since SSE only has
23379   // GT and EQ comparisons for integer, swapping operands and multiple
23380   // operations may be required for some comparisons.
23381   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
23382                                                             : X86ISD::PCMPGT;
23383   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
23384               Cond == ISD::SETGE || Cond == ISD::SETUGE;
23385   bool Invert = Cond == ISD::SETNE ||
23386                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
23387 
23388   if (Swap)
23389     std::swap(Op0, Op1);
23390 
23391   // Check that the operation in question is available (most are plain SSE2,
23392   // but PCMPGTQ and PCMPEQQ have different requirements).
23393   if (VT == MVT::v2i64) {
23394     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
23395       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
23396 
23397       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
23398       // the odd elements over the even elements.
23399       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
23400         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
23401         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23402 
23403         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23404         static const int MaskHi[] = { 1, 1, 3, 3 };
23405         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23406 
23407         return DAG.getBitcast(VT, Result);
23408       }
23409 
23410       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
23411         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23412         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
23413 
23414         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23415         static const int MaskHi[] = { 1, 1, 3, 3 };
23416         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23417 
23418         return DAG.getBitcast(VT, Result);
23419       }
23420 
23421       // Since SSE has no unsigned integer comparisons, we need to flip the sign
23422       // bits of the inputs before performing those operations. The lower
23423       // compare is always unsigned.
23424       SDValue SB = DAG.getConstant(FlipSigns ? 0x8000000080000000ULL
23425                                              : 0x0000000080000000ULL,
23426                                    dl, MVT::v2i64);
23427 
23428       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
23429       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
23430 
23431       // Cast everything to the right type.
23432       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23433       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23434 
23435       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
23436       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23437       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
23438 
23439       // Create masks for only the low parts/high parts of the 64 bit integers.
23440       static const int MaskHi[] = { 1, 1, 3, 3 };
23441       static const int MaskLo[] = { 0, 0, 2, 2 };
23442       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
23443       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
23444       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23445 
23446       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
23447       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
23448 
23449       if (Invert)
23450         Result = DAG.getNOT(dl, Result, MVT::v4i32);
23451 
23452       return DAG.getBitcast(VT, Result);
23453     }
23454 
23455     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
23456       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
23457       // pcmpeqd + pshufd + pand.
23458       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
23459 
23460       // First cast everything to the right type.
23461       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23462       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23463 
23464       // Do the compare.
23465       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
23466 
23467       // Make sure the lower and upper halves are both all-ones.
23468       static const int Mask[] = { 1, 0, 3, 2 };
23469       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
23470       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
23471 
23472       if (Invert)
23473         Result = DAG.getNOT(dl, Result, MVT::v4i32);
23474 
23475       return DAG.getBitcast(VT, Result);
23476     }
23477   }
23478 
23479   // Since SSE has no unsigned integer comparisons, we need to flip the sign
23480   // bits of the inputs before performing those operations.
23481   if (FlipSigns) {
23482     MVT EltVT = VT.getVectorElementType();
23483     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
23484                                  VT);
23485     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
23486     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
23487   }
23488 
23489   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23490 
23491   // If the logical-not of the result is required, perform that now.
23492   if (Invert)
23493     Result = DAG.getNOT(dl, Result, VT);
23494 
23495   return Result;
23496 }
23497 
23498 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
EmitAVX512Test(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue & X86CC)23499 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
23500                               const SDLoc &dl, SelectionDAG &DAG,
23501                               const X86Subtarget &Subtarget,
23502                               SDValue &X86CC) {
23503   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
23504 
23505   // Must be a bitcast from vXi1.
23506   if (Op0.getOpcode() != ISD::BITCAST)
23507     return SDValue();
23508 
23509   Op0 = Op0.getOperand(0);
23510   MVT VT = Op0.getSimpleValueType();
23511   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
23512       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
23513       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
23514     return SDValue();
23515 
23516   X86::CondCode X86Cond;
23517   if (isNullConstant(Op1)) {
23518     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
23519   } else if (isAllOnesConstant(Op1)) {
23520     // C flag is set for all ones.
23521     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
23522   } else
23523     return SDValue();
23524 
23525   // If the input is an AND, we can combine it's operands into the KTEST.
23526   bool KTestable = false;
23527   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
23528     KTestable = true;
23529   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
23530     KTestable = true;
23531   if (!isNullConstant(Op1))
23532     KTestable = false;
23533   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
23534     SDValue LHS = Op0.getOperand(0);
23535     SDValue RHS = Op0.getOperand(1);
23536     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23537     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
23538   }
23539 
23540   // If the input is an OR, we can combine it's operands into the KORTEST.
23541   SDValue LHS = Op0;
23542   SDValue RHS = Op0;
23543   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
23544     LHS = Op0.getOperand(0);
23545     RHS = Op0.getOperand(1);
23546   }
23547 
23548   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23549   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
23550 }
23551 
23552 /// Emit flags for the given setcc condition and operands. Also returns the
23553 /// corresponding X86 condition code constant in X86CC.
emitFlagsForSetcc(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC) const23554 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
23555                                              ISD::CondCode CC, const SDLoc &dl,
23556                                              SelectionDAG &DAG,
23557                                              SDValue &X86CC) const {
23558   // Equality Combines.
23559   if (CC == ISD::SETEQ || CC == ISD::SETNE) {
23560     X86::CondCode X86CondCode;
23561 
23562     // Optimize to BT if possible.
23563     // Lower (X & (1 << N)) == 0 to BT(X, N).
23564     // Lower ((X >>u N) & 1) != 0 to BT(X, N).
23565     // Lower ((X >>s N) & 1) != 0 to BT(X, N).
23566     if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1)) {
23567       if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CondCode)) {
23568         X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
23569         return BT;
23570       }
23571     }
23572 
23573     // Try to use PTEST/PMOVMSKB for a tree AND/ORs equality compared with -1/0.
23574     if (SDValue CmpZ = MatchVectorAllEqualTest(Op0, Op1, CC, dl, Subtarget, DAG,
23575                                                X86CondCode)) {
23576       X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
23577       return CmpZ;
23578     }
23579 
23580     // Try to lower using KORTEST or KTEST.
23581     if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
23582       return Test;
23583 
23584     // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms
23585     // of these.
23586     if (isOneConstant(Op1) || isNullConstant(Op1)) {
23587       // If the input is a setcc, then reuse the input setcc or use a new one
23588       // with the inverted condition.
23589       if (Op0.getOpcode() == X86ISD::SETCC) {
23590         bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
23591 
23592         X86CC = Op0.getOperand(0);
23593         if (Invert) {
23594           X86CondCode = (X86::CondCode)Op0.getConstantOperandVal(0);
23595           X86CondCode = X86::GetOppositeBranchCondition(X86CondCode);
23596           X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
23597         }
23598 
23599         return Op0.getOperand(1);
23600       }
23601     }
23602 
23603     // Try to use the carry flag from the add in place of an separate CMP for:
23604     // (seteq (add X, -1), -1). Similar for setne.
23605     if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
23606         Op0.getOperand(1) == Op1) {
23607       if (isProfitableToUseFlagOp(Op0)) {
23608         SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
23609 
23610         SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
23611                                   Op0.getOperand(1));
23612         DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
23613         X86CondCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
23614         X86CC = DAG.getTargetConstant(X86CondCode, dl, MVT::i8);
23615         return SDValue(New.getNode(), 1);
23616       }
23617     }
23618   }
23619 
23620   X86::CondCode CondCode =
23621       TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
23622   assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
23623 
23624   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
23625   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
23626   return EFLAGS;
23627 }
23628 
LowerSETCC(SDValue Op,SelectionDAG & DAG) const23629 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
23630 
23631   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23632                   Op.getOpcode() == ISD::STRICT_FSETCCS;
23633   MVT VT = Op->getSimpleValueType(0);
23634 
23635   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
23636 
23637   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
23638   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23639   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23640   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23641   SDLoc dl(Op);
23642   ISD::CondCode CC =
23643       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
23644 
23645   if (isSoftF16(Op0.getValueType(), Subtarget))
23646     return SDValue();
23647 
23648   // Handle f128 first, since one possible outcome is a normal integer
23649   // comparison which gets handled by emitFlagsForSetcc.
23650   if (Op0.getValueType() == MVT::f128) {
23651     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
23652                         Op.getOpcode() == ISD::STRICT_FSETCCS);
23653 
23654     // If softenSetCCOperands returned a scalar, use it.
23655     if (!Op1.getNode()) {
23656       assert(Op0.getValueType() == Op.getValueType() &&
23657              "Unexpected setcc expansion!");
23658       if (IsStrict)
23659         return DAG.getMergeValues({Op0, Chain}, dl);
23660       return Op0;
23661     }
23662   }
23663 
23664   if (Op0.getSimpleValueType().isInteger()) {
23665     // Attempt to canonicalize SGT/UGT -> SGE/UGE compares with constant which
23666     // reduces the number of EFLAGs bit reads (the GE conditions don't read ZF),
23667     // this may translate to less uops depending on uarch implementation. The
23668     // equivalent for SLE/ULE -> SLT/ULT isn't likely to happen as we already
23669     // canonicalize to that CondCode.
23670     // NOTE: Only do this if incrementing the constant doesn't increase the bit
23671     // encoding size - so it must either already be a i8 or i32 immediate, or it
23672     // shrinks down to that. We don't do this for any i64's to avoid additional
23673     // constant materializations.
23674     // TODO: Can we move this to TranslateX86CC to handle jumps/branches too?
23675     if (auto *Op1C = dyn_cast<ConstantSDNode>(Op1)) {
23676       const APInt &Op1Val = Op1C->getAPIntValue();
23677       if (!Op1Val.isZero()) {
23678         // Ensure the constant+1 doesn't overflow.
23679         if ((CC == ISD::CondCode::SETGT && !Op1Val.isMaxSignedValue()) ||
23680             (CC == ISD::CondCode::SETUGT && !Op1Val.isMaxValue())) {
23681           APInt Op1ValPlusOne = Op1Val + 1;
23682           if (Op1ValPlusOne.isSignedIntN(32) &&
23683               (!Op1Val.isSignedIntN(8) || Op1ValPlusOne.isSignedIntN(8))) {
23684             Op1 = DAG.getConstant(Op1ValPlusOne, dl, Op0.getValueType());
23685             CC = CC == ISD::CondCode::SETGT ? ISD::CondCode::SETGE
23686                                             : ISD::CondCode::SETUGE;
23687           }
23688         }
23689       }
23690     }
23691 
23692     SDValue X86CC;
23693     SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
23694     SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
23695     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
23696   }
23697 
23698   // Handle floating point.
23699   X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
23700   if (CondCode == X86::COND_INVALID)
23701     return SDValue();
23702 
23703   SDValue EFLAGS;
23704   if (IsStrict) {
23705     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23706     EFLAGS =
23707         DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
23708                     dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
23709     Chain = EFLAGS.getValue(1);
23710   } else {
23711     EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
23712   }
23713 
23714   SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
23715   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
23716   return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
23717 }
23718 
LowerSETCCCARRY(SDValue Op,SelectionDAG & DAG) const23719 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
23720   SDValue LHS = Op.getOperand(0);
23721   SDValue RHS = Op.getOperand(1);
23722   SDValue Carry = Op.getOperand(2);
23723   SDValue Cond = Op.getOperand(3);
23724   SDLoc DL(Op);
23725 
23726   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
23727   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
23728 
23729   // Recreate the carry if needed.
23730   EVT CarryVT = Carry.getValueType();
23731   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
23732                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
23733 
23734   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
23735   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
23736   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
23737 }
23738 
23739 // This function returns three things: the arithmetic computation itself
23740 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
23741 // flag and the condition code define the case in which the arithmetic
23742 // computation overflows.
23743 static std::pair<SDValue, SDValue>
getX86XALUOOp(X86::CondCode & Cond,SDValue Op,SelectionDAG & DAG)23744 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
23745   assert(Op.getResNo() == 0 && "Unexpected result number!");
23746   SDValue Value, Overflow;
23747   SDValue LHS = Op.getOperand(0);
23748   SDValue RHS = Op.getOperand(1);
23749   unsigned BaseOp = 0;
23750   SDLoc DL(Op);
23751   switch (Op.getOpcode()) {
23752   default: llvm_unreachable("Unknown ovf instruction!");
23753   case ISD::SADDO:
23754     BaseOp = X86ISD::ADD;
23755     Cond = X86::COND_O;
23756     break;
23757   case ISD::UADDO:
23758     BaseOp = X86ISD::ADD;
23759     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
23760     break;
23761   case ISD::SSUBO:
23762     BaseOp = X86ISD::SUB;
23763     Cond = X86::COND_O;
23764     break;
23765   case ISD::USUBO:
23766     BaseOp = X86ISD::SUB;
23767     Cond = X86::COND_B;
23768     break;
23769   case ISD::SMULO:
23770     BaseOp = X86ISD::SMUL;
23771     Cond = X86::COND_O;
23772     break;
23773   case ISD::UMULO:
23774     BaseOp = X86ISD::UMUL;
23775     Cond = X86::COND_O;
23776     break;
23777   }
23778 
23779   if (BaseOp) {
23780     // Also sets EFLAGS.
23781     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23782     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
23783     Overflow = Value.getValue(1);
23784   }
23785 
23786   return std::make_pair(Value, Overflow);
23787 }
23788 
LowerXALUO(SDValue Op,SelectionDAG & DAG)23789 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
23790   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
23791   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
23792   // looks for this combo and may remove the "setcc" instruction if the "setcc"
23793   // has only one use.
23794   SDLoc DL(Op);
23795   X86::CondCode Cond;
23796   SDValue Value, Overflow;
23797   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
23798 
23799   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
23800   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
23801   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
23802 }
23803 
23804 /// Return true if opcode is a X86 logical comparison.
isX86LogicalCmp(SDValue Op)23805 static bool isX86LogicalCmp(SDValue Op) {
23806   unsigned Opc = Op.getOpcode();
23807   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
23808       Opc == X86ISD::FCMP)
23809     return true;
23810   if (Op.getResNo() == 1 &&
23811       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
23812        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
23813        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
23814     return true;
23815 
23816   return false;
23817 }
23818 
isTruncWithZeroHighBitsInput(SDValue V,SelectionDAG & DAG)23819 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
23820   if (V.getOpcode() != ISD::TRUNCATE)
23821     return false;
23822 
23823   SDValue VOp0 = V.getOperand(0);
23824   unsigned InBits = VOp0.getValueSizeInBits();
23825   unsigned Bits = V.getValueSizeInBits();
23826   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
23827 }
23828 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const23829 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
23830   bool AddTest = true;
23831   SDValue Cond  = Op.getOperand(0);
23832   SDValue Op1 = Op.getOperand(1);
23833   SDValue Op2 = Op.getOperand(2);
23834   SDLoc DL(Op);
23835   MVT VT = Op1.getSimpleValueType();
23836   SDValue CC;
23837 
23838   if (isSoftF16(VT, Subtarget)) {
23839     MVT NVT = VT.changeTypeToInteger();
23840     return DAG.getBitcast(VT, DAG.getNode(ISD::SELECT, DL, NVT, Cond,
23841                                           DAG.getBitcast(NVT, Op1),
23842                                           DAG.getBitcast(NVT, Op2)));
23843   }
23844 
23845   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
23846   // are available or VBLENDV if AVX is available.
23847   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
23848   if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
23849       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
23850     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
23851     bool IsAlwaysSignaling;
23852     unsigned SSECC =
23853         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
23854                            CondOp0, CondOp1, IsAlwaysSignaling);
23855 
23856     if (Subtarget.hasAVX512()) {
23857       SDValue Cmp =
23858           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
23859                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
23860       assert(!VT.isVector() && "Not a scalar type?");
23861       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23862     }
23863 
23864     if (SSECC < 8 || Subtarget.hasAVX()) {
23865       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
23866                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
23867 
23868       // If we have AVX, we can use a variable vector select (VBLENDV) instead
23869       // of 3 logic instructions for size savings and potentially speed.
23870       // Unfortunately, there is no scalar form of VBLENDV.
23871 
23872       // If either operand is a +0.0 constant, don't try this. We can expect to
23873       // optimize away at least one of the logic instructions later in that
23874       // case, so that sequence would be faster than a variable blend.
23875 
23876       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
23877       // uses XMM0 as the selection register. That may need just as many
23878       // instructions as the AND/ANDN/OR sequence due to register moves, so
23879       // don't bother.
23880       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
23881           !isNullFPConstant(Op2)) {
23882         // Convert to vectors, do a VSELECT, and convert back to scalar.
23883         // All of the conversions should be optimized away.
23884         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
23885         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
23886         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
23887         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
23888 
23889         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
23890         VCmp = DAG.getBitcast(VCmpVT, VCmp);
23891 
23892         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
23893 
23894         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
23895                            VSel, DAG.getIntPtrConstant(0, DL));
23896       }
23897       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
23898       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
23899       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
23900     }
23901   }
23902 
23903   // AVX512 fallback is to lower selects of scalar floats to masked moves.
23904   if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
23905     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
23906     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23907   }
23908 
23909   if (Cond.getOpcode() == ISD::SETCC &&
23910       !isSoftF16(Cond.getOperand(0).getSimpleValueType(), Subtarget)) {
23911     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
23912       Cond = NewCond;
23913       // If the condition was updated, it's possible that the operands of the
23914       // select were also updated (for example, EmitTest has a RAUW). Refresh
23915       // the local references to the select operands in case they got stale.
23916       Op1 = Op.getOperand(1);
23917       Op2 = Op.getOperand(2);
23918     }
23919   }
23920 
23921   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
23922   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
23923   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
23924   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
23925   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
23926   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
23927   // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
23928   // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
23929   if (Cond.getOpcode() == X86ISD::SETCC &&
23930       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
23931       isNullConstant(Cond.getOperand(1).getOperand(1))) {
23932     SDValue Cmp = Cond.getOperand(1);
23933     SDValue CmpOp0 = Cmp.getOperand(0);
23934     unsigned CondCode = Cond.getConstantOperandVal(0);
23935 
23936     // Special handling for __builtin_ffs(X) - 1 pattern which looks like
23937     // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
23938     // handle to keep the CMP with 0. This should be removed by
23939     // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
23940     // cttz_zero_undef.
23941     auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
23942       return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
23943               Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
23944     };
23945     if (Subtarget.canUseCMOV() && (VT == MVT::i32 || VT == MVT::i64) &&
23946         ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
23947          (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
23948       // Keep Cmp.
23949     } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
23950         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
23951       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
23952       SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
23953 
23954       // 'X - 1' sets the carry flag if X == 0.
23955       // '0 - X' sets the carry flag if X != 0.
23956       // Convert the carry flag to a -1/0 mask with sbb:
23957       // select (X != 0), -1, Y --> 0 - X; or (sbb), Y
23958       // select (X == 0), Y, -1 --> 0 - X; or (sbb), Y
23959       // select (X != 0), Y, -1 --> X - 1; or (sbb), Y
23960       // select (X == 0), -1, Y --> X - 1; or (sbb), Y
23961       SDValue Sub;
23962       if (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE)) {
23963         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
23964         Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
23965       } else {
23966         SDValue One = DAG.getConstant(1, DL, CmpOp0.getValueType());
23967         Sub = DAG.getNode(X86ISD::SUB, DL, CmpVTs, CmpOp0, One);
23968       }
23969       SDValue SBB = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23970                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
23971                                 Sub.getValue(1));
23972       return DAG.getNode(ISD::OR, DL, VT, SBB, Y);
23973     } else if (!Subtarget.canUseCMOV() && CondCode == X86::COND_E &&
23974                CmpOp0.getOpcode() == ISD::AND &&
23975                isOneConstant(CmpOp0.getOperand(1))) {
23976       SDValue Src1, Src2;
23977       // true if Op2 is XOR or OR operator and one of its operands
23978       // is equal to Op1
23979       // ( a , a op b) || ( b , a op b)
23980       auto isOrXorPattern = [&]() {
23981         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
23982             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
23983           Src1 =
23984               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
23985           Src2 = Op1;
23986           return true;
23987         }
23988         return false;
23989       };
23990 
23991       if (isOrXorPattern()) {
23992         SDValue Neg;
23993         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
23994         // we need mask of all zeros or ones with same size of the other
23995         // operands.
23996         if (CmpSz > VT.getSizeInBits())
23997           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
23998         else if (CmpSz < VT.getSizeInBits())
23999           Neg = DAG.getNode(ISD::AND, DL, VT,
24000               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
24001               DAG.getConstant(1, DL, VT));
24002         else
24003           Neg = CmpOp0;
24004         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
24005                                    Neg); // -(and (x, 0x1))
24006         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
24007         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
24008       }
24009     } else if ((VT == MVT::i32 || VT == MVT::i64) && isNullConstant(Op2) &&
24010                Cmp.getNode()->hasOneUse() && (CmpOp0 == Op1) &&
24011                ((CondCode == X86::COND_S) ||                    // smin(x, 0)
24012                 (CondCode == X86::COND_G && hasAndNot(Op1)))) { // smax(x, 0)
24013       // (select (x < 0), x, 0) -> ((x >> (size_in_bits(x)-1))) & x
24014       //
24015       // If the comparison is testing for a positive value, we have to invert
24016       // the sign bit mask, so only do that transform if the target has a
24017       // bitwise 'and not' instruction (the invert is free).
24018       // (select (x > 0), x, 0) -> (~(x >> (size_in_bits(x)-1))) & x
24019       unsigned ShCt = VT.getSizeInBits() - 1;
24020       SDValue ShiftAmt = DAG.getConstant(ShCt, DL, VT);
24021       SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, Op1, ShiftAmt);
24022       if (CondCode == X86::COND_G)
24023         Shift = DAG.getNOT(DL, Shift, VT);
24024       return DAG.getNode(ISD::AND, DL, VT, Shift, Op1);
24025     }
24026   }
24027 
24028   // Look past (and (setcc_carry (cmp ...)), 1).
24029   if (Cond.getOpcode() == ISD::AND &&
24030       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
24031       isOneConstant(Cond.getOperand(1)))
24032     Cond = Cond.getOperand(0);
24033 
24034   // If condition flag is set by a X86ISD::CMP, then use it as the condition
24035   // setting operand in place of the X86ISD::SETCC.
24036   unsigned CondOpcode = Cond.getOpcode();
24037   if (CondOpcode == X86ISD::SETCC ||
24038       CondOpcode == X86ISD::SETCC_CARRY) {
24039     CC = Cond.getOperand(0);
24040 
24041     SDValue Cmp = Cond.getOperand(1);
24042     bool IllegalFPCMov = false;
24043     if (VT.isFloatingPoint() && !VT.isVector() &&
24044         !isScalarFPTypeInSSEReg(VT) && Subtarget.canUseCMOV())  // FPStack?
24045       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
24046 
24047     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
24048         Cmp.getOpcode() == X86ISD::BT) { // FIXME
24049       Cond = Cmp;
24050       AddTest = false;
24051     }
24052   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
24053              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
24054              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
24055     SDValue Value;
24056     X86::CondCode X86Cond;
24057     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
24058 
24059     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
24060     AddTest = false;
24061   }
24062 
24063   if (AddTest) {
24064     // Look past the truncate if the high bits are known zero.
24065     if (isTruncWithZeroHighBitsInput(Cond, DAG))
24066       Cond = Cond.getOperand(0);
24067 
24068     // We know the result of AND is compared against zero. Try to match
24069     // it to BT.
24070     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
24071       X86::CondCode X86CondCode;
24072       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, X86CondCode)) {
24073         CC = DAG.getTargetConstant(X86CondCode, DL, MVT::i8);
24074         Cond = BT;
24075         AddTest = false;
24076       }
24077     }
24078   }
24079 
24080   if (AddTest) {
24081     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
24082     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
24083   }
24084 
24085   // a <  b ? -1 :  0 -> RES = ~setcc_carry
24086   // a <  b ?  0 : -1 -> RES = setcc_carry
24087   // a >= b ? -1 :  0 -> RES = setcc_carry
24088   // a >= b ?  0 : -1 -> RES = ~setcc_carry
24089   if (Cond.getOpcode() == X86ISD::SUB) {
24090     unsigned CondCode = CC->getAsZExtVal();
24091 
24092     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
24093         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
24094         (isNullConstant(Op1) || isNullConstant(Op2))) {
24095       SDValue Res =
24096           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
24097                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
24098       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
24099         return DAG.getNOT(DL, Res, Res.getValueType());
24100       return Res;
24101     }
24102   }
24103 
24104   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
24105   // widen the cmov and push the truncate through. This avoids introducing a new
24106   // branch during isel and doesn't add any extensions.
24107   if (Op.getValueType() == MVT::i8 &&
24108       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
24109     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
24110     if (T1.getValueType() == T2.getValueType() &&
24111         // Exclude CopyFromReg to avoid partial register stalls.
24112         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
24113       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
24114                                  CC, Cond);
24115       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24116     }
24117   }
24118 
24119   // Or finally, promote i8 cmovs if we have CMOV,
24120   //                 or i16 cmovs if it won't prevent folding a load.
24121   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
24122   //        legal, but EmitLoweredSelect() can not deal with these extensions
24123   //        being inserted between two CMOV's. (in i16 case too TBN)
24124   //        https://bugs.llvm.org/show_bug.cgi?id=40974
24125   if ((Op.getValueType() == MVT::i8 && Subtarget.canUseCMOV()) ||
24126       (Op.getValueType() == MVT::i16 && !X86::mayFoldLoad(Op1, Subtarget) &&
24127        !X86::mayFoldLoad(Op2, Subtarget))) {
24128     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
24129     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
24130     SDValue Ops[] = { Op2, Op1, CC, Cond };
24131     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
24132     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
24133   }
24134 
24135   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
24136   // condition is true.
24137   SDValue Ops[] = { Op2, Op1, CC, Cond };
24138   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops, Op->getFlags());
24139 }
24140 
LowerSIGN_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24141 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
24142                                      const X86Subtarget &Subtarget,
24143                                      SelectionDAG &DAG) {
24144   MVT VT = Op->getSimpleValueType(0);
24145   SDValue In = Op->getOperand(0);
24146   MVT InVT = In.getSimpleValueType();
24147   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
24148   MVT VTElt = VT.getVectorElementType();
24149   SDLoc dl(Op);
24150 
24151   unsigned NumElts = VT.getVectorNumElements();
24152 
24153   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
24154   MVT ExtVT = VT;
24155   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
24156     // If v16i32 is to be avoided, we'll need to split and concatenate.
24157     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
24158       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
24159 
24160     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
24161   }
24162 
24163   // Widen to 512-bits if VLX is not supported.
24164   MVT WideVT = ExtVT;
24165   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
24166     NumElts *= 512 / ExtVT.getSizeInBits();
24167     InVT = MVT::getVectorVT(MVT::i1, NumElts);
24168     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
24169                      In, DAG.getIntPtrConstant(0, dl));
24170     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
24171   }
24172 
24173   SDValue V;
24174   MVT WideEltVT = WideVT.getVectorElementType();
24175   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
24176       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
24177     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
24178   } else {
24179     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
24180     SDValue Zero = DAG.getConstant(0, dl, WideVT);
24181     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
24182   }
24183 
24184   // Truncate if we had to extend i16/i8 above.
24185   if (VT != ExtVT) {
24186     WideVT = MVT::getVectorVT(VTElt, NumElts);
24187     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
24188   }
24189 
24190   // Extract back to 128/256-bit if we widened.
24191   if (WideVT != VT)
24192     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
24193                     DAG.getIntPtrConstant(0, dl));
24194 
24195   return V;
24196 }
24197 
LowerANY_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24198 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24199                                SelectionDAG &DAG) {
24200   SDValue In = Op->getOperand(0);
24201   MVT InVT = In.getSimpleValueType();
24202 
24203   if (InVT.getVectorElementType() == MVT::i1)
24204     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24205 
24206   assert(Subtarget.hasAVX() && "Expected AVX support");
24207   return LowerAVXExtend(Op, DAG, Subtarget);
24208 }
24209 
24210 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
24211 // For sign extend this needs to handle all vector sizes and SSE4.1 and
24212 // non-SSE4.1 targets. For zero extend this should only handle inputs of
24213 // MVT::v64i8 when BWI is not supported, but AVX512 is.
LowerEXTEND_VECTOR_INREG(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24214 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
24215                                         const X86Subtarget &Subtarget,
24216                                         SelectionDAG &DAG) {
24217   SDValue In = Op->getOperand(0);
24218   MVT VT = Op->getSimpleValueType(0);
24219   MVT InVT = In.getSimpleValueType();
24220 
24221   MVT SVT = VT.getVectorElementType();
24222   MVT InSVT = InVT.getVectorElementType();
24223   assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits());
24224 
24225   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
24226     return SDValue();
24227   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
24228     return SDValue();
24229   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
24230       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
24231       !(VT.is512BitVector() && Subtarget.hasAVX512()))
24232     return SDValue();
24233 
24234   SDLoc dl(Op);
24235   unsigned Opc = Op.getOpcode();
24236   unsigned NumElts = VT.getVectorNumElements();
24237 
24238   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
24239   // For 512-bit vectors, we need 128-bits or 256-bits.
24240   if (InVT.getSizeInBits() > 128) {
24241     // Input needs to be at least the same number of elements as output, and
24242     // at least 128-bits.
24243     int InSize = InSVT.getSizeInBits() * NumElts;
24244     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
24245     InVT = In.getSimpleValueType();
24246   }
24247 
24248   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
24249   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
24250   // need to be handled here for 256/512-bit results.
24251   if (Subtarget.hasInt256()) {
24252     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
24253 
24254     if (InVT.getVectorNumElements() != NumElts)
24255       return DAG.getNode(Op.getOpcode(), dl, VT, In);
24256 
24257     // FIXME: Apparently we create inreg operations that could be regular
24258     // extends.
24259     unsigned ExtOpc =
24260         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
24261                                              : ISD::ZERO_EXTEND;
24262     return DAG.getNode(ExtOpc, dl, VT, In);
24263   }
24264 
24265   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
24266   if (Subtarget.hasAVX()) {
24267     assert(VT.is256BitVector() && "256-bit vector expected");
24268     MVT HalfVT = VT.getHalfNumVectorElementsVT();
24269     int HalfNumElts = HalfVT.getVectorNumElements();
24270 
24271     unsigned NumSrcElts = InVT.getVectorNumElements();
24272     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
24273     for (int i = 0; i != HalfNumElts; ++i)
24274       HiMask[i] = HalfNumElts + i;
24275 
24276     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
24277     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
24278     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
24279     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
24280   }
24281 
24282   // We should only get here for sign extend.
24283   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
24284   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
24285   unsigned InNumElts = InVT.getVectorNumElements();
24286 
24287   // If the source elements are already all-signbits, we don't need to extend,
24288   // just splat the elements.
24289   APInt DemandedElts = APInt::getLowBitsSet(InNumElts, NumElts);
24290   if (DAG.ComputeNumSignBits(In, DemandedElts) == InVT.getScalarSizeInBits()) {
24291     unsigned Scale = InNumElts / NumElts;
24292     SmallVector<int, 16> ShuffleMask;
24293     for (unsigned I = 0; I != NumElts; ++I)
24294       ShuffleMask.append(Scale, I);
24295     return DAG.getBitcast(VT,
24296                           DAG.getVectorShuffle(InVT, dl, In, In, ShuffleMask));
24297   }
24298 
24299   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
24300   SDValue Curr = In;
24301   SDValue SignExt = Curr;
24302 
24303   // As SRAI is only available on i16/i32 types, we expand only up to i32
24304   // and handle i64 separately.
24305   if (InVT != MVT::v4i32) {
24306     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
24307 
24308     unsigned DestWidth = DestVT.getScalarSizeInBits();
24309     unsigned Scale = DestWidth / InSVT.getSizeInBits();
24310     unsigned DestElts = DestVT.getVectorNumElements();
24311 
24312     // Build a shuffle mask that takes each input element and places it in the
24313     // MSBs of the new element size.
24314     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
24315     for (unsigned i = 0; i != DestElts; ++i)
24316       Mask[i * Scale + (Scale - 1)] = i;
24317 
24318     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
24319     Curr = DAG.getBitcast(DestVT, Curr);
24320 
24321     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
24322     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
24323                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
24324   }
24325 
24326   if (VT == MVT::v2i64) {
24327     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
24328     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
24329     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
24330     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
24331     SignExt = DAG.getBitcast(VT, SignExt);
24332   }
24333 
24334   return SignExt;
24335 }
24336 
LowerSIGN_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24337 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24338                                 SelectionDAG &DAG) {
24339   MVT VT = Op->getSimpleValueType(0);
24340   SDValue In = Op->getOperand(0);
24341   MVT InVT = In.getSimpleValueType();
24342   SDLoc dl(Op);
24343 
24344   if (InVT.getVectorElementType() == MVT::i1)
24345     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24346 
24347   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
24348   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
24349          "Expected same number of elements");
24350   assert((VT.getVectorElementType() == MVT::i16 ||
24351           VT.getVectorElementType() == MVT::i32 ||
24352           VT.getVectorElementType() == MVT::i64) &&
24353          "Unexpected element type");
24354   assert((InVT.getVectorElementType() == MVT::i8 ||
24355           InVT.getVectorElementType() == MVT::i16 ||
24356           InVT.getVectorElementType() == MVT::i32) &&
24357          "Unexpected element type");
24358 
24359   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
24360     assert(InVT == MVT::v32i8 && "Unexpected VT!");
24361     return splitVectorIntUnary(Op, DAG);
24362   }
24363 
24364   if (Subtarget.hasInt256())
24365     return Op;
24366 
24367   // Optimize vectors in AVX mode
24368   // Sign extend  v8i16 to v8i32 and
24369   //              v4i32 to v4i64
24370   //
24371   // Divide input vector into two parts
24372   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
24373   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
24374   // concat the vectors to original VT
24375   MVT HalfVT = VT.getHalfNumVectorElementsVT();
24376   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
24377 
24378   unsigned NumElems = InVT.getVectorNumElements();
24379   SmallVector<int,8> ShufMask(NumElems, -1);
24380   for (unsigned i = 0; i != NumElems/2; ++i)
24381     ShufMask[i] = i + NumElems/2;
24382 
24383   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
24384   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
24385 
24386   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
24387 }
24388 
24389 /// Change a vector store into a pair of half-size vector stores.
splitVectorStore(StoreSDNode * Store,SelectionDAG & DAG)24390 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
24391   SDValue StoredVal = Store->getValue();
24392   assert((StoredVal.getValueType().is256BitVector() ||
24393           StoredVal.getValueType().is512BitVector()) &&
24394          "Expecting 256/512-bit op");
24395 
24396   // Splitting volatile memory ops is not allowed unless the operation was not
24397   // legal to begin with. Assume the input store is legal (this transform is
24398   // only used for targets with AVX). Note: It is possible that we have an
24399   // illegal type like v2i128, and so we could allow splitting a volatile store
24400   // in that case if that is important.
24401   if (!Store->isSimple())
24402     return SDValue();
24403 
24404   SDLoc DL(Store);
24405   SDValue Value0, Value1;
24406   std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
24407   unsigned HalfOffset = Value0.getValueType().getStoreSize();
24408   SDValue Ptr0 = Store->getBasePtr();
24409   SDValue Ptr1 =
24410       DAG.getMemBasePlusOffset(Ptr0, TypeSize::getFixed(HalfOffset), DL);
24411   SDValue Ch0 =
24412       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
24413                    Store->getOriginalAlign(),
24414                    Store->getMemOperand()->getFlags());
24415   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
24416                              Store->getPointerInfo().getWithOffset(HalfOffset),
24417                              Store->getOriginalAlign(),
24418                              Store->getMemOperand()->getFlags());
24419   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
24420 }
24421 
24422 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
24423 /// type.
scalarizeVectorStore(StoreSDNode * Store,MVT StoreVT,SelectionDAG & DAG)24424 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
24425                                     SelectionDAG &DAG) {
24426   SDValue StoredVal = Store->getValue();
24427   assert(StoreVT.is128BitVector() &&
24428          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
24429   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
24430 
24431   // Splitting volatile memory ops is not allowed unless the operation was not
24432   // legal to begin with. We are assuming the input op is legal (this transform
24433   // is only used for targets with AVX).
24434   if (!Store->isSimple())
24435     return SDValue();
24436 
24437   MVT StoreSVT = StoreVT.getScalarType();
24438   unsigned NumElems = StoreVT.getVectorNumElements();
24439   unsigned ScalarSize = StoreSVT.getStoreSize();
24440 
24441   SDLoc DL(Store);
24442   SmallVector<SDValue, 4> Stores;
24443   for (unsigned i = 0; i != NumElems; ++i) {
24444     unsigned Offset = i * ScalarSize;
24445     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(),
24446                                            TypeSize::getFixed(Offset), DL);
24447     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
24448                               DAG.getIntPtrConstant(i, DL));
24449     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
24450                               Store->getPointerInfo().getWithOffset(Offset),
24451                               Store->getOriginalAlign(),
24452                               Store->getMemOperand()->getFlags());
24453     Stores.push_back(Ch);
24454   }
24455   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
24456 }
24457 
LowerStore(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24458 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
24459                           SelectionDAG &DAG) {
24460   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
24461   SDLoc dl(St);
24462   SDValue StoredVal = St->getValue();
24463 
24464   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
24465   if (StoredVal.getValueType().isVector() &&
24466       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
24467     unsigned NumElts = StoredVal.getValueType().getVectorNumElements();
24468     assert(NumElts <= 8 && "Unexpected VT");
24469     assert(!St->isTruncatingStore() && "Expected non-truncating store");
24470     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
24471            "Expected AVX512F without AVX512DQI");
24472 
24473     // We must pad with zeros to ensure we store zeroes to any unused bits.
24474     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
24475                             DAG.getUNDEF(MVT::v16i1), StoredVal,
24476                             DAG.getIntPtrConstant(0, dl));
24477     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
24478     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
24479     // Make sure we store zeros in the extra bits.
24480     if (NumElts < 8)
24481       StoredVal = DAG.getZeroExtendInReg(
24482           StoredVal, dl, EVT::getIntegerVT(*DAG.getContext(), NumElts));
24483 
24484     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
24485                         St->getPointerInfo(), St->getOriginalAlign(),
24486                         St->getMemOperand()->getFlags());
24487   }
24488 
24489   if (St->isTruncatingStore())
24490     return SDValue();
24491 
24492   // If this is a 256-bit store of concatenated ops, we are better off splitting
24493   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
24494   // and each half can execute independently. Some cores would split the op into
24495   // halves anyway, so the concat (vinsertf128) is purely an extra op.
24496   MVT StoreVT = StoredVal.getSimpleValueType();
24497   if (StoreVT.is256BitVector() ||
24498       ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
24499        !Subtarget.hasBWI())) {
24500     if (StoredVal.hasOneUse() && isFreeToSplitVector(StoredVal.getNode(), DAG))
24501       return splitVectorStore(St, DAG);
24502     return SDValue();
24503   }
24504 
24505   if (StoreVT.is32BitVector())
24506     return SDValue();
24507 
24508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24509   assert(StoreVT.is64BitVector() && "Unexpected VT");
24510   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
24511              TargetLowering::TypeWidenVector &&
24512          "Unexpected type action!");
24513 
24514   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
24515   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
24516                           DAG.getUNDEF(StoreVT));
24517 
24518   if (Subtarget.hasSSE2()) {
24519     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
24520     // and store it.
24521     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
24522     MVT CastVT = MVT::getVectorVT(StVT, 2);
24523     StoredVal = DAG.getBitcast(CastVT, StoredVal);
24524     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
24525                             DAG.getIntPtrConstant(0, dl));
24526 
24527     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
24528                         St->getPointerInfo(), St->getOriginalAlign(),
24529                         St->getMemOperand()->getFlags());
24530   }
24531   assert(Subtarget.hasSSE1() && "Expected SSE");
24532   SDVTList Tys = DAG.getVTList(MVT::Other);
24533   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
24534   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
24535                                  St->getMemOperand());
24536 }
24537 
24538 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
24539 // may emit an illegal shuffle but the expansion is still better than scalar
24540 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
24541 // we'll emit a shuffle and a arithmetic shift.
24542 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
24543 // TODO: It is possible to support ZExt by zeroing the undef values during
24544 // the shuffle phase or after the shuffle.
LowerLoad(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24545 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
24546                                  SelectionDAG &DAG) {
24547   MVT RegVT = Op.getSimpleValueType();
24548   assert(RegVT.isVector() && "We only custom lower vector loads.");
24549   assert(RegVT.isInteger() &&
24550          "We only custom lower integer vector loads.");
24551 
24552   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
24553   SDLoc dl(Ld);
24554 
24555   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
24556   if (RegVT.getVectorElementType() == MVT::i1) {
24557     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
24558     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
24559     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
24560            "Expected AVX512F without AVX512DQI");
24561 
24562     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
24563                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
24564                                 Ld->getMemOperand()->getFlags());
24565 
24566     // Replace chain users with the new chain.
24567     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
24568 
24569     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
24570     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
24571                       DAG.getBitcast(MVT::v16i1, Val),
24572                       DAG.getIntPtrConstant(0, dl));
24573     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
24574   }
24575 
24576   return SDValue();
24577 }
24578 
24579 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
24580 /// each of which has no other use apart from the AND / OR.
isAndOrOfSetCCs(SDValue Op,unsigned & Opc)24581 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
24582   Opc = Op.getOpcode();
24583   if (Opc != ISD::OR && Opc != ISD::AND)
24584     return false;
24585   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
24586           Op.getOperand(0).hasOneUse() &&
24587           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
24588           Op.getOperand(1).hasOneUse());
24589 }
24590 
LowerBRCOND(SDValue Op,SelectionDAG & DAG) const24591 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
24592   SDValue Chain = Op.getOperand(0);
24593   SDValue Cond  = Op.getOperand(1);
24594   SDValue Dest  = Op.getOperand(2);
24595   SDLoc dl(Op);
24596 
24597   // Bail out when we don't have native compare instructions.
24598   if (Cond.getOpcode() == ISD::SETCC &&
24599       Cond.getOperand(0).getValueType() != MVT::f128 &&
24600       !isSoftF16(Cond.getOperand(0).getValueType(), Subtarget)) {
24601     SDValue LHS = Cond.getOperand(0);
24602     SDValue RHS = Cond.getOperand(1);
24603     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24604 
24605     // Special case for
24606     // setcc([su]{add,sub,mul}o == 0)
24607     // setcc([su]{add,sub,mul}o != 1)
24608     if (ISD::isOverflowIntrOpRes(LHS) &&
24609         (CC == ISD::SETEQ || CC == ISD::SETNE) &&
24610         (isNullConstant(RHS) || isOneConstant(RHS))) {
24611       SDValue Value, Overflow;
24612       X86::CondCode X86Cond;
24613       std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
24614 
24615       if ((CC == ISD::SETEQ) == isNullConstant(RHS))
24616         X86Cond = X86::GetOppositeBranchCondition(X86Cond);
24617 
24618       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24619       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24620                          Overflow);
24621     }
24622 
24623     if (LHS.getSimpleValueType().isInteger()) {
24624       SDValue CCVal;
24625       SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
24626       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24627                          EFLAGS);
24628     }
24629 
24630     if (CC == ISD::SETOEQ) {
24631       // For FCMP_OEQ, we can emit
24632       // two branches instead of an explicit AND instruction with a
24633       // separate test. However, we only do this if this block doesn't
24634       // have a fall-through edge, because this requires an explicit
24635       // jmp when the condition is false.
24636       if (Op.getNode()->hasOneUse()) {
24637         SDNode *User = *Op.getNode()->use_begin();
24638         // Look for an unconditional branch following this conditional branch.
24639         // We need this because we need to reverse the successors in order
24640         // to implement FCMP_OEQ.
24641         if (User->getOpcode() == ISD::BR) {
24642           SDValue FalseBB = User->getOperand(1);
24643           SDNode *NewBR =
24644             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
24645           assert(NewBR == User);
24646           (void)NewBR;
24647           Dest = FalseBB;
24648 
24649           SDValue Cmp =
24650               DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24651           SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
24652           Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
24653                               CCVal, Cmp);
24654           CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
24655           return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24656                              Cmp);
24657         }
24658       }
24659     } else if (CC == ISD::SETUNE) {
24660       // For FCMP_UNE, we can emit
24661       // two branches instead of an explicit OR instruction with a
24662       // separate test.
24663       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24664       SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
24665       Chain =
24666           DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
24667       CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
24668       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24669                          Cmp);
24670     } else {
24671       X86::CondCode X86Cond =
24672           TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
24673       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24674       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24675       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24676                          Cmp);
24677     }
24678   }
24679 
24680   if (ISD::isOverflowIntrOpRes(Cond)) {
24681     SDValue Value, Overflow;
24682     X86::CondCode X86Cond;
24683     std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
24684 
24685     SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24686     return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24687                        Overflow);
24688   }
24689 
24690   // Look past the truncate if the high bits are known zero.
24691   if (isTruncWithZeroHighBitsInput(Cond, DAG))
24692     Cond = Cond.getOperand(0);
24693 
24694   EVT CondVT = Cond.getValueType();
24695 
24696   // Add an AND with 1 if we don't already have one.
24697   if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
24698     Cond =
24699         DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
24700 
24701   SDValue LHS = Cond;
24702   SDValue RHS = DAG.getConstant(0, dl, CondVT);
24703 
24704   SDValue CCVal;
24705   SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
24706   return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24707                      EFLAGS);
24708 }
24709 
24710 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
24711 // Calls to _alloca are needed to probe the stack when allocating more than 4k
24712 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
24713 // that the guard pages used by the OS virtual memory manager are allocated in
24714 // correct sequence.
24715 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const24716 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
24717                                            SelectionDAG &DAG) const {
24718   MachineFunction &MF = DAG.getMachineFunction();
24719   bool SplitStack = MF.shouldSplitStack();
24720   bool EmitStackProbeCall = hasStackProbeSymbol(MF);
24721   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
24722                SplitStack || EmitStackProbeCall;
24723   SDLoc dl(Op);
24724 
24725   // Get the inputs.
24726   SDNode *Node = Op.getNode();
24727   SDValue Chain = Op.getOperand(0);
24728   SDValue Size  = Op.getOperand(1);
24729   MaybeAlign Alignment(Op.getConstantOperandVal(2));
24730   EVT VT = Node->getValueType(0);
24731 
24732   // Chain the dynamic stack allocation so that it doesn't modify the stack
24733   // pointer when other instructions are using the stack.
24734   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
24735 
24736   bool Is64Bit = Subtarget.is64Bit();
24737   MVT SPTy = getPointerTy(DAG.getDataLayout());
24738 
24739   SDValue Result;
24740   if (!Lower) {
24741     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24742     Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
24743     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
24744                     " not tell us which reg is the stack pointer!");
24745 
24746     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
24747     const Align StackAlign = TFI.getStackAlign();
24748     if (hasInlineStackProbe(MF)) {
24749       MachineRegisterInfo &MRI = MF.getRegInfo();
24750 
24751       const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
24752       Register Vreg = MRI.createVirtualRegister(AddrRegClass);
24753       Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
24754       Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
24755                            DAG.getRegister(Vreg, SPTy));
24756     } else {
24757       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
24758       Chain = SP.getValue(1);
24759       Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
24760     }
24761     if (Alignment && *Alignment > StackAlign)
24762       Result =
24763           DAG.getNode(ISD::AND, dl, VT, Result,
24764                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
24765     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
24766   } else if (SplitStack) {
24767     MachineRegisterInfo &MRI = MF.getRegInfo();
24768 
24769     if (Is64Bit) {
24770       // The 64 bit implementation of segmented stacks needs to clobber both r10
24771       // r11. This makes it impossible to use it along with nested parameters.
24772       const Function &F = MF.getFunction();
24773       for (const auto &A : F.args()) {
24774         if (A.hasNestAttr())
24775           report_fatal_error("Cannot use segmented stacks with functions that "
24776                              "have nested arguments.");
24777       }
24778     }
24779 
24780     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
24781     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
24782     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
24783     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
24784                                 DAG.getRegister(Vreg, SPTy));
24785   } else {
24786     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
24787     Chain = DAG.getNode(X86ISD::DYN_ALLOCA, dl, NodeTys, Chain, Size);
24788     MF.getInfo<X86MachineFunctionInfo>()->setHasDynAlloca(true);
24789 
24790     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
24791     Register SPReg = RegInfo->getStackRegister();
24792     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
24793     Chain = SP.getValue(1);
24794 
24795     if (Alignment) {
24796       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
24797                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
24798       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
24799     }
24800 
24801     Result = SP;
24802   }
24803 
24804   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
24805 
24806   SDValue Ops[2] = {Result, Chain};
24807   return DAG.getMergeValues(Ops, dl);
24808 }
24809 
LowerVASTART(SDValue Op,SelectionDAG & DAG) const24810 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
24811   MachineFunction &MF = DAG.getMachineFunction();
24812   auto PtrVT = getPointerTy(MF.getDataLayout());
24813   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
24814 
24815   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
24816   SDLoc DL(Op);
24817 
24818   if (!Subtarget.is64Bit() ||
24819       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
24820     // vastart just stores the address of the VarArgsFrameIndex slot into the
24821     // memory location argument.
24822     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
24823     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
24824                         MachinePointerInfo(SV));
24825   }
24826 
24827   // __va_list_tag:
24828   //   gp_offset         (0 - 6 * 8)
24829   //   fp_offset         (48 - 48 + 8 * 16)
24830   //   overflow_arg_area (point to parameters coming in memory).
24831   //   reg_save_area
24832   SmallVector<SDValue, 8> MemOps;
24833   SDValue FIN = Op.getOperand(1);
24834   // Store gp_offset
24835   SDValue Store = DAG.getStore(
24836       Op.getOperand(0), DL,
24837       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
24838       MachinePointerInfo(SV));
24839   MemOps.push_back(Store);
24840 
24841   // Store fp_offset
24842   FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::getFixed(4), DL);
24843   Store = DAG.getStore(
24844       Op.getOperand(0), DL,
24845       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
24846       MachinePointerInfo(SV, 4));
24847   MemOps.push_back(Store);
24848 
24849   // Store ptr to overflow_arg_area
24850   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
24851   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
24852   Store =
24853       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
24854   MemOps.push_back(Store);
24855 
24856   // Store ptr to reg_save_area.
24857   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
24858       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
24859   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
24860   Store = DAG.getStore(
24861       Op.getOperand(0), DL, RSFIN, FIN,
24862       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
24863   MemOps.push_back(Store);
24864   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
24865 }
24866 
LowerVAARG(SDValue Op,SelectionDAG & DAG) const24867 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
24868   assert(Subtarget.is64Bit() &&
24869          "LowerVAARG only handles 64-bit va_arg!");
24870   assert(Op.getNumOperands() == 4);
24871 
24872   MachineFunction &MF = DAG.getMachineFunction();
24873   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
24874     // The Win64 ABI uses char* instead of a structure.
24875     return DAG.expandVAArg(Op.getNode());
24876 
24877   SDValue Chain = Op.getOperand(0);
24878   SDValue SrcPtr = Op.getOperand(1);
24879   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
24880   unsigned Align = Op.getConstantOperandVal(3);
24881   SDLoc dl(Op);
24882 
24883   EVT ArgVT = Op.getNode()->getValueType(0);
24884   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
24885   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
24886   uint8_t ArgMode;
24887 
24888   // Decide which area this value should be read from.
24889   // TODO: Implement the AMD64 ABI in its entirety. This simple
24890   // selection mechanism works only for the basic types.
24891   assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
24892   if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
24893     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
24894   } else {
24895     assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
24896            "Unhandled argument type in LowerVAARG");
24897     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
24898   }
24899 
24900   if (ArgMode == 2) {
24901     // Make sure using fp_offset makes sense.
24902     assert(!Subtarget.useSoftFloat() &&
24903            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
24904            Subtarget.hasSSE1());
24905   }
24906 
24907   // Insert VAARG node into the DAG
24908   // VAARG returns two values: Variable Argument Address, Chain
24909   SDValue InstOps[] = {Chain, SrcPtr,
24910                        DAG.getTargetConstant(ArgSize, dl, MVT::i32),
24911                        DAG.getTargetConstant(ArgMode, dl, MVT::i8),
24912                        DAG.getTargetConstant(Align, dl, MVT::i32)};
24913   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
24914   SDValue VAARG = DAG.getMemIntrinsicNode(
24915       Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
24916       VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
24917       /*Alignment=*/std::nullopt,
24918       MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
24919   Chain = VAARG.getValue(1);
24920 
24921   // Load the next argument and return it
24922   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
24923 }
24924 
LowerVACOPY(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)24925 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
24926                            SelectionDAG &DAG) {
24927   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
24928   // where a va_list is still an i8*.
24929   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
24930   if (Subtarget.isCallingConvWin64(
24931         DAG.getMachineFunction().getFunction().getCallingConv()))
24932     // Probably a Win64 va_copy.
24933     return DAG.expandVACopy(Op.getNode());
24934 
24935   SDValue Chain = Op.getOperand(0);
24936   SDValue DstPtr = Op.getOperand(1);
24937   SDValue SrcPtr = Op.getOperand(2);
24938   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
24939   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
24940   SDLoc DL(Op);
24941 
24942   return DAG.getMemcpy(
24943       Chain, DL, DstPtr, SrcPtr,
24944       DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
24945       Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
24946       false, MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
24947 }
24948 
24949 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
getTargetVShiftUniformOpcode(unsigned Opc,bool IsVariable)24950 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
24951   switch (Opc) {
24952   case ISD::SHL:
24953   case X86ISD::VSHL:
24954   case X86ISD::VSHLI:
24955     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
24956   case ISD::SRL:
24957   case X86ISD::VSRL:
24958   case X86ISD::VSRLI:
24959     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
24960   case ISD::SRA:
24961   case X86ISD::VSRA:
24962   case X86ISD::VSRAI:
24963     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
24964   }
24965   llvm_unreachable("Unknown target vector shift node");
24966 }
24967 
24968 /// Handle vector element shifts where the shift amount is a constant.
24969 /// Takes immediate version of shift as input.
getTargetVShiftByConstNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,uint64_t ShiftAmt,SelectionDAG & DAG)24970 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
24971                                           SDValue SrcOp, uint64_t ShiftAmt,
24972                                           SelectionDAG &DAG) {
24973   MVT ElementType = VT.getVectorElementType();
24974 
24975   // Bitcast the source vector to the output type, this is mainly necessary for
24976   // vXi8/vXi64 shifts.
24977   if (VT != SrcOp.getSimpleValueType())
24978     SrcOp = DAG.getBitcast(VT, SrcOp);
24979 
24980   // Fold this packed shift into its first operand if ShiftAmt is 0.
24981   if (ShiftAmt == 0)
24982     return SrcOp;
24983 
24984   // Check for ShiftAmt >= element width
24985   if (ShiftAmt >= ElementType.getSizeInBits()) {
24986     if (Opc == X86ISD::VSRAI)
24987       ShiftAmt = ElementType.getSizeInBits() - 1;
24988     else
24989       return DAG.getConstant(0, dl, VT);
24990   }
24991 
24992   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
24993          && "Unknown target vector shift-by-constant node");
24994 
24995   // Fold this packed vector shift into a build vector if SrcOp is a
24996   // vector of Constants or UNDEFs.
24997   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
24998     unsigned ShiftOpc;
24999     switch (Opc) {
25000     default: llvm_unreachable("Unknown opcode!");
25001     case X86ISD::VSHLI:
25002       ShiftOpc = ISD::SHL;
25003       break;
25004     case X86ISD::VSRLI:
25005       ShiftOpc = ISD::SRL;
25006       break;
25007     case X86ISD::VSRAI:
25008       ShiftOpc = ISD::SRA;
25009       break;
25010     }
25011 
25012     SDValue Amt = DAG.getConstant(ShiftAmt, dl, VT);
25013     if (SDValue C = DAG.FoldConstantArithmetic(ShiftOpc, dl, VT, {SrcOp, Amt}))
25014       return C;
25015   }
25016 
25017   return DAG.getNode(Opc, dl, VT, SrcOp,
25018                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
25019 }
25020 
25021 /// Handle vector element shifts by a splat shift amount
getTargetVShiftNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,SDValue ShAmt,int ShAmtIdx,const X86Subtarget & Subtarget,SelectionDAG & DAG)25022 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
25023                                    SDValue SrcOp, SDValue ShAmt, int ShAmtIdx,
25024                                    const X86Subtarget &Subtarget,
25025                                    SelectionDAG &DAG) {
25026   MVT AmtVT = ShAmt.getSimpleValueType();
25027   assert(AmtVT.isVector() && "Vector shift type mismatch");
25028   assert(0 <= ShAmtIdx && ShAmtIdx < (int)AmtVT.getVectorNumElements() &&
25029          "Illegal vector splat index");
25030 
25031   // Move the splat element to the bottom element.
25032   if (ShAmtIdx != 0) {
25033     SmallVector<int> Mask(AmtVT.getVectorNumElements(), -1);
25034     Mask[0] = ShAmtIdx;
25035     ShAmt = DAG.getVectorShuffle(AmtVT, dl, ShAmt, DAG.getUNDEF(AmtVT), Mask);
25036   }
25037 
25038   // Peek through any zext node if we can get back to a 128-bit source.
25039   if (AmtVT.getScalarSizeInBits() == 64 &&
25040       (ShAmt.getOpcode() == ISD::ZERO_EXTEND ||
25041        ShAmt.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
25042       ShAmt.getOperand(0).getValueType().isSimple() &&
25043       ShAmt.getOperand(0).getValueType().is128BitVector()) {
25044     ShAmt = ShAmt.getOperand(0);
25045     AmtVT = ShAmt.getSimpleValueType();
25046   }
25047 
25048   // See if we can mask off the upper elements using the existing source node.
25049   // The shift uses the entire lower 64-bits of the amount vector, so no need to
25050   // do this for vXi64 types.
25051   bool IsMasked = false;
25052   if (AmtVT.getScalarSizeInBits() < 64) {
25053     if (ShAmt.getOpcode() == ISD::BUILD_VECTOR ||
25054         ShAmt.getOpcode() == ISD::SCALAR_TO_VECTOR) {
25055       // If the shift amount has come from a scalar, then zero-extend the scalar
25056       // before moving to the vector.
25057       ShAmt = DAG.getZExtOrTrunc(ShAmt.getOperand(0), dl, MVT::i32);
25058       ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
25059       ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, ShAmt);
25060       AmtVT = MVT::v4i32;
25061       IsMasked = true;
25062     } else if (ShAmt.getOpcode() == ISD::AND) {
25063       // See if the shift amount is already masked (e.g. for rotation modulo),
25064       // then we can zero-extend it by setting all the other mask elements to
25065       // zero.
25066       SmallVector<SDValue> MaskElts(
25067           AmtVT.getVectorNumElements(),
25068           DAG.getConstant(0, dl, AmtVT.getScalarType()));
25069       MaskElts[0] = DAG.getAllOnesConstant(dl, AmtVT.getScalarType());
25070       SDValue Mask = DAG.getBuildVector(AmtVT, dl, MaskElts);
25071       if ((Mask = DAG.FoldConstantArithmetic(ISD::AND, dl, AmtVT,
25072                                              {ShAmt.getOperand(1), Mask}))) {
25073         ShAmt = DAG.getNode(ISD::AND, dl, AmtVT, ShAmt.getOperand(0), Mask);
25074         IsMasked = true;
25075       }
25076     }
25077   }
25078 
25079   // Extract if the shift amount vector is larger than 128-bits.
25080   if (AmtVT.getSizeInBits() > 128) {
25081     ShAmt = extract128BitVector(ShAmt, 0, DAG, dl);
25082     AmtVT = ShAmt.getSimpleValueType();
25083   }
25084 
25085   // Zero-extend bottom element to v2i64 vector type, either by extension or
25086   // shuffle masking.
25087   if (!IsMasked && AmtVT.getScalarSizeInBits() < 64) {
25088     if (AmtVT == MVT::v4i32 && (ShAmt.getOpcode() == X86ISD::VBROADCAST ||
25089                                 ShAmt.getOpcode() == X86ISD::VBROADCAST_LOAD)) {
25090       ShAmt = DAG.getNode(X86ISD::VZEXT_MOVL, SDLoc(ShAmt), MVT::v4i32, ShAmt);
25091     } else if (Subtarget.hasSSE41()) {
25092       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
25093                           MVT::v2i64, ShAmt);
25094     } else {
25095       SDValue ByteShift = DAG.getTargetConstant(
25096           (128 - AmtVT.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
25097       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
25098       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25099                           ByteShift);
25100       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
25101                           ByteShift);
25102     }
25103   }
25104 
25105   // Change opcode to non-immediate version.
25106   Opc = getTargetVShiftUniformOpcode(Opc, true);
25107 
25108   // The return type has to be a 128-bit type with the same element
25109   // type as the input type.
25110   MVT EltVT = VT.getVectorElementType();
25111   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
25112 
25113   ShAmt = DAG.getBitcast(ShVT, ShAmt);
25114   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
25115 }
25116 
25117 /// Return Mask with the necessary casting or extending
25118 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
getMaskNode(SDValue Mask,MVT MaskVT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)25119 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
25120                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
25121                            const SDLoc &dl) {
25122 
25123   if (isAllOnesConstant(Mask))
25124     return DAG.getConstant(1, dl, MaskVT);
25125   if (X86::isZeroNode(Mask))
25126     return DAG.getConstant(0, dl, MaskVT);
25127 
25128   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
25129 
25130   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
25131     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
25132     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
25133     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
25134     SDValue Lo, Hi;
25135     std::tie(Lo, Hi) = DAG.SplitScalar(Mask, dl, MVT::i32, MVT::i32);
25136     Lo = DAG.getBitcast(MVT::v32i1, Lo);
25137     Hi = DAG.getBitcast(MVT::v32i1, Hi);
25138     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
25139   } else {
25140     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
25141                                      Mask.getSimpleValueType().getSizeInBits());
25142     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
25143     // are extracted by EXTRACT_SUBVECTOR.
25144     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
25145                        DAG.getBitcast(BitcastVT, Mask),
25146                        DAG.getIntPtrConstant(0, dl));
25147   }
25148 }
25149 
25150 /// Return (and \p Op, \p Mask) for compare instructions or
25151 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
25152 /// necessary casting or extending for \p Mask when lowering masking intrinsics
getVectorMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)25153 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
25154                                     SDValue PreservedSrc,
25155                                     const X86Subtarget &Subtarget,
25156                                     SelectionDAG &DAG) {
25157   MVT VT = Op.getSimpleValueType();
25158   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
25159   unsigned OpcodeSelect = ISD::VSELECT;
25160   SDLoc dl(Op);
25161 
25162   if (isAllOnesConstant(Mask))
25163     return Op;
25164 
25165   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25166 
25167   if (PreservedSrc.isUndef())
25168     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25169   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
25170 }
25171 
25172 /// Creates an SDNode for a predicated scalar operation.
25173 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
25174 /// The mask is coming as MVT::i8 and it should be transformed
25175 /// to MVT::v1i1 while lowering masking intrinsics.
25176 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
25177 /// "X86select" instead of "vselect". We just can't create the "vselect" node
25178 /// for a scalar instruction.
getScalarMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)25179 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
25180                                     SDValue PreservedSrc,
25181                                     const X86Subtarget &Subtarget,
25182                                     SelectionDAG &DAG) {
25183 
25184   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
25185     if (MaskConst->getZExtValue() & 0x1)
25186       return Op;
25187 
25188   MVT VT = Op.getSimpleValueType();
25189   SDLoc dl(Op);
25190 
25191   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
25192   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
25193                               DAG.getBitcast(MVT::v8i1, Mask),
25194                               DAG.getIntPtrConstant(0, dl));
25195   if (Op.getOpcode() == X86ISD::FSETCCM ||
25196       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
25197       Op.getOpcode() == X86ISD::VFPCLASSS)
25198     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
25199 
25200   if (PreservedSrc.isUndef())
25201     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
25202   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
25203 }
25204 
getSEHRegistrationNodeSize(const Function * Fn)25205 static int getSEHRegistrationNodeSize(const Function *Fn) {
25206   if (!Fn->hasPersonalityFn())
25207     report_fatal_error(
25208         "querying registration node size for function without personality");
25209   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
25210   // WinEHStatePass for the full struct definition.
25211   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
25212   case EHPersonality::MSVC_X86SEH: return 24;
25213   case EHPersonality::MSVC_CXX: return 16;
25214   default: break;
25215   }
25216   report_fatal_error(
25217       "can only recover FP for 32-bit MSVC EH personality functions");
25218 }
25219 
25220 /// When the MSVC runtime transfers control to us, either to an outlined
25221 /// function or when returning to a parent frame after catching an exception, we
25222 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
25223 /// Here's the math:
25224 ///   RegNodeBase = EntryEBP - RegNodeSize
25225 ///   ParentFP = RegNodeBase - ParentFrameOffset
25226 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
25227 /// subtracting the offset (negative on x86) takes us back to the parent FP.
recoverFramePointer(SelectionDAG & DAG,const Function * Fn,SDValue EntryEBP)25228 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
25229                                    SDValue EntryEBP) {
25230   MachineFunction &MF = DAG.getMachineFunction();
25231   SDLoc dl;
25232 
25233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25234   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
25235 
25236   // It's possible that the parent function no longer has a personality function
25237   // if the exceptional code was optimized away, in which case we just return
25238   // the incoming EBP.
25239   if (!Fn->hasPersonalityFn())
25240     return EntryEBP;
25241 
25242   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
25243   // registration, or the .set_setframe offset.
25244   MCSymbol *OffsetSym =
25245       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
25246           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
25247   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
25248   SDValue ParentFrameOffset =
25249       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
25250 
25251   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
25252   // prologue to RBP in the parent function.
25253   const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
25254   if (Subtarget.is64Bit())
25255     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
25256 
25257   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
25258   // RegNodeBase = EntryEBP - RegNodeSize
25259   // ParentFP = RegNodeBase - ParentFrameOffset
25260   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
25261                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
25262   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
25263 }
25264 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const25265 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
25266                                                    SelectionDAG &DAG) const {
25267   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
25268   auto isRoundModeCurDirection = [](SDValue Rnd) {
25269     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
25270       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
25271 
25272     return false;
25273   };
25274   auto isRoundModeSAE = [](SDValue Rnd) {
25275     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25276       unsigned RC = C->getZExtValue();
25277       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25278         // Clear the NO_EXC bit and check remaining bits.
25279         RC ^= X86::STATIC_ROUNDING::NO_EXC;
25280         // As a convenience we allow no other bits or explicitly
25281         // current direction.
25282         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
25283       }
25284     }
25285 
25286     return false;
25287   };
25288   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
25289     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
25290       RC = C->getZExtValue();
25291       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
25292         // Clear the NO_EXC bit and check remaining bits.
25293         RC ^= X86::STATIC_ROUNDING::NO_EXC;
25294         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
25295                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
25296                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
25297                RC == X86::STATIC_ROUNDING::TO_ZERO;
25298       }
25299     }
25300 
25301     return false;
25302   };
25303 
25304   SDLoc dl(Op);
25305   unsigned IntNo = Op.getConstantOperandVal(0);
25306   MVT VT = Op.getSimpleValueType();
25307   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
25308 
25309   // Propagate flags from original node to transformed node(s).
25310   SelectionDAG::FlagInserter FlagsInserter(DAG, Op->getFlags());
25311 
25312   if (IntrData) {
25313     switch(IntrData->Type) {
25314     case INTR_TYPE_1OP: {
25315       // We specify 2 possible opcodes for intrinsics with rounding modes.
25316       // First, we check if the intrinsic may have non-default rounding mode,
25317       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25318       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25319       if (IntrWithRoundingModeOpcode != 0) {
25320         SDValue Rnd = Op.getOperand(2);
25321         unsigned RC = 0;
25322         if (isRoundModeSAEToX(Rnd, RC))
25323           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25324                              Op.getOperand(1),
25325                              DAG.getTargetConstant(RC, dl, MVT::i32));
25326         if (!isRoundModeCurDirection(Rnd))
25327           return SDValue();
25328       }
25329       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25330                          Op.getOperand(1));
25331     }
25332     case INTR_TYPE_1OP_SAE: {
25333       SDValue Sae = Op.getOperand(2);
25334 
25335       unsigned Opc;
25336       if (isRoundModeCurDirection(Sae))
25337         Opc = IntrData->Opc0;
25338       else if (isRoundModeSAE(Sae))
25339         Opc = IntrData->Opc1;
25340       else
25341         return SDValue();
25342 
25343       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
25344     }
25345     case INTR_TYPE_2OP: {
25346       SDValue Src2 = Op.getOperand(2);
25347 
25348       // We specify 2 possible opcodes for intrinsics with rounding modes.
25349       // First, we check if the intrinsic may have non-default rounding mode,
25350       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25351       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25352       if (IntrWithRoundingModeOpcode != 0) {
25353         SDValue Rnd = Op.getOperand(3);
25354         unsigned RC = 0;
25355         if (isRoundModeSAEToX(Rnd, RC))
25356           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25357                              Op.getOperand(1), Src2,
25358                              DAG.getTargetConstant(RC, dl, MVT::i32));
25359         if (!isRoundModeCurDirection(Rnd))
25360           return SDValue();
25361       }
25362 
25363       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25364                          Op.getOperand(1), Src2);
25365     }
25366     case INTR_TYPE_2OP_SAE: {
25367       SDValue Sae = Op.getOperand(3);
25368 
25369       unsigned Opc;
25370       if (isRoundModeCurDirection(Sae))
25371         Opc = IntrData->Opc0;
25372       else if (isRoundModeSAE(Sae))
25373         Opc = IntrData->Opc1;
25374       else
25375         return SDValue();
25376 
25377       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
25378                          Op.getOperand(2));
25379     }
25380     case INTR_TYPE_3OP:
25381     case INTR_TYPE_3OP_IMM8: {
25382       SDValue Src1 = Op.getOperand(1);
25383       SDValue Src2 = Op.getOperand(2);
25384       SDValue Src3 = Op.getOperand(3);
25385 
25386       if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
25387           Src3.getValueType() != MVT::i8) {
25388         Src3 = DAG.getTargetConstant(Src3->getAsZExtVal() & 0xff, dl, MVT::i8);
25389       }
25390 
25391       // We specify 2 possible opcodes for intrinsics with rounding modes.
25392       // First, we check if the intrinsic may have non-default rounding mode,
25393       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25394       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25395       if (IntrWithRoundingModeOpcode != 0) {
25396         SDValue Rnd = Op.getOperand(4);
25397         unsigned RC = 0;
25398         if (isRoundModeSAEToX(Rnd, RC))
25399           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25400                              Src1, Src2, Src3,
25401                              DAG.getTargetConstant(RC, dl, MVT::i32));
25402         if (!isRoundModeCurDirection(Rnd))
25403           return SDValue();
25404       }
25405 
25406       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25407                          {Src1, Src2, Src3});
25408     }
25409     case INTR_TYPE_4OP_IMM8: {
25410       assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant);
25411       SDValue Src4 = Op.getOperand(4);
25412       if (Src4.getValueType() != MVT::i8) {
25413         Src4 = DAG.getTargetConstant(Src4->getAsZExtVal() & 0xff, dl, MVT::i8);
25414       }
25415 
25416       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25417                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
25418                          Src4);
25419     }
25420     case INTR_TYPE_1OP_MASK: {
25421       SDValue Src = Op.getOperand(1);
25422       SDValue PassThru = Op.getOperand(2);
25423       SDValue Mask = Op.getOperand(3);
25424       // We add rounding mode to the Node when
25425       //   - RC Opcode is specified and
25426       //   - RC is not "current direction".
25427       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25428       if (IntrWithRoundingModeOpcode != 0) {
25429         SDValue Rnd = Op.getOperand(4);
25430         unsigned RC = 0;
25431         if (isRoundModeSAEToX(Rnd, RC))
25432           return getVectorMaskingNode(
25433               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25434                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
25435               Mask, PassThru, Subtarget, DAG);
25436         if (!isRoundModeCurDirection(Rnd))
25437           return SDValue();
25438       }
25439       return getVectorMaskingNode(
25440           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
25441           Subtarget, DAG);
25442     }
25443     case INTR_TYPE_1OP_MASK_SAE: {
25444       SDValue Src = Op.getOperand(1);
25445       SDValue PassThru = Op.getOperand(2);
25446       SDValue Mask = Op.getOperand(3);
25447       SDValue Rnd = Op.getOperand(4);
25448 
25449       unsigned Opc;
25450       if (isRoundModeCurDirection(Rnd))
25451         Opc = IntrData->Opc0;
25452       else if (isRoundModeSAE(Rnd))
25453         Opc = IntrData->Opc1;
25454       else
25455         return SDValue();
25456 
25457       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
25458                                   Subtarget, DAG);
25459     }
25460     case INTR_TYPE_SCALAR_MASK: {
25461       SDValue Src1 = Op.getOperand(1);
25462       SDValue Src2 = Op.getOperand(2);
25463       SDValue passThru = Op.getOperand(3);
25464       SDValue Mask = Op.getOperand(4);
25465       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25466       // There are 2 kinds of intrinsics in this group:
25467       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
25468       // (2) With rounding mode and sae - 7 operands.
25469       bool HasRounding = IntrWithRoundingModeOpcode != 0;
25470       if (Op.getNumOperands() == (5U + HasRounding)) {
25471         if (HasRounding) {
25472           SDValue Rnd = Op.getOperand(5);
25473           unsigned RC = 0;
25474           if (isRoundModeSAEToX(Rnd, RC))
25475             return getScalarMaskingNode(
25476                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
25477                             DAG.getTargetConstant(RC, dl, MVT::i32)),
25478                 Mask, passThru, Subtarget, DAG);
25479           if (!isRoundModeCurDirection(Rnd))
25480             return SDValue();
25481         }
25482         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
25483                                                 Src2),
25484                                     Mask, passThru, Subtarget, DAG);
25485       }
25486 
25487       assert(Op.getNumOperands() == (6U + HasRounding) &&
25488              "Unexpected intrinsic form");
25489       SDValue RoundingMode = Op.getOperand(5);
25490       unsigned Opc = IntrData->Opc0;
25491       if (HasRounding) {
25492         SDValue Sae = Op.getOperand(6);
25493         if (isRoundModeSAE(Sae))
25494           Opc = IntrWithRoundingModeOpcode;
25495         else if (!isRoundModeCurDirection(Sae))
25496           return SDValue();
25497       }
25498       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
25499                                               Src2, RoundingMode),
25500                                   Mask, passThru, Subtarget, DAG);
25501     }
25502     case INTR_TYPE_SCALAR_MASK_RND: {
25503       SDValue Src1 = Op.getOperand(1);
25504       SDValue Src2 = Op.getOperand(2);
25505       SDValue passThru = Op.getOperand(3);
25506       SDValue Mask = Op.getOperand(4);
25507       SDValue Rnd = Op.getOperand(5);
25508 
25509       SDValue NewOp;
25510       unsigned RC = 0;
25511       if (isRoundModeCurDirection(Rnd))
25512         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
25513       else if (isRoundModeSAEToX(Rnd, RC))
25514         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
25515                             DAG.getTargetConstant(RC, dl, MVT::i32));
25516       else
25517         return SDValue();
25518 
25519       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
25520     }
25521     case INTR_TYPE_SCALAR_MASK_SAE: {
25522       SDValue Src1 = Op.getOperand(1);
25523       SDValue Src2 = Op.getOperand(2);
25524       SDValue passThru = Op.getOperand(3);
25525       SDValue Mask = Op.getOperand(4);
25526       SDValue Sae = Op.getOperand(5);
25527       unsigned Opc;
25528       if (isRoundModeCurDirection(Sae))
25529         Opc = IntrData->Opc0;
25530       else if (isRoundModeSAE(Sae))
25531         Opc = IntrData->Opc1;
25532       else
25533         return SDValue();
25534 
25535       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
25536                                   Mask, passThru, Subtarget, DAG);
25537     }
25538     case INTR_TYPE_2OP_MASK: {
25539       SDValue Src1 = Op.getOperand(1);
25540       SDValue Src2 = Op.getOperand(2);
25541       SDValue PassThru = Op.getOperand(3);
25542       SDValue Mask = Op.getOperand(4);
25543       SDValue NewOp;
25544       if (IntrData->Opc1 != 0) {
25545         SDValue Rnd = Op.getOperand(5);
25546         unsigned RC = 0;
25547         if (isRoundModeSAEToX(Rnd, RC))
25548           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
25549                               DAG.getTargetConstant(RC, dl, MVT::i32));
25550         else if (!isRoundModeCurDirection(Rnd))
25551           return SDValue();
25552       }
25553       if (!NewOp)
25554         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
25555       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
25556     }
25557     case INTR_TYPE_2OP_MASK_SAE: {
25558       SDValue Src1 = Op.getOperand(1);
25559       SDValue Src2 = Op.getOperand(2);
25560       SDValue PassThru = Op.getOperand(3);
25561       SDValue Mask = Op.getOperand(4);
25562 
25563       unsigned Opc = IntrData->Opc0;
25564       if (IntrData->Opc1 != 0) {
25565         SDValue Sae = Op.getOperand(5);
25566         if (isRoundModeSAE(Sae))
25567           Opc = IntrData->Opc1;
25568         else if (!isRoundModeCurDirection(Sae))
25569           return SDValue();
25570       }
25571 
25572       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
25573                                   Mask, PassThru, Subtarget, DAG);
25574     }
25575     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
25576       SDValue Src1 = Op.getOperand(1);
25577       SDValue Src2 = Op.getOperand(2);
25578       SDValue Src3 = Op.getOperand(3);
25579       SDValue PassThru = Op.getOperand(4);
25580       SDValue Mask = Op.getOperand(5);
25581       SDValue Sae = Op.getOperand(6);
25582       unsigned Opc;
25583       if (isRoundModeCurDirection(Sae))
25584         Opc = IntrData->Opc0;
25585       else if (isRoundModeSAE(Sae))
25586         Opc = IntrData->Opc1;
25587       else
25588         return SDValue();
25589 
25590       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
25591                                   Mask, PassThru, Subtarget, DAG);
25592     }
25593     case INTR_TYPE_3OP_MASK_SAE: {
25594       SDValue Src1 = Op.getOperand(1);
25595       SDValue Src2 = Op.getOperand(2);
25596       SDValue Src3 = Op.getOperand(3);
25597       SDValue PassThru = Op.getOperand(4);
25598       SDValue Mask = Op.getOperand(5);
25599 
25600       unsigned Opc = IntrData->Opc0;
25601       if (IntrData->Opc1 != 0) {
25602         SDValue Sae = Op.getOperand(6);
25603         if (isRoundModeSAE(Sae))
25604           Opc = IntrData->Opc1;
25605         else if (!isRoundModeCurDirection(Sae))
25606           return SDValue();
25607       }
25608       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
25609                                   Mask, PassThru, Subtarget, DAG);
25610     }
25611     case BLENDV: {
25612       SDValue Src1 = Op.getOperand(1);
25613       SDValue Src2 = Op.getOperand(2);
25614       SDValue Src3 = Op.getOperand(3);
25615 
25616       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
25617       Src3 = DAG.getBitcast(MaskVT, Src3);
25618 
25619       // Reverse the operands to match VSELECT order.
25620       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
25621     }
25622     case VPERM_2OP : {
25623       SDValue Src1 = Op.getOperand(1);
25624       SDValue Src2 = Op.getOperand(2);
25625 
25626       // Swap Src1 and Src2 in the node creation
25627       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
25628     }
25629     case CFMA_OP_MASKZ:
25630     case CFMA_OP_MASK: {
25631       SDValue Src1 = Op.getOperand(1);
25632       SDValue Src2 = Op.getOperand(2);
25633       SDValue Src3 = Op.getOperand(3);
25634       SDValue Mask = Op.getOperand(4);
25635       MVT VT = Op.getSimpleValueType();
25636 
25637       SDValue PassThru = Src3;
25638       if (IntrData->Type == CFMA_OP_MASKZ)
25639         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
25640 
25641       // We add rounding mode to the Node when
25642       //   - RC Opcode is specified and
25643       //   - RC is not "current direction".
25644       SDValue NewOp;
25645       if (IntrData->Opc1 != 0) {
25646         SDValue Rnd = Op.getOperand(5);
25647         unsigned RC = 0;
25648         if (isRoundModeSAEToX(Rnd, RC))
25649           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2, Src3,
25650                               DAG.getTargetConstant(RC, dl, MVT::i32));
25651         else if (!isRoundModeCurDirection(Rnd))
25652           return SDValue();
25653       }
25654       if (!NewOp)
25655         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2, Src3);
25656       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
25657     }
25658     case IFMA_OP:
25659       // NOTE: We need to swizzle the operands to pass the multiply operands
25660       // first.
25661       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25662                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
25663     case FPCLASSS: {
25664       SDValue Src1 = Op.getOperand(1);
25665       SDValue Imm = Op.getOperand(2);
25666       SDValue Mask = Op.getOperand(3);
25667       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
25668       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
25669                                                  Subtarget, DAG);
25670       // Need to fill with zeros to ensure the bitcast will produce zeroes
25671       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25672       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
25673                                 DAG.getConstant(0, dl, MVT::v8i1),
25674                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
25675       return DAG.getBitcast(MVT::i8, Ins);
25676     }
25677 
25678     case CMP_MASK_CC: {
25679       MVT MaskVT = Op.getSimpleValueType();
25680       SDValue CC = Op.getOperand(3);
25681       SDValue Mask = Op.getOperand(4);
25682       // We specify 2 possible opcodes for intrinsics with rounding modes.
25683       // First, we check if the intrinsic may have non-default rounding mode,
25684       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25685       if (IntrData->Opc1 != 0) {
25686         SDValue Sae = Op.getOperand(5);
25687         if (isRoundModeSAE(Sae))
25688           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
25689                              Op.getOperand(2), CC, Mask, Sae);
25690         if (!isRoundModeCurDirection(Sae))
25691           return SDValue();
25692       }
25693       //default rounding mode
25694       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
25695                          {Op.getOperand(1), Op.getOperand(2), CC, Mask});
25696     }
25697     case CMP_MASK_SCALAR_CC: {
25698       SDValue Src1 = Op.getOperand(1);
25699       SDValue Src2 = Op.getOperand(2);
25700       SDValue CC = Op.getOperand(3);
25701       SDValue Mask = Op.getOperand(4);
25702 
25703       SDValue Cmp;
25704       if (IntrData->Opc1 != 0) {
25705         SDValue Sae = Op.getOperand(5);
25706         if (isRoundModeSAE(Sae))
25707           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
25708         else if (!isRoundModeCurDirection(Sae))
25709           return SDValue();
25710       }
25711       //default rounding mode
25712       if (!Cmp.getNode())
25713         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
25714 
25715       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
25716                                              Subtarget, DAG);
25717       // Need to fill with zeros to ensure the bitcast will produce zeroes
25718       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25719       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
25720                                 DAG.getConstant(0, dl, MVT::v8i1),
25721                                 CmpMask, DAG.getIntPtrConstant(0, dl));
25722       return DAG.getBitcast(MVT::i8, Ins);
25723     }
25724     case COMI: { // Comparison intrinsics
25725       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
25726       SDValue LHS = Op.getOperand(1);
25727       SDValue RHS = Op.getOperand(2);
25728       // Some conditions require the operands to be swapped.
25729       if (CC == ISD::SETLT || CC == ISD::SETLE)
25730         std::swap(LHS, RHS);
25731 
25732       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
25733       SDValue SetCC;
25734       switch (CC) {
25735       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
25736         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
25737         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
25738         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
25739         break;
25740       }
25741       case ISD::SETNE: { // (ZF = 1 or PF = 1)
25742         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
25743         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
25744         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
25745         break;
25746       }
25747       case ISD::SETGT: // (CF = 0 and ZF = 0)
25748       case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
25749         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
25750         break;
25751       }
25752       case ISD::SETGE: // CF = 0
25753       case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
25754         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
25755         break;
25756       default:
25757         llvm_unreachable("Unexpected illegal condition!");
25758       }
25759       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25760     }
25761     case COMI_RM: { // Comparison intrinsics with Sae
25762       SDValue LHS = Op.getOperand(1);
25763       SDValue RHS = Op.getOperand(2);
25764       unsigned CondVal = Op.getConstantOperandVal(3);
25765       SDValue Sae = Op.getOperand(4);
25766 
25767       SDValue FCmp;
25768       if (isRoundModeCurDirection(Sae))
25769         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
25770                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
25771       else if (isRoundModeSAE(Sae))
25772         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
25773                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
25774       else
25775         return SDValue();
25776       // Need to fill with zeros to ensure the bitcast will produce zeroes
25777       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25778       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
25779                                 DAG.getConstant(0, dl, MVT::v16i1),
25780                                 FCmp, DAG.getIntPtrConstant(0, dl));
25781       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
25782                          DAG.getBitcast(MVT::i16, Ins));
25783     }
25784     case VSHIFT: {
25785       SDValue SrcOp = Op.getOperand(1);
25786       SDValue ShAmt = Op.getOperand(2);
25787       assert(ShAmt.getValueType() == MVT::i32 &&
25788              "Unexpected VSHIFT amount type");
25789 
25790       // Catch shift-by-constant.
25791       if (auto *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
25792         return getTargetVShiftByConstNode(IntrData->Opc0, dl,
25793                                           Op.getSimpleValueType(), SrcOp,
25794                                           CShAmt->getZExtValue(), DAG);
25795 
25796       ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, ShAmt);
25797       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
25798                                  SrcOp, ShAmt, 0, Subtarget, DAG);
25799     }
25800     case COMPRESS_EXPAND_IN_REG: {
25801       SDValue Mask = Op.getOperand(3);
25802       SDValue DataToCompress = Op.getOperand(1);
25803       SDValue PassThru = Op.getOperand(2);
25804       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
25805         return Op.getOperand(1);
25806 
25807       // Avoid false dependency.
25808       if (PassThru.isUndef())
25809         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
25810 
25811       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
25812                          Mask);
25813     }
25814     case FIXUPIMM:
25815     case FIXUPIMM_MASKZ: {
25816       SDValue Src1 = Op.getOperand(1);
25817       SDValue Src2 = Op.getOperand(2);
25818       SDValue Src3 = Op.getOperand(3);
25819       SDValue Imm = Op.getOperand(4);
25820       SDValue Mask = Op.getOperand(5);
25821       SDValue Passthru = (IntrData->Type == FIXUPIMM)
25822                              ? Src1
25823                              : getZeroVector(VT, Subtarget, DAG, dl);
25824 
25825       unsigned Opc = IntrData->Opc0;
25826       if (IntrData->Opc1 != 0) {
25827         SDValue Sae = Op.getOperand(6);
25828         if (isRoundModeSAE(Sae))
25829           Opc = IntrData->Opc1;
25830         else if (!isRoundModeCurDirection(Sae))
25831           return SDValue();
25832       }
25833 
25834       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
25835 
25836       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
25837         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
25838 
25839       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
25840     }
25841     case ROUNDP: {
25842       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
25843       // Clear the upper bits of the rounding immediate so that the legacy
25844       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
25845       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
25846       SDValue RoundingMode =
25847           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
25848       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25849                          Op.getOperand(1), RoundingMode);
25850     }
25851     case ROUNDS: {
25852       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
25853       // Clear the upper bits of the rounding immediate so that the legacy
25854       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
25855       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
25856       SDValue RoundingMode =
25857           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
25858       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25859                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
25860     }
25861     case BEXTRI: {
25862       assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode");
25863 
25864       uint64_t Imm = Op.getConstantOperandVal(2);
25865       SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
25866                                               Op.getValueType());
25867       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25868                          Op.getOperand(1), Control);
25869     }
25870     // ADC/SBB
25871     case ADX: {
25872       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
25873       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
25874 
25875       SDValue Res;
25876       // If the carry in is zero, then we should just use ADD/SUB instead of
25877       // ADC/SBB.
25878       if (isNullConstant(Op.getOperand(1))) {
25879         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
25880                           Op.getOperand(3));
25881       } else {
25882         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
25883                                     DAG.getConstant(-1, dl, MVT::i8));
25884         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
25885                           Op.getOperand(3), GenCF.getValue(1));
25886       }
25887       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
25888       SDValue Results[] = { SetCC, Res };
25889       return DAG.getMergeValues(Results, dl);
25890     }
25891     case CVTPD2PS_MASK:
25892     case CVTPD2DQ_MASK:
25893     case CVTQQ2PS_MASK:
25894     case TRUNCATE_TO_REG: {
25895       SDValue Src = Op.getOperand(1);
25896       SDValue PassThru = Op.getOperand(2);
25897       SDValue Mask = Op.getOperand(3);
25898 
25899       if (isAllOnesConstant(Mask))
25900         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
25901 
25902       MVT SrcVT = Src.getSimpleValueType();
25903       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
25904       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25905       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
25906                          {Src, PassThru, Mask});
25907     }
25908     case CVTPS2PH_MASK: {
25909       SDValue Src = Op.getOperand(1);
25910       SDValue Rnd = Op.getOperand(2);
25911       SDValue PassThru = Op.getOperand(3);
25912       SDValue Mask = Op.getOperand(4);
25913 
25914       unsigned RC = 0;
25915       unsigned Opc = IntrData->Opc0;
25916       bool SAE = Src.getValueType().is512BitVector() &&
25917                  (isRoundModeSAEToX(Rnd, RC) || isRoundModeSAE(Rnd));
25918       if (SAE) {
25919         Opc = X86ISD::CVTPS2PH_SAE;
25920         Rnd = DAG.getTargetConstant(RC, dl, MVT::i32);
25921       }
25922 
25923       if (isAllOnesConstant(Mask))
25924         return DAG.getNode(Opc, dl, Op.getValueType(), Src, Rnd);
25925 
25926       if (SAE)
25927         Opc = X86ISD::MCVTPS2PH_SAE;
25928       else
25929         Opc = IntrData->Opc1;
25930       MVT SrcVT = Src.getSimpleValueType();
25931       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
25932       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25933       return DAG.getNode(Opc, dl, Op.getValueType(), Src, Rnd, PassThru, Mask);
25934     }
25935     case CVTNEPS2BF16_MASK: {
25936       SDValue Src = Op.getOperand(1);
25937       SDValue PassThru = Op.getOperand(2);
25938       SDValue Mask = Op.getOperand(3);
25939 
25940       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
25941         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
25942 
25943       // Break false dependency.
25944       if (PassThru.isUndef())
25945         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
25946 
25947       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
25948                          Mask);
25949     }
25950     default:
25951       break;
25952     }
25953   }
25954 
25955   switch (IntNo) {
25956   default: return SDValue();    // Don't custom lower most intrinsics.
25957 
25958   // ptest and testp intrinsics. The intrinsic these come from are designed to
25959   // return an integer value, not just an instruction so lower it to the ptest
25960   // or testp pattern and a setcc for the result.
25961   case Intrinsic::x86_avx512_ktestc_b:
25962   case Intrinsic::x86_avx512_ktestc_w:
25963   case Intrinsic::x86_avx512_ktestc_d:
25964   case Intrinsic::x86_avx512_ktestc_q:
25965   case Intrinsic::x86_avx512_ktestz_b:
25966   case Intrinsic::x86_avx512_ktestz_w:
25967   case Intrinsic::x86_avx512_ktestz_d:
25968   case Intrinsic::x86_avx512_ktestz_q:
25969   case Intrinsic::x86_sse41_ptestz:
25970   case Intrinsic::x86_sse41_ptestc:
25971   case Intrinsic::x86_sse41_ptestnzc:
25972   case Intrinsic::x86_avx_ptestz_256:
25973   case Intrinsic::x86_avx_ptestc_256:
25974   case Intrinsic::x86_avx_ptestnzc_256:
25975   case Intrinsic::x86_avx_vtestz_ps:
25976   case Intrinsic::x86_avx_vtestc_ps:
25977   case Intrinsic::x86_avx_vtestnzc_ps:
25978   case Intrinsic::x86_avx_vtestz_pd:
25979   case Intrinsic::x86_avx_vtestc_pd:
25980   case Intrinsic::x86_avx_vtestnzc_pd:
25981   case Intrinsic::x86_avx_vtestz_ps_256:
25982   case Intrinsic::x86_avx_vtestc_ps_256:
25983   case Intrinsic::x86_avx_vtestnzc_ps_256:
25984   case Intrinsic::x86_avx_vtestz_pd_256:
25985   case Intrinsic::x86_avx_vtestc_pd_256:
25986   case Intrinsic::x86_avx_vtestnzc_pd_256: {
25987     unsigned TestOpc = X86ISD::PTEST;
25988     X86::CondCode X86CC;
25989     switch (IntNo) {
25990     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
25991     case Intrinsic::x86_avx512_ktestc_b:
25992     case Intrinsic::x86_avx512_ktestc_w:
25993     case Intrinsic::x86_avx512_ktestc_d:
25994     case Intrinsic::x86_avx512_ktestc_q:
25995       // CF = 1
25996       TestOpc = X86ISD::KTEST;
25997       X86CC = X86::COND_B;
25998       break;
25999     case Intrinsic::x86_avx512_ktestz_b:
26000     case Intrinsic::x86_avx512_ktestz_w:
26001     case Intrinsic::x86_avx512_ktestz_d:
26002     case Intrinsic::x86_avx512_ktestz_q:
26003       TestOpc = X86ISD::KTEST;
26004       X86CC = X86::COND_E;
26005       break;
26006     case Intrinsic::x86_avx_vtestz_ps:
26007     case Intrinsic::x86_avx_vtestz_pd:
26008     case Intrinsic::x86_avx_vtestz_ps_256:
26009     case Intrinsic::x86_avx_vtestz_pd_256:
26010       TestOpc = X86ISD::TESTP;
26011       [[fallthrough]];
26012     case Intrinsic::x86_sse41_ptestz:
26013     case Intrinsic::x86_avx_ptestz_256:
26014       // ZF = 1
26015       X86CC = X86::COND_E;
26016       break;
26017     case Intrinsic::x86_avx_vtestc_ps:
26018     case Intrinsic::x86_avx_vtestc_pd:
26019     case Intrinsic::x86_avx_vtestc_ps_256:
26020     case Intrinsic::x86_avx_vtestc_pd_256:
26021       TestOpc = X86ISD::TESTP;
26022       [[fallthrough]];
26023     case Intrinsic::x86_sse41_ptestc:
26024     case Intrinsic::x86_avx_ptestc_256:
26025       // CF = 1
26026       X86CC = X86::COND_B;
26027       break;
26028     case Intrinsic::x86_avx_vtestnzc_ps:
26029     case Intrinsic::x86_avx_vtestnzc_pd:
26030     case Intrinsic::x86_avx_vtestnzc_ps_256:
26031     case Intrinsic::x86_avx_vtestnzc_pd_256:
26032       TestOpc = X86ISD::TESTP;
26033       [[fallthrough]];
26034     case Intrinsic::x86_sse41_ptestnzc:
26035     case Intrinsic::x86_avx_ptestnzc_256:
26036       // ZF and CF = 0
26037       X86CC = X86::COND_A;
26038       break;
26039     }
26040 
26041     SDValue LHS = Op.getOperand(1);
26042     SDValue RHS = Op.getOperand(2);
26043     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
26044     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
26045     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26046   }
26047 
26048   case Intrinsic::x86_sse42_pcmpistria128:
26049   case Intrinsic::x86_sse42_pcmpestria128:
26050   case Intrinsic::x86_sse42_pcmpistric128:
26051   case Intrinsic::x86_sse42_pcmpestric128:
26052   case Intrinsic::x86_sse42_pcmpistrio128:
26053   case Intrinsic::x86_sse42_pcmpestrio128:
26054   case Intrinsic::x86_sse42_pcmpistris128:
26055   case Intrinsic::x86_sse42_pcmpestris128:
26056   case Intrinsic::x86_sse42_pcmpistriz128:
26057   case Intrinsic::x86_sse42_pcmpestriz128: {
26058     unsigned Opcode;
26059     X86::CondCode X86CC;
26060     switch (IntNo) {
26061     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
26062     case Intrinsic::x86_sse42_pcmpistria128:
26063       Opcode = X86ISD::PCMPISTR;
26064       X86CC = X86::COND_A;
26065       break;
26066     case Intrinsic::x86_sse42_pcmpestria128:
26067       Opcode = X86ISD::PCMPESTR;
26068       X86CC = X86::COND_A;
26069       break;
26070     case Intrinsic::x86_sse42_pcmpistric128:
26071       Opcode = X86ISD::PCMPISTR;
26072       X86CC = X86::COND_B;
26073       break;
26074     case Intrinsic::x86_sse42_pcmpestric128:
26075       Opcode = X86ISD::PCMPESTR;
26076       X86CC = X86::COND_B;
26077       break;
26078     case Intrinsic::x86_sse42_pcmpistrio128:
26079       Opcode = X86ISD::PCMPISTR;
26080       X86CC = X86::COND_O;
26081       break;
26082     case Intrinsic::x86_sse42_pcmpestrio128:
26083       Opcode = X86ISD::PCMPESTR;
26084       X86CC = X86::COND_O;
26085       break;
26086     case Intrinsic::x86_sse42_pcmpistris128:
26087       Opcode = X86ISD::PCMPISTR;
26088       X86CC = X86::COND_S;
26089       break;
26090     case Intrinsic::x86_sse42_pcmpestris128:
26091       Opcode = X86ISD::PCMPESTR;
26092       X86CC = X86::COND_S;
26093       break;
26094     case Intrinsic::x86_sse42_pcmpistriz128:
26095       Opcode = X86ISD::PCMPISTR;
26096       X86CC = X86::COND_E;
26097       break;
26098     case Intrinsic::x86_sse42_pcmpestriz128:
26099       Opcode = X86ISD::PCMPESTR;
26100       X86CC = X86::COND_E;
26101       break;
26102     }
26103     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26104     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26105     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
26106     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
26107     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
26108   }
26109 
26110   case Intrinsic::x86_sse42_pcmpistri128:
26111   case Intrinsic::x86_sse42_pcmpestri128: {
26112     unsigned Opcode;
26113     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
26114       Opcode = X86ISD::PCMPISTR;
26115     else
26116       Opcode = X86ISD::PCMPESTR;
26117 
26118     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26119     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26120     return DAG.getNode(Opcode, dl, VTs, NewOps);
26121   }
26122 
26123   case Intrinsic::x86_sse42_pcmpistrm128:
26124   case Intrinsic::x86_sse42_pcmpestrm128: {
26125     unsigned Opcode;
26126     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
26127       Opcode = X86ISD::PCMPISTR;
26128     else
26129       Opcode = X86ISD::PCMPESTR;
26130 
26131     SmallVector<SDValue, 5> NewOps(llvm::drop_begin(Op->ops()));
26132     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
26133     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
26134   }
26135 
26136   case Intrinsic::eh_sjlj_lsda: {
26137     MachineFunction &MF = DAG.getMachineFunction();
26138     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26139     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
26140     auto &Context = MF.getMMI().getContext();
26141     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
26142                                             Twine(MF.getFunctionNumber()));
26143     return DAG.getNode(getGlobalWrapperKind(nullptr, /*OpFlags=*/0), dl, VT,
26144                        DAG.getMCSymbol(S, PtrVT));
26145   }
26146 
26147   case Intrinsic::x86_seh_lsda: {
26148     // Compute the symbol for the LSDA. We know it'll get emitted later.
26149     MachineFunction &MF = DAG.getMachineFunction();
26150     SDValue Op1 = Op.getOperand(1);
26151     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
26152     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
26153         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
26154 
26155     // Generate a simple absolute symbol reference. This intrinsic is only
26156     // supported on 32-bit Windows, which isn't PIC.
26157     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
26158     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
26159   }
26160 
26161   case Intrinsic::eh_recoverfp: {
26162     SDValue FnOp = Op.getOperand(1);
26163     SDValue IncomingFPOp = Op.getOperand(2);
26164     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
26165     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
26166     if (!Fn)
26167       report_fatal_error(
26168           "llvm.eh.recoverfp must take a function as the first argument");
26169     return recoverFramePointer(DAG, Fn, IncomingFPOp);
26170   }
26171 
26172   case Intrinsic::localaddress: {
26173     // Returns one of the stack, base, or frame pointer registers, depending on
26174     // which is used to reference local variables.
26175     MachineFunction &MF = DAG.getMachineFunction();
26176     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26177     unsigned Reg;
26178     if (RegInfo->hasBasePointer(MF))
26179       Reg = RegInfo->getBaseRegister();
26180     else { // Handles the SP or FP case.
26181       bool CantUseFP = RegInfo->hasStackRealignment(MF);
26182       if (CantUseFP)
26183         Reg = RegInfo->getPtrSizedStackRegister(MF);
26184       else
26185         Reg = RegInfo->getPtrSizedFrameRegister(MF);
26186     }
26187     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
26188   }
26189   case Intrinsic::x86_avx512_vp2intersect_q_512:
26190   case Intrinsic::x86_avx512_vp2intersect_q_256:
26191   case Intrinsic::x86_avx512_vp2intersect_q_128:
26192   case Intrinsic::x86_avx512_vp2intersect_d_512:
26193   case Intrinsic::x86_avx512_vp2intersect_d_256:
26194   case Intrinsic::x86_avx512_vp2intersect_d_128: {
26195     MVT MaskVT = Op.getSimpleValueType();
26196 
26197     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
26198     SDLoc DL(Op);
26199 
26200     SDValue Operation =
26201         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
26202                     Op->getOperand(1), Op->getOperand(2));
26203 
26204     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
26205                                                  MaskVT, Operation);
26206     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
26207                                                  MaskVT, Operation);
26208     return DAG.getMergeValues({Result0, Result1}, DL);
26209   }
26210   case Intrinsic::x86_mmx_pslli_w:
26211   case Intrinsic::x86_mmx_pslli_d:
26212   case Intrinsic::x86_mmx_pslli_q:
26213   case Intrinsic::x86_mmx_psrli_w:
26214   case Intrinsic::x86_mmx_psrli_d:
26215   case Intrinsic::x86_mmx_psrli_q:
26216   case Intrinsic::x86_mmx_psrai_w:
26217   case Intrinsic::x86_mmx_psrai_d: {
26218     SDLoc DL(Op);
26219     SDValue ShAmt = Op.getOperand(2);
26220     // If the argument is a constant, convert it to a target constant.
26221     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
26222       // Clamp out of bounds shift amounts since they will otherwise be masked
26223       // to 8-bits which may make it no longer out of bounds.
26224       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
26225       if (ShiftAmount == 0)
26226         return Op.getOperand(1);
26227 
26228       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26229                          Op.getOperand(0), Op.getOperand(1),
26230                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
26231     }
26232 
26233     unsigned NewIntrinsic;
26234     switch (IntNo) {
26235     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
26236     case Intrinsic::x86_mmx_pslli_w:
26237       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
26238       break;
26239     case Intrinsic::x86_mmx_pslli_d:
26240       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
26241       break;
26242     case Intrinsic::x86_mmx_pslli_q:
26243       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
26244       break;
26245     case Intrinsic::x86_mmx_psrli_w:
26246       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
26247       break;
26248     case Intrinsic::x86_mmx_psrli_d:
26249       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
26250       break;
26251     case Intrinsic::x86_mmx_psrli_q:
26252       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
26253       break;
26254     case Intrinsic::x86_mmx_psrai_w:
26255       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
26256       break;
26257     case Intrinsic::x86_mmx_psrai_d:
26258       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
26259       break;
26260     }
26261 
26262     // The vector shift intrinsics with scalars uses 32b shift amounts but
26263     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
26264     // MMX register.
26265     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
26266     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
26267                        DAG.getTargetConstant(NewIntrinsic, DL,
26268                                              getPointerTy(DAG.getDataLayout())),
26269                        Op.getOperand(1), ShAmt);
26270   }
26271   case Intrinsic::thread_pointer: {
26272     if (Subtarget.isTargetELF()) {
26273       SDLoc dl(Op);
26274       EVT PtrVT = getPointerTy(DAG.getDataLayout());
26275       // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
26276       Value *Ptr = Constant::getNullValue(PointerType::get(
26277           *DAG.getContext(), Subtarget.is64Bit() ? X86AS::FS : X86AS::GS));
26278       return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
26279                          DAG.getIntPtrConstant(0, dl), MachinePointerInfo(Ptr));
26280     }
26281     report_fatal_error(
26282         "Target OS doesn't support __builtin_thread_pointer() yet.");
26283   }
26284   }
26285 }
26286 
getAVX2GatherNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)26287 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26288                                  SDValue Src, SDValue Mask, SDValue Base,
26289                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
26290                                  const X86Subtarget &Subtarget) {
26291   SDLoc dl(Op);
26292   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26293   // Scale must be constant.
26294   if (!C)
26295     return SDValue();
26296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26297   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26298                                         TLI.getPointerTy(DAG.getDataLayout()));
26299   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
26300   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26301   // If source is undef or we know it won't be used, use a zero vector
26302   // to break register dependency.
26303   // TODO: use undef instead and let BreakFalseDeps deal with it?
26304   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26305     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26306 
26307   // Cast mask to an integer type.
26308   Mask = DAG.getBitcast(MaskVT, Mask);
26309 
26310   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26311 
26312   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26313   SDValue Res =
26314       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26315                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26316   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26317 }
26318 
getGatherNode(SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)26319 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
26320                              SDValue Src, SDValue Mask, SDValue Base,
26321                              SDValue Index, SDValue ScaleOp, SDValue Chain,
26322                              const X86Subtarget &Subtarget) {
26323   MVT VT = Op.getSimpleValueType();
26324   SDLoc dl(Op);
26325   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26326   // Scale must be constant.
26327   if (!C)
26328     return SDValue();
26329   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26330   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26331                                         TLI.getPointerTy(DAG.getDataLayout()));
26332   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26333                               VT.getVectorNumElements());
26334   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26335 
26336   // We support two versions of the gather intrinsics. One with scalar mask and
26337   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26338   if (Mask.getValueType() != MaskVT)
26339     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26340 
26341   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
26342   // If source is undef or we know it won't be used, use a zero vector
26343   // to break register dependency.
26344   // TODO: use undef instead and let BreakFalseDeps deal with it?
26345   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
26346     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
26347 
26348   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26349 
26350   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
26351   SDValue Res =
26352       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
26353                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26354   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
26355 }
26356 
getScatterNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)26357 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26358                                SDValue Src, SDValue Mask, SDValue Base,
26359                                SDValue Index, SDValue ScaleOp, SDValue Chain,
26360                                const X86Subtarget &Subtarget) {
26361   SDLoc dl(Op);
26362   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26363   // Scale must be constant.
26364   if (!C)
26365     return SDValue();
26366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26367   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26368                                         TLI.getPointerTy(DAG.getDataLayout()));
26369   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
26370                               Src.getSimpleValueType().getVectorNumElements());
26371   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
26372 
26373   // We support two versions of the scatter intrinsics. One with scalar mask and
26374   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26375   if (Mask.getValueType() != MaskVT)
26376     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26377 
26378   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26379 
26380   SDVTList VTs = DAG.getVTList(MVT::Other);
26381   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
26382   SDValue Res =
26383       DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
26384                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26385   return Res;
26386 }
26387 
getPrefetchNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)26388 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26389                                SDValue Mask, SDValue Base, SDValue Index,
26390                                SDValue ScaleOp, SDValue Chain,
26391                                const X86Subtarget &Subtarget) {
26392   SDLoc dl(Op);
26393   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26394   // Scale must be constant.
26395   if (!C)
26396     return SDValue();
26397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26398   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26399                                         TLI.getPointerTy(DAG.getDataLayout()));
26400   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
26401   SDValue Segment = DAG.getRegister(0, MVT::i32);
26402   MVT MaskVT =
26403     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
26404   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26405   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
26406   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
26407   return SDValue(Res, 0);
26408 }
26409 
26410 /// Handles the lowering of builtin intrinsics with chain that return their
26411 /// value into registers EDX:EAX.
26412 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
26413 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
26414 /// TargetOpcode.
26415 /// Returns a Glue value which can be used to add extra copy-from-reg if the
26416 /// expanded intrinsics implicitly defines extra registers (i.e. not just
26417 /// EDX:EAX).
expandIntrinsicWChainHelper(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,unsigned TargetOpcode,unsigned SrcReg,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)26418 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
26419                                         SelectionDAG &DAG,
26420                                         unsigned TargetOpcode,
26421                                         unsigned SrcReg,
26422                                         const X86Subtarget &Subtarget,
26423                                         SmallVectorImpl<SDValue> &Results) {
26424   SDValue Chain = N->getOperand(0);
26425   SDValue Glue;
26426 
26427   if (SrcReg) {
26428     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
26429     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
26430     Glue = Chain.getValue(1);
26431   }
26432 
26433   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
26434   SDValue N1Ops[] = {Chain, Glue};
26435   SDNode *N1 = DAG.getMachineNode(
26436       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
26437   Chain = SDValue(N1, 0);
26438 
26439   // Reads the content of XCR and returns it in registers EDX:EAX.
26440   SDValue LO, HI;
26441   if (Subtarget.is64Bit()) {
26442     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
26443     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
26444                             LO.getValue(2));
26445   } else {
26446     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
26447     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
26448                             LO.getValue(2));
26449   }
26450   Chain = HI.getValue(1);
26451   Glue = HI.getValue(2);
26452 
26453   if (Subtarget.is64Bit()) {
26454     // Merge the two 32-bit values into a 64-bit one.
26455     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
26456                               DAG.getConstant(32, DL, MVT::i8));
26457     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
26458     Results.push_back(Chain);
26459     return Glue;
26460   }
26461 
26462   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
26463   SDValue Ops[] = { LO, HI };
26464   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
26465   Results.push_back(Pair);
26466   Results.push_back(Chain);
26467   return Glue;
26468 }
26469 
26470 /// Handles the lowering of builtin intrinsics that read the time stamp counter
26471 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
26472 /// READCYCLECOUNTER nodes.
getReadTimeStampCounter(SDNode * N,const SDLoc & DL,unsigned Opcode,SelectionDAG & DAG,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)26473 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
26474                                     SelectionDAG &DAG,
26475                                     const X86Subtarget &Subtarget,
26476                                     SmallVectorImpl<SDValue> &Results) {
26477   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
26478   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
26479   // and the EAX register is loaded with the low-order 32 bits.
26480   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
26481                                              /* NoRegister */0, Subtarget,
26482                                              Results);
26483   if (Opcode != X86::RDTSCP)
26484     return;
26485 
26486   SDValue Chain = Results[1];
26487   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
26488   // the ECX register. Add 'ecx' explicitly to the chain.
26489   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
26490   Results[1] = ecx;
26491   Results.push_back(ecx.getValue(1));
26492 }
26493 
LowerREADCYCLECOUNTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26494 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
26495                                      SelectionDAG &DAG) {
26496   SmallVector<SDValue, 3> Results;
26497   SDLoc DL(Op);
26498   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
26499                           Results);
26500   return DAG.getMergeValues(Results, DL);
26501 }
26502 
MarkEHRegistrationNode(SDValue Op,SelectionDAG & DAG)26503 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
26504   MachineFunction &MF = DAG.getMachineFunction();
26505   SDValue Chain = Op.getOperand(0);
26506   SDValue RegNode = Op.getOperand(2);
26507   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
26508   if (!EHInfo)
26509     report_fatal_error("EH registrations only live in functions using WinEH");
26510 
26511   // Cast the operand to an alloca, and remember the frame index.
26512   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
26513   if (!FINode)
26514     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
26515   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
26516 
26517   // Return the chain operand without making any DAG nodes.
26518   return Chain;
26519 }
26520 
MarkEHGuard(SDValue Op,SelectionDAG & DAG)26521 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
26522   MachineFunction &MF = DAG.getMachineFunction();
26523   SDValue Chain = Op.getOperand(0);
26524   SDValue EHGuard = Op.getOperand(2);
26525   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
26526   if (!EHInfo)
26527     report_fatal_error("EHGuard only live in functions using WinEH");
26528 
26529   // Cast the operand to an alloca, and remember the frame index.
26530   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
26531   if (!FINode)
26532     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
26533   EHInfo->EHGuardFrameIndex = FINode->getIndex();
26534 
26535   // Return the chain operand without making any DAG nodes.
26536   return Chain;
26537 }
26538 
26539 /// Emit Truncating Store with signed or unsigned saturation.
26540 static SDValue
EmitTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & DL,SDValue Val,SDValue Ptr,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)26541 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &DL, SDValue Val,
26542                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
26543                 SelectionDAG &DAG) {
26544   SDVTList VTs = DAG.getVTList(MVT::Other);
26545   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
26546   SDValue Ops[] = { Chain, Val, Ptr, Undef };
26547   unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
26548   return DAG.getMemIntrinsicNode(Opc, DL, VTs, Ops, MemVT, MMO);
26549 }
26550 
26551 /// Emit Masked Truncating Store with signed or unsigned saturation.
EmitMaskedTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & DL,SDValue Val,SDValue Ptr,SDValue Mask,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)26552 static SDValue EmitMaskedTruncSStore(bool SignedSat, SDValue Chain,
26553                                      const SDLoc &DL,
26554                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
26555                       MachineMemOperand *MMO, SelectionDAG &DAG) {
26556   SDVTList VTs = DAG.getVTList(MVT::Other);
26557   SDValue Ops[] = { Chain, Val, Ptr, Mask };
26558   unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
26559   return DAG.getMemIntrinsicNode(Opc, DL, VTs, Ops, MemVT, MMO);
26560 }
26561 
LowerINTRINSIC_W_CHAIN(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26562 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
26563                                       SelectionDAG &DAG) {
26564   unsigned IntNo = Op.getConstantOperandVal(1);
26565   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
26566   if (!IntrData) {
26567     switch (IntNo) {
26568 
26569     case Intrinsic::swift_async_context_addr: {
26570       SDLoc dl(Op);
26571       auto &MF = DAG.getMachineFunction();
26572       auto X86FI = MF.getInfo<X86MachineFunctionInfo>();
26573       if (Subtarget.is64Bit()) {
26574         MF.getFrameInfo().setFrameAddressIsTaken(true);
26575         X86FI->setHasSwiftAsyncContext(true);
26576         SDValue Chain = Op->getOperand(0);
26577         SDValue CopyRBP = DAG.getCopyFromReg(Chain, dl, X86::RBP, MVT::i64);
26578         SDValue Result =
26579             SDValue(DAG.getMachineNode(X86::SUB64ri32, dl, MVT::i64, CopyRBP,
26580                                        DAG.getTargetConstant(8, dl, MVT::i32)),
26581                     0);
26582         // Return { result, chain }.
26583         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
26584                            CopyRBP.getValue(1));
26585       } else {
26586         // 32-bit so no special extended frame, create or reuse an existing
26587         // stack slot.
26588         if (!X86FI->getSwiftAsyncContextFrameIdx())
26589           X86FI->setSwiftAsyncContextFrameIdx(
26590               MF.getFrameInfo().CreateStackObject(4, Align(4), false));
26591         SDValue Result =
26592             DAG.getFrameIndex(*X86FI->getSwiftAsyncContextFrameIdx(), MVT::i32);
26593         // Return { result, chain }.
26594         return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result,
26595                            Op->getOperand(0));
26596       }
26597     }
26598 
26599     case llvm::Intrinsic::x86_seh_ehregnode:
26600       return MarkEHRegistrationNode(Op, DAG);
26601     case llvm::Intrinsic::x86_seh_ehguard:
26602       return MarkEHGuard(Op, DAG);
26603     case llvm::Intrinsic::x86_rdpkru: {
26604       SDLoc dl(Op);
26605       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26606       // Create a RDPKRU node and pass 0 to the ECX parameter.
26607       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
26608                          DAG.getConstant(0, dl, MVT::i32));
26609     }
26610     case llvm::Intrinsic::x86_wrpkru: {
26611       SDLoc dl(Op);
26612       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
26613       // to the EDX and ECX parameters.
26614       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
26615                          Op.getOperand(0), Op.getOperand(2),
26616                          DAG.getConstant(0, dl, MVT::i32),
26617                          DAG.getConstant(0, dl, MVT::i32));
26618     }
26619     case llvm::Intrinsic::asan_check_memaccess: {
26620       // Mark this as adjustsStack because it will be lowered to a call.
26621       DAG.getMachineFunction().getFrameInfo().setAdjustsStack(true);
26622       // Don't do anything here, we will expand these intrinsics out later.
26623       return Op;
26624     }
26625     case llvm::Intrinsic::x86_flags_read_u32:
26626     case llvm::Intrinsic::x86_flags_read_u64:
26627     case llvm::Intrinsic::x86_flags_write_u32:
26628     case llvm::Intrinsic::x86_flags_write_u64: {
26629       // We need a frame pointer because this will get lowered to a PUSH/POP
26630       // sequence.
26631       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
26632       MFI.setHasCopyImplyingStackAdjustment(true);
26633       // Don't do anything here, we will expand these intrinsics out later
26634       // during FinalizeISel in EmitInstrWithCustomInserter.
26635       return Op;
26636     }
26637     case Intrinsic::x86_lwpins32:
26638     case Intrinsic::x86_lwpins64:
26639     case Intrinsic::x86_umwait:
26640     case Intrinsic::x86_tpause: {
26641       SDLoc dl(Op);
26642       SDValue Chain = Op->getOperand(0);
26643       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26644       unsigned Opcode;
26645 
26646       switch (IntNo) {
26647       default: llvm_unreachable("Impossible intrinsic");
26648       case Intrinsic::x86_umwait:
26649         Opcode = X86ISD::UMWAIT;
26650         break;
26651       case Intrinsic::x86_tpause:
26652         Opcode = X86ISD::TPAUSE;
26653         break;
26654       case Intrinsic::x86_lwpins32:
26655       case Intrinsic::x86_lwpins64:
26656         Opcode = X86ISD::LWPINS;
26657         break;
26658       }
26659 
26660       SDValue Operation =
26661           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
26662                       Op->getOperand(3), Op->getOperand(4));
26663       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
26664       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26665                          Operation.getValue(1));
26666     }
26667     case Intrinsic::x86_enqcmd:
26668     case Intrinsic::x86_enqcmds: {
26669       SDLoc dl(Op);
26670       SDValue Chain = Op.getOperand(0);
26671       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26672       unsigned Opcode;
26673       switch (IntNo) {
26674       default: llvm_unreachable("Impossible intrinsic!");
26675       case Intrinsic::x86_enqcmd:
26676         Opcode = X86ISD::ENQCMD;
26677         break;
26678       case Intrinsic::x86_enqcmds:
26679         Opcode = X86ISD::ENQCMDS;
26680         break;
26681       }
26682       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
26683                                       Op.getOperand(3));
26684       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
26685       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26686                          Operation.getValue(1));
26687     }
26688     case Intrinsic::x86_aesenc128kl:
26689     case Intrinsic::x86_aesdec128kl:
26690     case Intrinsic::x86_aesenc256kl:
26691     case Intrinsic::x86_aesdec256kl: {
26692       SDLoc DL(Op);
26693       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
26694       SDValue Chain = Op.getOperand(0);
26695       unsigned Opcode;
26696 
26697       switch (IntNo) {
26698       default: llvm_unreachable("Impossible intrinsic");
26699       case Intrinsic::x86_aesenc128kl:
26700         Opcode = X86ISD::AESENC128KL;
26701         break;
26702       case Intrinsic::x86_aesdec128kl:
26703         Opcode = X86ISD::AESDEC128KL;
26704         break;
26705       case Intrinsic::x86_aesenc256kl:
26706         Opcode = X86ISD::AESENC256KL;
26707         break;
26708       case Intrinsic::x86_aesdec256kl:
26709         Opcode = X86ISD::AESDEC256KL;
26710         break;
26711       }
26712 
26713       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26714       MachineMemOperand *MMO = MemIntr->getMemOperand();
26715       EVT MemVT = MemIntr->getMemoryVT();
26716       SDValue Operation = DAG.getMemIntrinsicNode(
26717           Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
26718           MMO);
26719       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
26720 
26721       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26722                          {ZF, Operation.getValue(0), Operation.getValue(2)});
26723     }
26724     case Intrinsic::x86_aesencwide128kl:
26725     case Intrinsic::x86_aesdecwide128kl:
26726     case Intrinsic::x86_aesencwide256kl:
26727     case Intrinsic::x86_aesdecwide256kl: {
26728       SDLoc DL(Op);
26729       SDVTList VTs = DAG.getVTList(
26730           {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
26731            MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
26732       SDValue Chain = Op.getOperand(0);
26733       unsigned Opcode;
26734 
26735       switch (IntNo) {
26736       default: llvm_unreachable("Impossible intrinsic");
26737       case Intrinsic::x86_aesencwide128kl:
26738         Opcode = X86ISD::AESENCWIDE128KL;
26739         break;
26740       case Intrinsic::x86_aesdecwide128kl:
26741         Opcode = X86ISD::AESDECWIDE128KL;
26742         break;
26743       case Intrinsic::x86_aesencwide256kl:
26744         Opcode = X86ISD::AESENCWIDE256KL;
26745         break;
26746       case Intrinsic::x86_aesdecwide256kl:
26747         Opcode = X86ISD::AESDECWIDE256KL;
26748         break;
26749       }
26750 
26751       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26752       MachineMemOperand *MMO = MemIntr->getMemOperand();
26753       EVT MemVT = MemIntr->getMemoryVT();
26754       SDValue Operation = DAG.getMemIntrinsicNode(
26755           Opcode, DL, VTs,
26756           {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
26757            Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
26758            Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
26759           MemVT, MMO);
26760       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
26761 
26762       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26763                          {ZF, Operation.getValue(1), Operation.getValue(2),
26764                           Operation.getValue(3), Operation.getValue(4),
26765                           Operation.getValue(5), Operation.getValue(6),
26766                           Operation.getValue(7), Operation.getValue(8),
26767                           Operation.getValue(9)});
26768     }
26769     case Intrinsic::x86_testui: {
26770       SDLoc dl(Op);
26771       SDValue Chain = Op.getOperand(0);
26772       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26773       SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
26774       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
26775       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26776                          Operation.getValue(1));
26777     }
26778     case Intrinsic::x86_atomic_bts_rm:
26779     case Intrinsic::x86_atomic_btc_rm:
26780     case Intrinsic::x86_atomic_btr_rm: {
26781       SDLoc DL(Op);
26782       MVT VT = Op.getSimpleValueType();
26783       SDValue Chain = Op.getOperand(0);
26784       SDValue Op1 = Op.getOperand(2);
26785       SDValue Op2 = Op.getOperand(3);
26786       unsigned Opc = IntNo == Intrinsic::x86_atomic_bts_rm   ? X86ISD::LBTS_RM
26787                      : IntNo == Intrinsic::x86_atomic_btc_rm ? X86ISD::LBTC_RM
26788                                                              : X86ISD::LBTR_RM;
26789       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
26790       SDValue Res =
26791           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
26792                                   {Chain, Op1, Op2}, VT, MMO);
26793       Chain = Res.getValue(1);
26794       Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
26795       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
26796     }
26797     case Intrinsic::x86_atomic_bts:
26798     case Intrinsic::x86_atomic_btc:
26799     case Intrinsic::x86_atomic_btr: {
26800       SDLoc DL(Op);
26801       MVT VT = Op.getSimpleValueType();
26802       SDValue Chain = Op.getOperand(0);
26803       SDValue Op1 = Op.getOperand(2);
26804       SDValue Op2 = Op.getOperand(3);
26805       unsigned Opc = IntNo == Intrinsic::x86_atomic_bts   ? X86ISD::LBTS
26806                      : IntNo == Intrinsic::x86_atomic_btc ? X86ISD::LBTC
26807                                                           : X86ISD::LBTR;
26808       SDValue Size = DAG.getConstant(VT.getScalarSizeInBits(), DL, MVT::i32);
26809       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
26810       SDValue Res =
26811           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
26812                                   {Chain, Op1, Op2, Size}, VT, MMO);
26813       Chain = Res.getValue(1);
26814       Res = DAG.getZExtOrTrunc(getSETCC(X86::COND_B, Res, DL, DAG), DL, VT);
26815       unsigned Imm = Op2->getAsZExtVal();
26816       if (Imm)
26817         Res = DAG.getNode(ISD::SHL, DL, VT, Res,
26818                           DAG.getShiftAmountConstant(Imm, VT, DL));
26819       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Res, Chain);
26820     }
26821     case Intrinsic::x86_cmpccxadd32:
26822     case Intrinsic::x86_cmpccxadd64: {
26823       SDLoc DL(Op);
26824       SDValue Chain = Op.getOperand(0);
26825       SDValue Addr = Op.getOperand(2);
26826       SDValue Src1 = Op.getOperand(3);
26827       SDValue Src2 = Op.getOperand(4);
26828       SDValue CC = Op.getOperand(5);
26829       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
26830       SDValue Operation = DAG.getMemIntrinsicNode(
26831           X86ISD::CMPCCXADD, DL, Op->getVTList(), {Chain, Addr, Src1, Src2, CC},
26832           MVT::i32, MMO);
26833       return Operation;
26834     }
26835     case Intrinsic::x86_aadd32:
26836     case Intrinsic::x86_aadd64:
26837     case Intrinsic::x86_aand32:
26838     case Intrinsic::x86_aand64:
26839     case Intrinsic::x86_aor32:
26840     case Intrinsic::x86_aor64:
26841     case Intrinsic::x86_axor32:
26842     case Intrinsic::x86_axor64: {
26843       SDLoc DL(Op);
26844       SDValue Chain = Op.getOperand(0);
26845       SDValue Op1 = Op.getOperand(2);
26846       SDValue Op2 = Op.getOperand(3);
26847       MVT VT = Op2.getSimpleValueType();
26848       unsigned Opc = 0;
26849       switch (IntNo) {
26850       default:
26851         llvm_unreachable("Unknown Intrinsic");
26852       case Intrinsic::x86_aadd32:
26853       case Intrinsic::x86_aadd64:
26854         Opc = X86ISD::AADD;
26855         break;
26856       case Intrinsic::x86_aand32:
26857       case Intrinsic::x86_aand64:
26858         Opc = X86ISD::AAND;
26859         break;
26860       case Intrinsic::x86_aor32:
26861       case Intrinsic::x86_aor64:
26862         Opc = X86ISD::AOR;
26863         break;
26864       case Intrinsic::x86_axor32:
26865       case Intrinsic::x86_axor64:
26866         Opc = X86ISD::AXOR;
26867         break;
26868       }
26869       MachineMemOperand *MMO = cast<MemSDNode>(Op)->getMemOperand();
26870       return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(),
26871                                      {Chain, Op1, Op2}, VT, MMO);
26872     }
26873     case Intrinsic::x86_atomic_add_cc:
26874     case Intrinsic::x86_atomic_sub_cc:
26875     case Intrinsic::x86_atomic_or_cc:
26876     case Intrinsic::x86_atomic_and_cc:
26877     case Intrinsic::x86_atomic_xor_cc: {
26878       SDLoc DL(Op);
26879       SDValue Chain = Op.getOperand(0);
26880       SDValue Op1 = Op.getOperand(2);
26881       SDValue Op2 = Op.getOperand(3);
26882       X86::CondCode CC = (X86::CondCode)Op.getConstantOperandVal(4);
26883       MVT VT = Op2.getSimpleValueType();
26884       unsigned Opc = 0;
26885       switch (IntNo) {
26886       default:
26887         llvm_unreachable("Unknown Intrinsic");
26888       case Intrinsic::x86_atomic_add_cc:
26889         Opc = X86ISD::LADD;
26890         break;
26891       case Intrinsic::x86_atomic_sub_cc:
26892         Opc = X86ISD::LSUB;
26893         break;
26894       case Intrinsic::x86_atomic_or_cc:
26895         Opc = X86ISD::LOR;
26896         break;
26897       case Intrinsic::x86_atomic_and_cc:
26898         Opc = X86ISD::LAND;
26899         break;
26900       case Intrinsic::x86_atomic_xor_cc:
26901         Opc = X86ISD::LXOR;
26902         break;
26903       }
26904       MachineMemOperand *MMO = cast<MemIntrinsicSDNode>(Op)->getMemOperand();
26905       SDValue LockArith =
26906           DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::i32, MVT::Other),
26907                                   {Chain, Op1, Op2}, VT, MMO);
26908       Chain = LockArith.getValue(1);
26909       return DAG.getMergeValues({getSETCC(CC, LockArith, DL, DAG), Chain}, DL);
26910     }
26911     }
26912     return SDValue();
26913   }
26914 
26915   SDLoc dl(Op);
26916   switch(IntrData->Type) {
26917   default: llvm_unreachable("Unknown Intrinsic Type");
26918   case RDSEED:
26919   case RDRAND: {
26920     // Emit the node with the right value type.
26921     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
26922     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
26923 
26924     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
26925     // Otherwise return the value from Rand, which is always 0, casted to i32.
26926     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
26927                      DAG.getConstant(1, dl, Op->getValueType(1)),
26928                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
26929                      SDValue(Result.getNode(), 1)};
26930     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
26931 
26932     // Return { result, isValid, chain }.
26933     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
26934                        SDValue(Result.getNode(), 2));
26935   }
26936   case GATHER_AVX2: {
26937     SDValue Chain = Op.getOperand(0);
26938     SDValue Src   = Op.getOperand(2);
26939     SDValue Base  = Op.getOperand(3);
26940     SDValue Index = Op.getOperand(4);
26941     SDValue Mask  = Op.getOperand(5);
26942     SDValue Scale = Op.getOperand(6);
26943     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
26944                              Scale, Chain, Subtarget);
26945   }
26946   case GATHER: {
26947   //gather(v1, mask, index, base, scale);
26948     SDValue Chain = Op.getOperand(0);
26949     SDValue Src   = Op.getOperand(2);
26950     SDValue Base  = Op.getOperand(3);
26951     SDValue Index = Op.getOperand(4);
26952     SDValue Mask  = Op.getOperand(5);
26953     SDValue Scale = Op.getOperand(6);
26954     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
26955                          Chain, Subtarget);
26956   }
26957   case SCATTER: {
26958   //scatter(base, mask, index, v1, scale);
26959     SDValue Chain = Op.getOperand(0);
26960     SDValue Base  = Op.getOperand(2);
26961     SDValue Mask  = Op.getOperand(3);
26962     SDValue Index = Op.getOperand(4);
26963     SDValue Src   = Op.getOperand(5);
26964     SDValue Scale = Op.getOperand(6);
26965     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
26966                           Scale, Chain, Subtarget);
26967   }
26968   case PREFETCH: {
26969     const APInt &HintVal = Op.getConstantOperandAPInt(6);
26970     assert((HintVal == 2 || HintVal == 3) &&
26971            "Wrong prefetch hint in intrinsic: should be 2 or 3");
26972     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
26973     SDValue Chain = Op.getOperand(0);
26974     SDValue Mask  = Op.getOperand(2);
26975     SDValue Index = Op.getOperand(3);
26976     SDValue Base  = Op.getOperand(4);
26977     SDValue Scale = Op.getOperand(5);
26978     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
26979                            Subtarget);
26980   }
26981   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
26982   case RDTSC: {
26983     SmallVector<SDValue, 2> Results;
26984     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
26985                             Results);
26986     return DAG.getMergeValues(Results, dl);
26987   }
26988   // Read Performance Monitoring Counters.
26989   case RDPMC:
26990   // Read Processor Register.
26991   case RDPRU:
26992   // GetExtended Control Register.
26993   case XGETBV: {
26994     SmallVector<SDValue, 2> Results;
26995 
26996     // RDPMC uses ECX to select the index of the performance counter to read.
26997     // RDPRU uses ECX to select the processor register to read.
26998     // XGETBV uses ECX to select the index of the XCR register to return.
26999     // The result is stored into registers EDX:EAX.
27000     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
27001                                 Subtarget, Results);
27002     return DAG.getMergeValues(Results, dl);
27003   }
27004   // XTEST intrinsics.
27005   case XTEST: {
27006     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
27007     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
27008 
27009     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
27010     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
27011     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
27012                        Ret, SDValue(InTrans.getNode(), 1));
27013   }
27014   case TRUNCATE_TO_MEM_VI8:
27015   case TRUNCATE_TO_MEM_VI16:
27016   case TRUNCATE_TO_MEM_VI32: {
27017     SDValue Mask = Op.getOperand(4);
27018     SDValue DataToTruncate = Op.getOperand(3);
27019     SDValue Addr = Op.getOperand(2);
27020     SDValue Chain = Op.getOperand(0);
27021 
27022     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
27023     assert(MemIntr && "Expected MemIntrinsicSDNode!");
27024 
27025     EVT MemVT  = MemIntr->getMemoryVT();
27026 
27027     uint16_t TruncationOp = IntrData->Opc0;
27028     switch (TruncationOp) {
27029     case X86ISD::VTRUNC: {
27030       if (isAllOnesConstant(Mask)) // return just a truncate store
27031         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
27032                                  MemIntr->getMemOperand());
27033 
27034       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
27035       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27036       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
27037 
27038       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
27039                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
27040                                 true /* truncating */);
27041     }
27042     case X86ISD::VTRUNCUS:
27043     case X86ISD::VTRUNCS: {
27044       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
27045       if (isAllOnesConstant(Mask))
27046         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
27047                                MemIntr->getMemOperand(), DAG);
27048 
27049       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
27050       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
27051 
27052       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
27053                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
27054     }
27055     default:
27056       llvm_unreachable("Unsupported truncstore intrinsic");
27057     }
27058   }
27059   }
27060 }
27061 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const27062 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
27063                                            SelectionDAG &DAG) const {
27064   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
27065   MFI.setReturnAddressIsTaken(true);
27066 
27067   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
27068     return SDValue();
27069 
27070   unsigned Depth = Op.getConstantOperandVal(0);
27071   SDLoc dl(Op);
27072   EVT PtrVT = getPointerTy(DAG.getDataLayout());
27073 
27074   if (Depth > 0) {
27075     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
27076     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27077     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
27078     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
27079                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
27080                        MachinePointerInfo());
27081   }
27082 
27083   // Just load the return address.
27084   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
27085   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
27086                      MachinePointerInfo());
27087 }
27088 
LowerADDROFRETURNADDR(SDValue Op,SelectionDAG & DAG) const27089 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
27090                                                  SelectionDAG &DAG) const {
27091   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
27092   return getReturnAddressFrameIndex(DAG);
27093 }
27094 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const27095 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
27096   MachineFunction &MF = DAG.getMachineFunction();
27097   MachineFrameInfo &MFI = MF.getFrameInfo();
27098   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
27099   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27100   EVT VT = Op.getValueType();
27101 
27102   MFI.setFrameAddressIsTaken(true);
27103 
27104   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
27105     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
27106     // is not possible to crawl up the stack without looking at the unwind codes
27107     // simultaneously.
27108     int FrameAddrIndex = FuncInfo->getFAIndex();
27109     if (!FrameAddrIndex) {
27110       // Set up a frame object for the return address.
27111       unsigned SlotSize = RegInfo->getSlotSize();
27112       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
27113           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
27114       FuncInfo->setFAIndex(FrameAddrIndex);
27115     }
27116     return DAG.getFrameIndex(FrameAddrIndex, VT);
27117   }
27118 
27119   unsigned FrameReg =
27120       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
27121   SDLoc dl(Op);  // FIXME probably not meaningful
27122   unsigned Depth = Op.getConstantOperandVal(0);
27123   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
27124           (FrameReg == X86::EBP && VT == MVT::i32)) &&
27125          "Invalid Frame Register!");
27126   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
27127   while (Depth--)
27128     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
27129                             MachinePointerInfo());
27130   return FrameAddr;
27131 }
27132 
27133 // FIXME? Maybe this could be a TableGen attribute on some registers and
27134 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const27135 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
27136                                               const MachineFunction &MF) const {
27137   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
27138 
27139   Register Reg = StringSwitch<unsigned>(RegName)
27140                      .Case("esp", X86::ESP)
27141                      .Case("rsp", X86::RSP)
27142                      .Case("ebp", X86::EBP)
27143                      .Case("rbp", X86::RBP)
27144                      .Case("r14", X86::R14)
27145                      .Case("r15", X86::R15)
27146                      .Default(0);
27147 
27148   if (Reg == X86::EBP || Reg == X86::RBP) {
27149     if (!TFI.hasFP(MF))
27150       report_fatal_error("register " + StringRef(RegName) +
27151                          " is allocatable: function has no frame pointer");
27152 #ifndef NDEBUG
27153     else {
27154       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27155       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
27156       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
27157              "Invalid Frame Register!");
27158     }
27159 #endif
27160   }
27161 
27162   if (Reg)
27163     return Reg;
27164 
27165   report_fatal_error("Invalid register name global variable");
27166 }
27167 
LowerFRAME_TO_ARGS_OFFSET(SDValue Op,SelectionDAG & DAG) const27168 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
27169                                                      SelectionDAG &DAG) const {
27170   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27171   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
27172 }
27173 
getExceptionPointerRegister(const Constant * PersonalityFn) const27174 Register X86TargetLowering::getExceptionPointerRegister(
27175     const Constant *PersonalityFn) const {
27176   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
27177     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
27178 
27179   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
27180 }
27181 
getExceptionSelectorRegister(const Constant * PersonalityFn) const27182 Register X86TargetLowering::getExceptionSelectorRegister(
27183     const Constant *PersonalityFn) const {
27184   // Funclet personalities don't use selectors (the runtime does the selection).
27185   if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
27186     return X86::NoRegister;
27187   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
27188 }
27189 
needsFixedCatchObjects() const27190 bool X86TargetLowering::needsFixedCatchObjects() const {
27191   return Subtarget.isTargetWin64();
27192 }
27193 
LowerEH_RETURN(SDValue Op,SelectionDAG & DAG) const27194 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
27195   SDValue Chain     = Op.getOperand(0);
27196   SDValue Offset    = Op.getOperand(1);
27197   SDValue Handler   = Op.getOperand(2);
27198   SDLoc dl      (Op);
27199 
27200   EVT PtrVT = getPointerTy(DAG.getDataLayout());
27201   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
27202   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
27203   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
27204           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
27205          "Invalid Frame Register!");
27206   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
27207   Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
27208 
27209   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
27210                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
27211                                                        dl));
27212   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
27213   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
27214   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
27215 
27216   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
27217                      DAG.getRegister(StoreAddrReg, PtrVT));
27218 }
27219 
lowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const27220 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
27221                                                SelectionDAG &DAG) const {
27222   SDLoc DL(Op);
27223   // If the subtarget is not 64bit, we may need the global base reg
27224   // after isel expand pseudo, i.e., after CGBR pass ran.
27225   // Therefore, ask for the GlobalBaseReg now, so that the pass
27226   // inserts the code for us in case we need it.
27227   // Otherwise, we will end up in a situation where we will
27228   // reference a virtual register that is not defined!
27229   if (!Subtarget.is64Bit()) {
27230     const X86InstrInfo *TII = Subtarget.getInstrInfo();
27231     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
27232   }
27233   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
27234                      DAG.getVTList(MVT::i32, MVT::Other),
27235                      Op.getOperand(0), Op.getOperand(1));
27236 }
27237 
lowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const27238 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
27239                                                 SelectionDAG &DAG) const {
27240   SDLoc DL(Op);
27241   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
27242                      Op.getOperand(0), Op.getOperand(1));
27243 }
27244 
lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,SelectionDAG & DAG) const27245 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
27246                                                        SelectionDAG &DAG) const {
27247   SDLoc DL(Op);
27248   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
27249                      Op.getOperand(0));
27250 }
27251 
LowerADJUST_TRAMPOLINE(SDValue Op,SelectionDAG & DAG)27252 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
27253   return Op.getOperand(0);
27254 }
27255 
LowerINIT_TRAMPOLINE(SDValue Op,SelectionDAG & DAG) const27256 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
27257                                                 SelectionDAG &DAG) const {
27258   SDValue Root = Op.getOperand(0);
27259   SDValue Trmp = Op.getOperand(1); // trampoline
27260   SDValue FPtr = Op.getOperand(2); // nested function
27261   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
27262   SDLoc dl (Op);
27263 
27264   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
27265   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
27266 
27267   if (Subtarget.is64Bit()) {
27268     SDValue OutChains[6];
27269 
27270     // Large code-model.
27271     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
27272     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
27273 
27274     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
27275     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
27276 
27277     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
27278 
27279     // Load the pointer to the nested function into R11.
27280     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
27281     SDValue Addr = Trmp;
27282     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27283                                 Addr, MachinePointerInfo(TrmpAddr));
27284 
27285     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27286                        DAG.getConstant(2, dl, MVT::i64));
27287     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
27288                                 MachinePointerInfo(TrmpAddr, 2), Align(2));
27289 
27290     // Load the 'nest' parameter value into R10.
27291     // R10 is specified in X86CallingConv.td
27292     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
27293     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27294                        DAG.getConstant(10, dl, MVT::i64));
27295     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27296                                 Addr, MachinePointerInfo(TrmpAddr, 10));
27297 
27298     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27299                        DAG.getConstant(12, dl, MVT::i64));
27300     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
27301                                 MachinePointerInfo(TrmpAddr, 12), Align(2));
27302 
27303     // Jump to the nested function.
27304     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
27305     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27306                        DAG.getConstant(20, dl, MVT::i64));
27307     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
27308                                 Addr, MachinePointerInfo(TrmpAddr, 20));
27309 
27310     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
27311     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
27312                        DAG.getConstant(22, dl, MVT::i64));
27313     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
27314                                 Addr, MachinePointerInfo(TrmpAddr, 22));
27315 
27316     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27317   } else {
27318     const Function *Func =
27319       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
27320     CallingConv::ID CC = Func->getCallingConv();
27321     unsigned NestReg;
27322 
27323     switch (CC) {
27324     default:
27325       llvm_unreachable("Unsupported calling convention");
27326     case CallingConv::C:
27327     case CallingConv::X86_StdCall: {
27328       // Pass 'nest' parameter in ECX.
27329       // Must be kept in sync with X86CallingConv.td
27330       NestReg = X86::ECX;
27331 
27332       // Check that ECX wasn't needed by an 'inreg' parameter.
27333       FunctionType *FTy = Func->getFunctionType();
27334       const AttributeList &Attrs = Func->getAttributes();
27335 
27336       if (!Attrs.isEmpty() && !Func->isVarArg()) {
27337         unsigned InRegCount = 0;
27338         unsigned Idx = 0;
27339 
27340         for (FunctionType::param_iterator I = FTy->param_begin(),
27341              E = FTy->param_end(); I != E; ++I, ++Idx)
27342           if (Attrs.hasParamAttr(Idx, Attribute::InReg)) {
27343             const DataLayout &DL = DAG.getDataLayout();
27344             // FIXME: should only count parameters that are lowered to integers.
27345             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
27346           }
27347 
27348         if (InRegCount > 2) {
27349           report_fatal_error("Nest register in use - reduce number of inreg"
27350                              " parameters!");
27351         }
27352       }
27353       break;
27354     }
27355     case CallingConv::X86_FastCall:
27356     case CallingConv::X86_ThisCall:
27357     case CallingConv::Fast:
27358     case CallingConv::Tail:
27359     case CallingConv::SwiftTail:
27360       // Pass 'nest' parameter in EAX.
27361       // Must be kept in sync with X86CallingConv.td
27362       NestReg = X86::EAX;
27363       break;
27364     }
27365 
27366     SDValue OutChains[4];
27367     SDValue Addr, Disp;
27368 
27369     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27370                        DAG.getConstant(10, dl, MVT::i32));
27371     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
27372 
27373     // This is storing the opcode for MOV32ri.
27374     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
27375     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
27376     OutChains[0] =
27377         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
27378                      Trmp, MachinePointerInfo(TrmpAddr));
27379 
27380     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27381                        DAG.getConstant(1, dl, MVT::i32));
27382     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
27383                                 MachinePointerInfo(TrmpAddr, 1), Align(1));
27384 
27385     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
27386     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27387                        DAG.getConstant(5, dl, MVT::i32));
27388     OutChains[2] =
27389         DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
27390                      MachinePointerInfo(TrmpAddr, 5), Align(1));
27391 
27392     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
27393                        DAG.getConstant(6, dl, MVT::i32));
27394     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
27395                                 MachinePointerInfo(TrmpAddr, 6), Align(1));
27396 
27397     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
27398   }
27399 }
27400 
LowerGET_ROUNDING(SDValue Op,SelectionDAG & DAG) const27401 SDValue X86TargetLowering::LowerGET_ROUNDING(SDValue Op,
27402                                              SelectionDAG &DAG) const {
27403   /*
27404    The rounding mode is in bits 11:10 of FPSR, and has the following
27405    settings:
27406      00 Round to nearest
27407      01 Round to -inf
27408      10 Round to +inf
27409      11 Round to 0
27410 
27411   GET_ROUNDING, on the other hand, expects the following:
27412     -1 Undefined
27413      0 Round to 0
27414      1 Round to nearest
27415      2 Round to +inf
27416      3 Round to -inf
27417 
27418   To perform the conversion, we use a packed lookup table of the four 2-bit
27419   values that we can index by FPSP[11:10]
27420     0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
27421 
27422     (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
27423   */
27424 
27425   MachineFunction &MF = DAG.getMachineFunction();
27426   MVT VT = Op.getSimpleValueType();
27427   SDLoc DL(Op);
27428 
27429   // Save FP Control Word to stack slot
27430   int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
27431   SDValue StackSlot =
27432       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
27433 
27434   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
27435 
27436   SDValue Chain = Op.getOperand(0);
27437   SDValue Ops[] = {Chain, StackSlot};
27438   Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
27439                                   DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
27440                                   Align(2), MachineMemOperand::MOStore);
27441 
27442   // Load FP Control Word from stack slot
27443   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
27444   Chain = CWD.getValue(1);
27445 
27446   // Mask and turn the control bits into a shift for the lookup table.
27447   SDValue Shift =
27448     DAG.getNode(ISD::SRL, DL, MVT::i16,
27449                 DAG.getNode(ISD::AND, DL, MVT::i16,
27450                             CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
27451                 DAG.getConstant(9, DL, MVT::i8));
27452   Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
27453 
27454   SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
27455   SDValue RetVal =
27456     DAG.getNode(ISD::AND, DL, MVT::i32,
27457                 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
27458                 DAG.getConstant(3, DL, MVT::i32));
27459 
27460   RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
27461 
27462   return DAG.getMergeValues({RetVal, Chain}, DL);
27463 }
27464 
LowerSET_ROUNDING(SDValue Op,SelectionDAG & DAG) const27465 SDValue X86TargetLowering::LowerSET_ROUNDING(SDValue Op,
27466                                              SelectionDAG &DAG) const {
27467   MachineFunction &MF = DAG.getMachineFunction();
27468   SDLoc DL(Op);
27469   SDValue Chain = Op.getNode()->getOperand(0);
27470 
27471   // FP control word may be set only from data in memory. So we need to allocate
27472   // stack space to save/load FP control word.
27473   int OldCWFrameIdx = MF.getFrameInfo().CreateStackObject(4, Align(4), false);
27474   SDValue StackSlot =
27475       DAG.getFrameIndex(OldCWFrameIdx, getPointerTy(DAG.getDataLayout()));
27476   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, OldCWFrameIdx);
27477   MachineMemOperand *MMO =
27478       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 2, Align(2));
27479 
27480   // Store FP control word into memory.
27481   SDValue Ops[] = {Chain, StackSlot};
27482   Chain = DAG.getMemIntrinsicNode(
27483       X86ISD::FNSTCW16m, DL, DAG.getVTList(MVT::Other), Ops, MVT::i16, MMO);
27484 
27485   // Load FP Control Word from stack slot and clear RM field (bits 11:10).
27486   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI);
27487   Chain = CWD.getValue(1);
27488   CWD = DAG.getNode(ISD::AND, DL, MVT::i16, CWD.getValue(0),
27489                     DAG.getConstant(0xf3ff, DL, MVT::i16));
27490 
27491   // Calculate new rounding mode.
27492   SDValue NewRM = Op.getNode()->getOperand(1);
27493   SDValue RMBits;
27494   if (auto *CVal = dyn_cast<ConstantSDNode>(NewRM)) {
27495     uint64_t RM = CVal->getZExtValue();
27496     int FieldVal;
27497     switch (static_cast<RoundingMode>(RM)) {
27498     case RoundingMode::NearestTiesToEven: FieldVal = X86::rmToNearest; break;
27499     case RoundingMode::TowardNegative:    FieldVal = X86::rmDownward; break;
27500     case RoundingMode::TowardPositive:    FieldVal = X86::rmUpward; break;
27501     case RoundingMode::TowardZero:        FieldVal = X86::rmTowardZero; break;
27502     default:
27503       llvm_unreachable("rounding mode is not supported by X86 hardware");
27504     }
27505     RMBits = DAG.getConstant(FieldVal, DL, MVT::i16);
27506   } else {
27507     // Need to convert argument into bits of control word:
27508     //    0 Round to 0       -> 11
27509     //    1 Round to nearest -> 00
27510     //    2 Round to +inf    -> 10
27511     //    3 Round to -inf    -> 01
27512     // The 2-bit value needs then to be shifted so that it occupies bits 11:10.
27513     // To make the conversion, put all these values into a value 0xc9 and shift
27514     // it left depending on the rounding mode:
27515     //    (0xc9 << 4) & 0xc00 = X86::rmTowardZero
27516     //    (0xc9 << 6) & 0xc00 = X86::rmToNearest
27517     //    ...
27518     // (0xc9 << (2 * NewRM + 4)) & 0xc00
27519     SDValue ShiftValue =
27520         DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
27521                     DAG.getNode(ISD::ADD, DL, MVT::i32,
27522                                 DAG.getNode(ISD::SHL, DL, MVT::i32, NewRM,
27523                                             DAG.getConstant(1, DL, MVT::i8)),
27524                                 DAG.getConstant(4, DL, MVT::i32)));
27525     SDValue Shifted =
27526         DAG.getNode(ISD::SHL, DL, MVT::i16, DAG.getConstant(0xc9, DL, MVT::i16),
27527                     ShiftValue);
27528     RMBits = DAG.getNode(ISD::AND, DL, MVT::i16, Shifted,
27529                          DAG.getConstant(0xc00, DL, MVT::i16));
27530   }
27531 
27532   // Update rounding mode bits and store the new FP Control Word into stack.
27533   CWD = DAG.getNode(ISD::OR, DL, MVT::i16, CWD, RMBits);
27534   Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, Align(2));
27535 
27536   // Load FP control word from the slot.
27537   SDValue OpsLD[] = {Chain, StackSlot};
27538   MachineMemOperand *MMOL =
27539       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 2, Align(2));
27540   Chain = DAG.getMemIntrinsicNode(
27541       X86ISD::FLDCW16m, DL, DAG.getVTList(MVT::Other), OpsLD, MVT::i16, MMOL);
27542 
27543   // If target supports SSE, set MXCSR as well. Rounding mode is encoded in the
27544   // same way but in bits 14:13.
27545   if (Subtarget.hasSSE1()) {
27546     // Store MXCSR into memory.
27547     Chain = DAG.getNode(
27548         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27549         DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
27550         StackSlot);
27551 
27552     // Load MXCSR from stack slot and clear RM field (bits 14:13).
27553     SDValue CWD = DAG.getLoad(MVT::i32, DL, Chain, StackSlot, MPI);
27554     Chain = CWD.getValue(1);
27555     CWD = DAG.getNode(ISD::AND, DL, MVT::i32, CWD.getValue(0),
27556                       DAG.getConstant(0xffff9fff, DL, MVT::i32));
27557 
27558     // Shift X87 RM bits from 11:10 to 14:13.
27559     RMBits = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, RMBits);
27560     RMBits = DAG.getNode(ISD::SHL, DL, MVT::i32, RMBits,
27561                          DAG.getConstant(3, DL, MVT::i8));
27562 
27563     // Update rounding mode bits and store the new FP Control Word into stack.
27564     CWD = DAG.getNode(ISD::OR, DL, MVT::i32, CWD, RMBits);
27565     Chain = DAG.getStore(Chain, DL, CWD, StackSlot, MPI, Align(4));
27566 
27567     // Load MXCSR from the slot.
27568     Chain = DAG.getNode(
27569         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27570         DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
27571         StackSlot);
27572   }
27573 
27574   return Chain;
27575 }
27576 
27577 const unsigned X87StateSize = 28;
27578 const unsigned FPStateSize = 32;
27579 [[maybe_unused]] const unsigned FPStateSizeInBits = FPStateSize * 8;
27580 
LowerGET_FPENV_MEM(SDValue Op,SelectionDAG & DAG) const27581 SDValue X86TargetLowering::LowerGET_FPENV_MEM(SDValue Op,
27582                                               SelectionDAG &DAG) const {
27583   MachineFunction &MF = DAG.getMachineFunction();
27584   SDLoc DL(Op);
27585   SDValue Chain = Op->getOperand(0);
27586   SDValue Ptr = Op->getOperand(1);
27587   auto *Node = cast<FPStateAccessSDNode>(Op);
27588   EVT MemVT = Node->getMemoryVT();
27589   assert(MemVT.getSizeInBits() == FPStateSizeInBits);
27590   MachineMemOperand *MMO = cast<FPStateAccessSDNode>(Op)->getMemOperand();
27591 
27592   // Get x87 state, if it presents.
27593   if (Subtarget.hasX87()) {
27594     Chain =
27595         DAG.getMemIntrinsicNode(X86ISD::FNSTENVm, DL, DAG.getVTList(MVT::Other),
27596                                 {Chain, Ptr}, MemVT, MMO);
27597 
27598     // FNSTENV changes the exception mask, so load back the stored environment.
27599     MachineMemOperand::Flags NewFlags =
27600         MachineMemOperand::MOLoad |
27601         (MMO->getFlags() & ~MachineMemOperand::MOStore);
27602     MMO = MF.getMachineMemOperand(MMO, NewFlags);
27603     Chain =
27604         DAG.getMemIntrinsicNode(X86ISD::FLDENVm, DL, DAG.getVTList(MVT::Other),
27605                                 {Chain, Ptr}, MemVT, MMO);
27606   }
27607 
27608   // If target supports SSE, get MXCSR as well.
27609   if (Subtarget.hasSSE1()) {
27610     // Get pointer to the MXCSR location in memory.
27611     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
27612     SDValue MXCSRAddr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr,
27613                                     DAG.getConstant(X87StateSize, DL, PtrVT));
27614     // Store MXCSR into memory.
27615     Chain = DAG.getNode(
27616         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27617         DAG.getTargetConstant(Intrinsic::x86_sse_stmxcsr, DL, MVT::i32),
27618         MXCSRAddr);
27619   }
27620 
27621   return Chain;
27622 }
27623 
createSetFPEnvNodes(SDValue Ptr,SDValue Chain,SDLoc DL,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG,const X86Subtarget & Subtarget)27624 static SDValue createSetFPEnvNodes(SDValue Ptr, SDValue Chain, SDLoc DL,
27625                                    EVT MemVT, MachineMemOperand *MMO,
27626                                    SelectionDAG &DAG,
27627                                    const X86Subtarget &Subtarget) {
27628   // Set x87 state, if it presents.
27629   if (Subtarget.hasX87())
27630     Chain =
27631         DAG.getMemIntrinsicNode(X86ISD::FLDENVm, DL, DAG.getVTList(MVT::Other),
27632                                 {Chain, Ptr}, MemVT, MMO);
27633   // If target supports SSE, set MXCSR as well.
27634   if (Subtarget.hasSSE1()) {
27635     // Get pointer to the MXCSR location in memory.
27636     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
27637     SDValue MXCSRAddr = DAG.getNode(ISD::ADD, DL, PtrVT, Ptr,
27638                                     DAG.getConstant(X87StateSize, DL, PtrVT));
27639     // Load MXCSR from memory.
27640     Chain = DAG.getNode(
27641         ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), Chain,
27642         DAG.getTargetConstant(Intrinsic::x86_sse_ldmxcsr, DL, MVT::i32),
27643         MXCSRAddr);
27644   }
27645   return Chain;
27646 }
27647 
LowerSET_FPENV_MEM(SDValue Op,SelectionDAG & DAG) const27648 SDValue X86TargetLowering::LowerSET_FPENV_MEM(SDValue Op,
27649                                               SelectionDAG &DAG) const {
27650   SDLoc DL(Op);
27651   SDValue Chain = Op->getOperand(0);
27652   SDValue Ptr = Op->getOperand(1);
27653   auto *Node = cast<FPStateAccessSDNode>(Op);
27654   EVT MemVT = Node->getMemoryVT();
27655   assert(MemVT.getSizeInBits() == FPStateSizeInBits);
27656   MachineMemOperand *MMO = cast<FPStateAccessSDNode>(Op)->getMemOperand();
27657   return createSetFPEnvNodes(Ptr, Chain, DL, MemVT, MMO, DAG, Subtarget);
27658 }
27659 
LowerRESET_FPENV(SDValue Op,SelectionDAG & DAG) const27660 SDValue X86TargetLowering::LowerRESET_FPENV(SDValue Op,
27661                                             SelectionDAG &DAG) const {
27662   MachineFunction &MF = DAG.getMachineFunction();
27663   SDLoc DL(Op);
27664   SDValue Chain = Op.getNode()->getOperand(0);
27665 
27666   IntegerType *ItemTy = Type::getInt32Ty(*DAG.getContext());
27667   ArrayType *FPEnvTy = ArrayType::get(ItemTy, 8);
27668   SmallVector<Constant *, 8> FPEnvVals;
27669 
27670   // x87 FPU Control Word: mask all floating-point exceptions, sets rounding to
27671   // nearest. FPU precision is set to 53 bits on Windows and 64 bits otherwise
27672   // for compatibility with glibc.
27673   unsigned X87CW = Subtarget.isTargetWindowsMSVC() ? 0x27F : 0x37F;
27674   FPEnvVals.push_back(ConstantInt::get(ItemTy, X87CW));
27675   Constant *Zero = ConstantInt::get(ItemTy, 0);
27676   for (unsigned I = 0; I < 6; ++I)
27677     FPEnvVals.push_back(Zero);
27678 
27679   // MXCSR: mask all floating-point exceptions, sets rounding to nearest, clear
27680   // all exceptions, sets DAZ and FTZ to 0.
27681   FPEnvVals.push_back(ConstantInt::get(ItemTy, 0x1F80));
27682   Constant *FPEnvBits = ConstantArray::get(FPEnvTy, FPEnvVals);
27683   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
27684   SDValue Env = DAG.getConstantPool(FPEnvBits, PtrVT);
27685   MachinePointerInfo MPI =
27686       MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
27687   MachineMemOperand *MMO = MF.getMachineMemOperand(
27688       MPI, MachineMemOperand::MOStore, X87StateSize, Align(4));
27689 
27690   return createSetFPEnvNodes(Env, Chain, DL, MVT::i32, MMO, DAG, Subtarget);
27691 }
27692 
27693 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
27694 //
27695 // i8/i16 vector implemented using dword LZCNT vector instruction
27696 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
27697 // split the vector, perform operation on it's Lo a Hi part and
27698 // concatenate the results.
LowerVectorCTLZ_AVX512CDI(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)27699 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
27700                                          const X86Subtarget &Subtarget) {
27701   assert(Op.getOpcode() == ISD::CTLZ);
27702   SDLoc dl(Op);
27703   MVT VT = Op.getSimpleValueType();
27704   MVT EltVT = VT.getVectorElementType();
27705   unsigned NumElems = VT.getVectorNumElements();
27706 
27707   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
27708           "Unsupported element type");
27709 
27710   // Split vector, it's Lo and Hi parts will be handled in next iteration.
27711   if (NumElems > 16 ||
27712       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
27713     return splitVectorIntUnary(Op, DAG);
27714 
27715   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
27716   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
27717           "Unsupported value type for operation");
27718 
27719   // Use native supported vector instruction vplzcntd.
27720   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
27721   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
27722   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
27723   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
27724 
27725   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
27726 }
27727 
27728 // Lower CTLZ using a PSHUFB lookup table implementation.
LowerVectorCTLZInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)27729 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
27730                                        const X86Subtarget &Subtarget,
27731                                        SelectionDAG &DAG) {
27732   MVT VT = Op.getSimpleValueType();
27733   int NumElts = VT.getVectorNumElements();
27734   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
27735   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
27736 
27737   // Per-nibble leading zero PSHUFB lookup table.
27738   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
27739                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
27740                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
27741                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
27742 
27743   SmallVector<SDValue, 64> LUTVec;
27744   for (int i = 0; i < NumBytes; ++i)
27745     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
27746   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
27747 
27748   // Begin by bitcasting the input to byte vector, then split those bytes
27749   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
27750   // If the hi input nibble is zero then we add both results together, otherwise
27751   // we just take the hi result (by masking the lo result to zero before the
27752   // add).
27753   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
27754   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
27755 
27756   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
27757   SDValue Lo = Op0;
27758   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
27759   SDValue HiZ;
27760   if (CurrVT.is512BitVector()) {
27761     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
27762     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
27763     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
27764   } else {
27765     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
27766   }
27767 
27768   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
27769   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
27770   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
27771   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
27772 
27773   // Merge result back from vXi8 back to VT, working on the lo/hi halves
27774   // of the current vector width in the same way we did for the nibbles.
27775   // If the upper half of the input element is zero then add the halves'
27776   // leading zero counts together, otherwise just use the upper half's.
27777   // Double the width of the result until we are at target width.
27778   while (CurrVT != VT) {
27779     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
27780     int CurrNumElts = CurrVT.getVectorNumElements();
27781     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
27782     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
27783     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
27784 
27785     // Check if the upper half of the input element is zero.
27786     if (CurrVT.is512BitVector()) {
27787       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
27788       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
27789                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
27790       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
27791     } else {
27792       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
27793                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
27794     }
27795     HiZ = DAG.getBitcast(NextVT, HiZ);
27796 
27797     // Move the upper/lower halves to the lower bits as we'll be extending to
27798     // NextVT. Mask the lower result to zero if HiZ is true and add the results
27799     // together.
27800     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
27801     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
27802     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
27803     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
27804     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
27805     CurrVT = NextVT;
27806   }
27807 
27808   return Res;
27809 }
27810 
LowerVectorCTLZ(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)27811 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
27812                                const X86Subtarget &Subtarget,
27813                                SelectionDAG &DAG) {
27814   MVT VT = Op.getSimpleValueType();
27815 
27816   if (Subtarget.hasCDI() &&
27817       // vXi8 vectors need to be promoted to 512-bits for vXi32.
27818       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
27819     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
27820 
27821   // Decompose 256-bit ops into smaller 128-bit ops.
27822   if (VT.is256BitVector() && !Subtarget.hasInt256())
27823     return splitVectorIntUnary(Op, DAG);
27824 
27825   // Decompose 512-bit ops into smaller 256-bit ops.
27826   if (VT.is512BitVector() && !Subtarget.hasBWI())
27827     return splitVectorIntUnary(Op, DAG);
27828 
27829   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
27830   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
27831 }
27832 
LowerCTLZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27833 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
27834                          SelectionDAG &DAG) {
27835   MVT VT = Op.getSimpleValueType();
27836   MVT OpVT = VT;
27837   unsigned NumBits = VT.getSizeInBits();
27838   SDLoc dl(Op);
27839   unsigned Opc = Op.getOpcode();
27840 
27841   if (VT.isVector())
27842     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
27843 
27844   Op = Op.getOperand(0);
27845   if (VT == MVT::i8) {
27846     // Zero extend to i32 since there is not an i8 bsr.
27847     OpVT = MVT::i32;
27848     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
27849   }
27850 
27851   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
27852   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
27853   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
27854 
27855   if (Opc == ISD::CTLZ) {
27856     // If src is zero (i.e. bsr sets ZF), returns NumBits.
27857     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
27858                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
27859                      Op.getValue(1)};
27860     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
27861   }
27862 
27863   // Finally xor with NumBits-1.
27864   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
27865                    DAG.getConstant(NumBits - 1, dl, OpVT));
27866 
27867   if (VT == MVT::i8)
27868     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
27869   return Op;
27870 }
27871 
LowerCTTZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27872 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
27873                          SelectionDAG &DAG) {
27874   MVT VT = Op.getSimpleValueType();
27875   unsigned NumBits = VT.getScalarSizeInBits();
27876   SDValue N0 = Op.getOperand(0);
27877   SDLoc dl(Op);
27878 
27879   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
27880          "Only scalar CTTZ requires custom lowering");
27881 
27882   // Issue a bsf (scan bits forward) which also sets EFLAGS.
27883   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
27884   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
27885 
27886   // If src is known never zero we can skip the CMOV.
27887   if (DAG.isKnownNeverZero(N0))
27888     return Op;
27889 
27890   // If src is zero (i.e. bsf sets ZF), returns NumBits.
27891   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
27892                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
27893                    Op.getValue(1)};
27894   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
27895 }
27896 
lowerAddSub(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)27897 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
27898                            const X86Subtarget &Subtarget) {
27899   MVT VT = Op.getSimpleValueType();
27900   if (VT == MVT::i16 || VT == MVT::i32)
27901     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
27902 
27903   if (VT == MVT::v32i16 || VT == MVT::v64i8)
27904     return splitVectorIntBinary(Op, DAG);
27905 
27906   assert(Op.getSimpleValueType().is256BitVector() &&
27907          Op.getSimpleValueType().isInteger() &&
27908          "Only handle AVX 256-bit vector integer operation");
27909   return splitVectorIntBinary(Op, DAG);
27910 }
27911 
LowerADDSAT_SUBSAT(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)27912 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
27913                                   const X86Subtarget &Subtarget) {
27914   MVT VT = Op.getSimpleValueType();
27915   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
27916   unsigned Opcode = Op.getOpcode();
27917   SDLoc DL(Op);
27918 
27919   if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
27920       (VT.is256BitVector() && !Subtarget.hasInt256())) {
27921     assert(Op.getSimpleValueType().isInteger() &&
27922            "Only handle AVX vector integer operation");
27923     return splitVectorIntBinary(Op, DAG);
27924   }
27925 
27926   // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
27927   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27928   EVT SetCCResultType =
27929       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
27930 
27931   unsigned BitWidth = VT.getScalarSizeInBits();
27932   if (Opcode == ISD::USUBSAT) {
27933     if (!TLI.isOperationLegal(ISD::UMAX, VT) || useVPTERNLOG(Subtarget, VT)) {
27934       // Handle a special-case with a bit-hack instead of cmp+select:
27935       // usubsat X, SMIN --> (X ^ SMIN) & (X s>> BW-1)
27936       // If the target can use VPTERNLOG, DAGToDAG will match this as
27937       // "vpsra + vpternlog" which is better than "vpmax + vpsub" with a
27938       // "broadcast" constant load.
27939       ConstantSDNode *C = isConstOrConstSplat(Y, true);
27940       if (C && C->getAPIntValue().isSignMask()) {
27941         SDValue SignMask = DAG.getConstant(C->getAPIntValue(), DL, VT);
27942         SDValue ShiftAmt = DAG.getConstant(BitWidth - 1, DL, VT);
27943         SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, X, SignMask);
27944         SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShiftAmt);
27945         return DAG.getNode(ISD::AND, DL, VT, Xor, Sra);
27946       }
27947     }
27948     if (!TLI.isOperationLegal(ISD::UMAX, VT)) {
27949       // usubsat X, Y --> (X >u Y) ? X - Y : 0
27950       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
27951       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
27952       // TODO: Move this to DAGCombiner?
27953       if (SetCCResultType == VT &&
27954           DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
27955         return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
27956       return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
27957     }
27958   }
27959 
27960   if ((Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) &&
27961       (!VT.isVector() || VT == MVT::v2i64)) {
27962     APInt MinVal = APInt::getSignedMinValue(BitWidth);
27963     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
27964     SDValue Zero = DAG.getConstant(0, DL, VT);
27965     SDValue Result =
27966         DAG.getNode(Opcode == ISD::SADDSAT ? ISD::SADDO : ISD::SSUBO, DL,
27967                     DAG.getVTList(VT, SetCCResultType), X, Y);
27968     SDValue SumDiff = Result.getValue(0);
27969     SDValue Overflow = Result.getValue(1);
27970     SDValue SatMin = DAG.getConstant(MinVal, DL, VT);
27971     SDValue SatMax = DAG.getConstant(MaxVal, DL, VT);
27972     SDValue SumNeg =
27973         DAG.getSetCC(DL, SetCCResultType, SumDiff, Zero, ISD::SETLT);
27974     Result = DAG.getSelect(DL, VT, SumNeg, SatMax, SatMin);
27975     return DAG.getSelect(DL, VT, Overflow, Result, SumDiff);
27976   }
27977 
27978   // Use default expansion.
27979   return SDValue();
27980 }
27981 
LowerABS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27982 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
27983                         SelectionDAG &DAG) {
27984   MVT VT = Op.getSimpleValueType();
27985   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
27986     // Since X86 does not have CMOV for 8-bit integer, we don't convert
27987     // 8-bit integer abs to NEG and CMOV.
27988     SDLoc DL(Op);
27989     SDValue N0 = Op.getOperand(0);
27990     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
27991                               DAG.getConstant(0, DL, VT), N0);
27992     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_NS, DL, MVT::i8),
27993                      SDValue(Neg.getNode(), 1)};
27994     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
27995   }
27996 
27997   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
27998   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
27999     SDLoc DL(Op);
28000     SDValue Src = Op.getOperand(0);
28001     SDValue Sub =
28002         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
28003     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
28004   }
28005 
28006   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
28007     assert(VT.isInteger() &&
28008            "Only handle AVX 256-bit vector integer operation");
28009     return splitVectorIntUnary(Op, DAG);
28010   }
28011 
28012   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28013     return splitVectorIntUnary(Op, DAG);
28014 
28015   // Default to expand.
28016   return SDValue();
28017 }
28018 
LowerAVG(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28019 static SDValue LowerAVG(SDValue Op, const X86Subtarget &Subtarget,
28020                         SelectionDAG &DAG) {
28021   MVT VT = Op.getSimpleValueType();
28022 
28023   // For AVX1 cases, split to use legal ops.
28024   if (VT.is256BitVector() && !Subtarget.hasInt256())
28025     return splitVectorIntBinary(Op, DAG);
28026 
28027   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28028     return splitVectorIntBinary(Op, DAG);
28029 
28030   // Default to expand.
28031   return SDValue();
28032 }
28033 
LowerMINMAX(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28034 static SDValue LowerMINMAX(SDValue Op, const X86Subtarget &Subtarget,
28035                            SelectionDAG &DAG) {
28036   MVT VT = Op.getSimpleValueType();
28037 
28038   // For AVX1 cases, split to use legal ops.
28039   if (VT.is256BitVector() && !Subtarget.hasInt256())
28040     return splitVectorIntBinary(Op, DAG);
28041 
28042   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28043     return splitVectorIntBinary(Op, DAG);
28044 
28045   // Default to expand.
28046   return SDValue();
28047 }
28048 
LowerFMINIMUM_FMAXIMUM(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28049 static SDValue LowerFMINIMUM_FMAXIMUM(SDValue Op, const X86Subtarget &Subtarget,
28050                                       SelectionDAG &DAG) {
28051   assert((Op.getOpcode() == ISD::FMAXIMUM || Op.getOpcode() == ISD::FMINIMUM) &&
28052          "Expected FMAXIMUM or FMINIMUM opcode");
28053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28054   EVT VT = Op.getValueType();
28055   SDValue X = Op.getOperand(0);
28056   SDValue Y = Op.getOperand(1);
28057   SDLoc DL(Op);
28058   uint64_t SizeInBits = VT.getScalarSizeInBits();
28059   APInt PreferredZero = APInt::getZero(SizeInBits);
28060   APInt OppositeZero = PreferredZero;
28061   EVT IVT = VT.changeTypeToInteger();
28062   X86ISD::NodeType MinMaxOp;
28063   if (Op.getOpcode() == ISD::FMAXIMUM) {
28064     MinMaxOp = X86ISD::FMAX;
28065     OppositeZero.setSignBit();
28066   } else {
28067     PreferredZero.setSignBit();
28068     MinMaxOp = X86ISD::FMIN;
28069   }
28070   EVT SetCCType =
28071       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28072 
28073   // The tables below show the expected result of Max in cases of NaN and
28074   // signed zeros.
28075   //
28076   //                 Y                       Y
28077   //             Num   xNaN              +0     -0
28078   //          ---------------         ---------------
28079   //     Num  |  Max |   Y  |     +0  |  +0  |  +0  |
28080   // X        ---------------  X      ---------------
28081   //    xNaN  |   X  |  X/Y |     -0  |  +0  |  -0  |
28082   //          ---------------         ---------------
28083   //
28084   // It is achieved by means of FMAX/FMIN with preliminary checks and operand
28085   // reordering.
28086   //
28087   // We check if any of operands is NaN and return NaN. Then we check if any of
28088   // operands is zero or negative zero (for fmaximum and fminimum respectively)
28089   // to ensure the correct zero is returned.
28090   auto MatchesZero = [](SDValue Op, APInt Zero) {
28091     Op = peekThroughBitcasts(Op);
28092     if (auto *CstOp = dyn_cast<ConstantFPSDNode>(Op))
28093       return CstOp->getValueAPF().bitcastToAPInt() == Zero;
28094     if (auto *CstOp = dyn_cast<ConstantSDNode>(Op))
28095       return CstOp->getAPIntValue() == Zero;
28096     if (Op->getOpcode() == ISD::BUILD_VECTOR ||
28097         Op->getOpcode() == ISD::SPLAT_VECTOR) {
28098       for (const SDValue &OpVal : Op->op_values()) {
28099         if (OpVal.isUndef())
28100           continue;
28101         auto *CstOp = dyn_cast<ConstantFPSDNode>(OpVal);
28102         if (!CstOp)
28103           return false;
28104         if (!CstOp->getValueAPF().isZero())
28105           continue;
28106         if (CstOp->getValueAPF().bitcastToAPInt() != Zero)
28107           return false;
28108       }
28109       return true;
28110     }
28111     return false;
28112   };
28113 
28114   bool IsXNeverNaN = DAG.isKnownNeverNaN(X);
28115   bool IsYNeverNaN = DAG.isKnownNeverNaN(Y);
28116   bool IgnoreSignedZero = DAG.getTarget().Options.NoSignedZerosFPMath ||
28117                           Op->getFlags().hasNoSignedZeros() ||
28118                           DAG.isKnownNeverZeroFloat(X) ||
28119                           DAG.isKnownNeverZeroFloat(Y);
28120   SDValue NewX, NewY;
28121   if (IgnoreSignedZero || MatchesZero(Y, PreferredZero) ||
28122       MatchesZero(X, OppositeZero)) {
28123     // Operands are already in right order or order does not matter.
28124     NewX = X;
28125     NewY = Y;
28126   } else if (MatchesZero(X, PreferredZero) || MatchesZero(Y, OppositeZero)) {
28127     NewX = Y;
28128     NewY = X;
28129   } else if (!VT.isVector() && (VT == MVT::f16 || Subtarget.hasDQI()) &&
28130              (Op->getFlags().hasNoNaNs() || IsXNeverNaN || IsYNeverNaN)) {
28131     if (IsXNeverNaN)
28132       std::swap(X, Y);
28133     // VFPCLASSS consumes a vector type. So provide a minimal one corresponded
28134     // xmm register.
28135     MVT VectorType = MVT::getVectorVT(VT.getSimpleVT(), 128 / SizeInBits);
28136     SDValue VX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorType, X);
28137     // Bits of classes:
28138     // Bits  Imm8[0] Imm8[1] Imm8[2] Imm8[3] Imm8[4]  Imm8[5]  Imm8[6] Imm8[7]
28139     // Class    QNAN PosZero NegZero  PosINF  NegINF Denormal Negative    SNAN
28140     SDValue Imm = DAG.getTargetConstant(MinMaxOp == X86ISD::FMAX ? 0b11 : 0b101,
28141                                         DL, MVT::i32);
28142     SDValue IsNanZero = DAG.getNode(X86ISD::VFPCLASSS, DL, MVT::v1i1, VX, Imm);
28143     SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
28144                               DAG.getConstant(0, DL, MVT::v8i1), IsNanZero,
28145                               DAG.getIntPtrConstant(0, DL));
28146     SDValue NeedSwap = DAG.getBitcast(MVT::i8, Ins);
28147     NewX = DAG.getSelect(DL, VT, NeedSwap, Y, X);
28148     NewY = DAG.getSelect(DL, VT, NeedSwap, X, Y);
28149     return DAG.getNode(MinMaxOp, DL, VT, NewX, NewY, Op->getFlags());
28150   } else {
28151     SDValue IsXSigned;
28152     if (Subtarget.is64Bit() || VT != MVT::f64) {
28153       SDValue XInt = DAG.getNode(ISD::BITCAST, DL, IVT, X);
28154       SDValue ZeroCst = DAG.getConstant(0, DL, IVT);
28155       IsXSigned = DAG.getSetCC(DL, SetCCType, XInt, ZeroCst, ISD::SETLT);
28156     } else {
28157       assert(VT == MVT::f64);
28158       SDValue Ins = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v2f64,
28159                                 DAG.getConstantFP(0, DL, MVT::v2f64), X,
28160                                 DAG.getIntPtrConstant(0, DL));
28161       SDValue VX = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, Ins);
28162       SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VX,
28163                                DAG.getIntPtrConstant(1, DL));
28164       Hi = DAG.getBitcast(MVT::i32, Hi);
28165       SDValue ZeroCst = DAG.getConstant(0, DL, MVT::i32);
28166       EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(),
28167                                              *DAG.getContext(), MVT::i32);
28168       IsXSigned = DAG.getSetCC(DL, SetCCType, Hi, ZeroCst, ISD::SETLT);
28169     }
28170     if (MinMaxOp == X86ISD::FMAX) {
28171       NewX = DAG.getSelect(DL, VT, IsXSigned, X, Y);
28172       NewY = DAG.getSelect(DL, VT, IsXSigned, Y, X);
28173     } else {
28174       NewX = DAG.getSelect(DL, VT, IsXSigned, Y, X);
28175       NewY = DAG.getSelect(DL, VT, IsXSigned, X, Y);
28176     }
28177   }
28178 
28179   bool IgnoreNaN = DAG.getTarget().Options.NoNaNsFPMath ||
28180                    Op->getFlags().hasNoNaNs() || (IsXNeverNaN && IsYNeverNaN);
28181 
28182   // If we did no ordering operands for signed zero handling and we need
28183   // to process NaN and we know that the second operand is not NaN then put
28184   // it in first operand and we will not need to post handle NaN after max/min.
28185   if (IgnoreSignedZero && !IgnoreNaN && DAG.isKnownNeverNaN(NewY))
28186     std::swap(NewX, NewY);
28187 
28188   SDValue MinMax = DAG.getNode(MinMaxOp, DL, VT, NewX, NewY, Op->getFlags());
28189 
28190   if (IgnoreNaN || DAG.isKnownNeverNaN(NewX))
28191     return MinMax;
28192 
28193   SDValue IsNaN = DAG.getSetCC(DL, SetCCType, NewX, NewX, ISD::SETUO);
28194   return DAG.getSelect(DL, VT, IsNaN, NewX, MinMax);
28195 }
28196 
LowerABD(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28197 static SDValue LowerABD(SDValue Op, const X86Subtarget &Subtarget,
28198                         SelectionDAG &DAG) {
28199   MVT VT = Op.getSimpleValueType();
28200 
28201   // For AVX1 cases, split to use legal ops.
28202   if (VT.is256BitVector() && !Subtarget.hasInt256())
28203     return splitVectorIntBinary(Op, DAG);
28204 
28205   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.useBWIRegs())
28206     return splitVectorIntBinary(Op, DAG);
28207 
28208   SDLoc dl(Op);
28209   bool IsSigned = Op.getOpcode() == ISD::ABDS;
28210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28211 
28212   // TODO: Move to TargetLowering expandABD() once we have ABD promotion.
28213   if (VT.isScalarInteger()) {
28214     unsigned WideBits = std::max<unsigned>(2 * VT.getScalarSizeInBits(), 32u);
28215     MVT WideVT = MVT::getIntegerVT(WideBits);
28216     if (TLI.isTypeLegal(WideVT)) {
28217       // abds(lhs, rhs) -> trunc(abs(sub(sext(lhs), sext(rhs))))
28218       // abdu(lhs, rhs) -> trunc(abs(sub(zext(lhs), zext(rhs))))
28219       unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28220       SDValue LHS = DAG.getNode(ExtOpc, dl, WideVT, Op.getOperand(0));
28221       SDValue RHS = DAG.getNode(ExtOpc, dl, WideVT, Op.getOperand(1));
28222       SDValue Diff = DAG.getNode(ISD::SUB, dl, WideVT, LHS, RHS);
28223       SDValue AbsDiff = DAG.getNode(ISD::ABS, dl, WideVT, Diff);
28224       return DAG.getNode(ISD::TRUNCATE, dl, VT, AbsDiff);
28225     }
28226   }
28227 
28228   // TODO: Move to TargetLowering expandABD().
28229   if (!Subtarget.hasSSE41() &&
28230       ((IsSigned && VT == MVT::v16i8) || VT == MVT::v4i32)) {
28231     SDValue LHS = DAG.getFreeze(Op.getOperand(0));
28232     SDValue RHS = DAG.getFreeze(Op.getOperand(1));
28233     ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT;
28234     SDValue Cmp = DAG.getSetCC(dl, VT, LHS, RHS, CC);
28235     SDValue Diff0 = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
28236     SDValue Diff1 = DAG.getNode(ISD::SUB, dl, VT, RHS, LHS);
28237     return getBitSelect(dl, VT, Diff0, Diff1, Cmp, DAG);
28238   }
28239 
28240   // Default to expand.
28241   return SDValue();
28242 }
28243 
LowerMUL(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28244 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
28245                         SelectionDAG &DAG) {
28246   SDLoc dl(Op);
28247   MVT VT = Op.getSimpleValueType();
28248 
28249   // Decompose 256-bit ops into 128-bit ops.
28250   if (VT.is256BitVector() && !Subtarget.hasInt256())
28251     return splitVectorIntBinary(Op, DAG);
28252 
28253   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28254     return splitVectorIntBinary(Op, DAG);
28255 
28256   SDValue A = Op.getOperand(0);
28257   SDValue B = Op.getOperand(1);
28258 
28259   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
28260   // vector pairs, multiply and truncate.
28261   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
28262     unsigned NumElts = VT.getVectorNumElements();
28263 
28264     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28265         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28266       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
28267       return DAG.getNode(
28268           ISD::TRUNCATE, dl, VT,
28269           DAG.getNode(ISD::MUL, dl, ExVT,
28270                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
28271                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
28272     }
28273 
28274     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28275 
28276     // Extract the lo/hi parts to any extend to i16.
28277     // We're going to mask off the low byte of each result element of the
28278     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
28279     // element.
28280     SDValue Undef = DAG.getUNDEF(VT);
28281     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
28282     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
28283 
28284     SDValue BLo, BHi;
28285     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
28286       // If the RHS is a constant, manually unpackl/unpackh.
28287       SmallVector<SDValue, 16> LoOps, HiOps;
28288       for (unsigned i = 0; i != NumElts; i += 16) {
28289         for (unsigned j = 0; j != 8; ++j) {
28290           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
28291                                                MVT::i16));
28292           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
28293                                                MVT::i16));
28294         }
28295       }
28296 
28297       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
28298       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
28299     } else {
28300       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
28301       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
28302     }
28303 
28304     // Multiply, mask the lower 8bits of the lo/hi results and pack.
28305     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
28306     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
28307     return getPack(DAG, Subtarget, dl, VT, RLo, RHi);
28308   }
28309 
28310   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
28311   if (VT == MVT::v4i32) {
28312     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
28313            "Should not custom lower when pmulld is available!");
28314 
28315     // Extract the odd parts.
28316     static const int UnpackMask[] = { 1, -1, 3, -1 };
28317     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
28318     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
28319 
28320     // Multiply the even parts.
28321     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
28322                                 DAG.getBitcast(MVT::v2i64, A),
28323                                 DAG.getBitcast(MVT::v2i64, B));
28324     // Now multiply odd parts.
28325     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
28326                                DAG.getBitcast(MVT::v2i64, Aodds),
28327                                DAG.getBitcast(MVT::v2i64, Bodds));
28328 
28329     Evens = DAG.getBitcast(VT, Evens);
28330     Odds = DAG.getBitcast(VT, Odds);
28331 
28332     // Merge the two vectors back together with a shuffle. This expands into 2
28333     // shuffles.
28334     static const int ShufMask[] = { 0, 4, 2, 6 };
28335     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
28336   }
28337 
28338   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
28339          "Only know how to lower V2I64/V4I64/V8I64 multiply");
28340   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
28341 
28342   //  Ahi = psrlqi(a, 32);
28343   //  Bhi = psrlqi(b, 32);
28344   //
28345   //  AloBlo = pmuludq(a, b);
28346   //  AloBhi = pmuludq(a, Bhi);
28347   //  AhiBlo = pmuludq(Ahi, b);
28348   //
28349   //  Hi = psllqi(AloBhi + AhiBlo, 32);
28350   //  return AloBlo + Hi;
28351   KnownBits AKnown = DAG.computeKnownBits(A);
28352   KnownBits BKnown = DAG.computeKnownBits(B);
28353 
28354   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
28355   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
28356   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
28357 
28358   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
28359   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
28360   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
28361 
28362   SDValue Zero = DAG.getConstant(0, dl, VT);
28363 
28364   // Only multiply lo/hi halves that aren't known to be zero.
28365   SDValue AloBlo = Zero;
28366   if (!ALoIsZero && !BLoIsZero)
28367     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
28368 
28369   SDValue AloBhi = Zero;
28370   if (!ALoIsZero && !BHiIsZero) {
28371     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
28372     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
28373   }
28374 
28375   SDValue AhiBlo = Zero;
28376   if (!AHiIsZero && !BLoIsZero) {
28377     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
28378     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
28379   }
28380 
28381   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
28382   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
28383 
28384   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
28385 }
28386 
LowervXi8MulWithUNPCK(SDValue A,SDValue B,const SDLoc & dl,MVT VT,bool IsSigned,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue * Low=nullptr)28387 static SDValue LowervXi8MulWithUNPCK(SDValue A, SDValue B, const SDLoc &dl,
28388                                      MVT VT, bool IsSigned,
28389                                      const X86Subtarget &Subtarget,
28390                                      SelectionDAG &DAG,
28391                                      SDValue *Low = nullptr) {
28392   unsigned NumElts = VT.getVectorNumElements();
28393 
28394   // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
28395   // to a vXi16 type. Do the multiplies, shift the results and pack the half
28396   // lane results back together.
28397 
28398   // We'll take different approaches for signed and unsigned.
28399   // For unsigned we'll use punpcklbw/punpckhbw to put zero extend the bytes
28400   // and use pmullw to calculate the full 16-bit product.
28401   // For signed we'll use punpcklbw/punpckbw to extend the bytes to words and
28402   // shift them left into the upper byte of each word. This allows us to use
28403   // pmulhw to calculate the full 16-bit product. This trick means we don't
28404   // need to sign extend the bytes to use pmullw.
28405 
28406   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28407   SDValue Zero = DAG.getConstant(0, dl, VT);
28408 
28409   SDValue ALo, AHi;
28410   if (IsSigned) {
28411     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, A));
28412     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, A));
28413   } else {
28414     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Zero));
28415     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Zero));
28416   }
28417 
28418   SDValue BLo, BHi;
28419   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
28420     // If the RHS is a constant, manually unpackl/unpackh and extend.
28421     SmallVector<SDValue, 16> LoOps, HiOps;
28422     for (unsigned i = 0; i != NumElts; i += 16) {
28423       for (unsigned j = 0; j != 8; ++j) {
28424         SDValue LoOp = B.getOperand(i + j);
28425         SDValue HiOp = B.getOperand(i + j + 8);
28426 
28427         if (IsSigned) {
28428           LoOp = DAG.getAnyExtOrTrunc(LoOp, dl, MVT::i16);
28429           HiOp = DAG.getAnyExtOrTrunc(HiOp, dl, MVT::i16);
28430           LoOp = DAG.getNode(ISD::SHL, dl, MVT::i16, LoOp,
28431                              DAG.getConstant(8, dl, MVT::i16));
28432           HiOp = DAG.getNode(ISD::SHL, dl, MVT::i16, HiOp,
28433                              DAG.getConstant(8, dl, MVT::i16));
28434         } else {
28435           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
28436           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
28437         }
28438 
28439         LoOps.push_back(LoOp);
28440         HiOps.push_back(HiOp);
28441       }
28442     }
28443 
28444     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
28445     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
28446   } else if (IsSigned) {
28447     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, Zero, B));
28448     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, Zero, B));
28449   } else {
28450     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Zero));
28451     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Zero));
28452   }
28453 
28454   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
28455   // pack back to vXi8.
28456   unsigned MulOpc = IsSigned ? ISD::MULHS : ISD::MUL;
28457   SDValue RLo = DAG.getNode(MulOpc, dl, ExVT, ALo, BLo);
28458   SDValue RHi = DAG.getNode(MulOpc, dl, ExVT, AHi, BHi);
28459 
28460   if (Low)
28461     *Low = getPack(DAG, Subtarget, dl, VT, RLo, RHi);
28462 
28463   return getPack(DAG, Subtarget, dl, VT, RLo, RHi, /*PackHiHalf*/ true);
28464 }
28465 
LowerMULH(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28466 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
28467                          SelectionDAG &DAG) {
28468   SDLoc dl(Op);
28469   MVT VT = Op.getSimpleValueType();
28470   bool IsSigned = Op->getOpcode() == ISD::MULHS;
28471   unsigned NumElts = VT.getVectorNumElements();
28472   SDValue A = Op.getOperand(0);
28473   SDValue B = Op.getOperand(1);
28474 
28475   // Decompose 256-bit ops into 128-bit ops.
28476   if (VT.is256BitVector() && !Subtarget.hasInt256())
28477     return splitVectorIntBinary(Op, DAG);
28478 
28479   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
28480     return splitVectorIntBinary(Op, DAG);
28481 
28482   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
28483     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
28484            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
28485            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
28486 
28487     // PMULxD operations multiply each even value (starting at 0) of LHS with
28488     // the related value of RHS and produce a widen result.
28489     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
28490     // => <2 x i64> <ae|cg>
28491     //
28492     // In other word, to have all the results, we need to perform two PMULxD:
28493     // 1. one with the even values.
28494     // 2. one with the odd values.
28495     // To achieve #2, with need to place the odd values at an even position.
28496     //
28497     // Place the odd value at an even position (basically, shift all values 1
28498     // step to the left):
28499     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
28500                         9, -1, 11, -1, 13, -1, 15, -1};
28501     // <a|b|c|d> => <b|undef|d|undef>
28502     SDValue Odd0 =
28503         DAG.getVectorShuffle(VT, dl, A, A, ArrayRef(&Mask[0], NumElts));
28504     // <e|f|g|h> => <f|undef|h|undef>
28505     SDValue Odd1 =
28506         DAG.getVectorShuffle(VT, dl, B, B, ArrayRef(&Mask[0], NumElts));
28507 
28508     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
28509     // ints.
28510     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
28511     unsigned Opcode =
28512         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
28513     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
28514     // => <2 x i64> <ae|cg>
28515     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
28516                                                   DAG.getBitcast(MulVT, A),
28517                                                   DAG.getBitcast(MulVT, B)));
28518     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
28519     // => <2 x i64> <bf|dh>
28520     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
28521                                                   DAG.getBitcast(MulVT, Odd0),
28522                                                   DAG.getBitcast(MulVT, Odd1)));
28523 
28524     // Shuffle it back into the right order.
28525     SmallVector<int, 16> ShufMask(NumElts);
28526     for (int i = 0; i != (int)NumElts; ++i)
28527       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
28528 
28529     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
28530 
28531     // If we have a signed multiply but no PMULDQ fix up the result of an
28532     // unsigned multiply.
28533     if (IsSigned && !Subtarget.hasSSE41()) {
28534       SDValue Zero = DAG.getConstant(0, dl, VT);
28535       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
28536                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
28537       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
28538                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
28539 
28540       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
28541       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
28542     }
28543 
28544     return Res;
28545   }
28546 
28547   // Only i8 vectors should need custom lowering after this.
28548   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
28549          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
28550          "Unsupported vector type");
28551 
28552   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
28553   // logical shift down the upper half and pack back to i8.
28554 
28555   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
28556   // and then ashr/lshr the upper bits down to the lower bits before multiply.
28557 
28558   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28559       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28560     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
28561     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28562     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
28563     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
28564     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
28565     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28566     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
28567   }
28568 
28569   return LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG);
28570 }
28571 
28572 // Custom lowering for SMULO/UMULO.
LowerMULO(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28573 static SDValue LowerMULO(SDValue Op, const X86Subtarget &Subtarget,
28574                          SelectionDAG &DAG) {
28575   MVT VT = Op.getSimpleValueType();
28576 
28577   // Scalars defer to LowerXALUO.
28578   if (!VT.isVector())
28579     return LowerXALUO(Op, DAG);
28580 
28581   SDLoc dl(Op);
28582   bool IsSigned = Op->getOpcode() == ISD::SMULO;
28583   SDValue A = Op.getOperand(0);
28584   SDValue B = Op.getOperand(1);
28585   EVT OvfVT = Op->getValueType(1);
28586 
28587   if ((VT == MVT::v32i8 && !Subtarget.hasInt256()) ||
28588       (VT == MVT::v64i8 && !Subtarget.hasBWI())) {
28589     // Extract the LHS Lo/Hi vectors
28590     SDValue LHSLo, LHSHi;
28591     std::tie(LHSLo, LHSHi) = splitVector(A, DAG, dl);
28592 
28593     // Extract the RHS Lo/Hi vectors
28594     SDValue RHSLo, RHSHi;
28595     std::tie(RHSLo, RHSHi) = splitVector(B, DAG, dl);
28596 
28597     EVT LoOvfVT, HiOvfVT;
28598     std::tie(LoOvfVT, HiOvfVT) = DAG.GetSplitDestVTs(OvfVT);
28599     SDVTList LoVTs = DAG.getVTList(LHSLo.getValueType(), LoOvfVT);
28600     SDVTList HiVTs = DAG.getVTList(LHSHi.getValueType(), HiOvfVT);
28601 
28602     // Issue the split operations.
28603     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, LoVTs, LHSLo, RHSLo);
28604     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, HiVTs, LHSHi, RHSHi);
28605 
28606     // Join the separate data results and the overflow results.
28607     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
28608     SDValue Ovf = DAG.getNode(ISD::CONCAT_VECTORS, dl, OvfVT, Lo.getValue(1),
28609                               Hi.getValue(1));
28610 
28611     return DAG.getMergeValues({Res, Ovf}, dl);
28612   }
28613 
28614   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28615   EVT SetccVT =
28616       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
28617 
28618   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
28619       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
28620     unsigned NumElts = VT.getVectorNumElements();
28621     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
28622     unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28623     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
28624     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
28625     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
28626 
28627     SDValue Low = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
28628 
28629     SDValue Ovf;
28630     if (IsSigned) {
28631       SDValue High, LowSign;
28632       if (OvfVT.getVectorElementType() == MVT::i1 &&
28633           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
28634         // Rather the truncating try to do the compare on vXi16 or vXi32.
28635         // Shift the high down filling with sign bits.
28636         High = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Mul, 8, DAG);
28637         // Fill all 16 bits with the sign bit from the low.
28638         LowSign =
28639             getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExVT, Mul, 8, DAG);
28640         LowSign = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, LowSign,
28641                                              15, DAG);
28642         SetccVT = OvfVT;
28643         if (!Subtarget.hasBWI()) {
28644           // We can't do a vXi16 compare so sign extend to v16i32.
28645           High = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, High);
28646           LowSign = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v16i32, LowSign);
28647         }
28648       } else {
28649         // Otherwise do the compare at vXi8.
28650         High = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28651         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
28652         LowSign =
28653             DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
28654       }
28655 
28656       Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
28657     } else {
28658       SDValue High =
28659           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
28660       if (OvfVT.getVectorElementType() == MVT::i1 &&
28661           (Subtarget.hasBWI() || Subtarget.canExtendTo512DQ())) {
28662         // Rather the truncating try to do the compare on vXi16 or vXi32.
28663         SetccVT = OvfVT;
28664         if (!Subtarget.hasBWI()) {
28665           // We can't do a vXi16 compare so sign extend to v16i32.
28666           High = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, High);
28667         }
28668       } else {
28669         // Otherwise do the compare at vXi8.
28670         High = DAG.getNode(ISD::TRUNCATE, dl, VT, High);
28671       }
28672 
28673       Ovf =
28674           DAG.getSetCC(dl, SetccVT, High,
28675                        DAG.getConstant(0, dl, High.getValueType()), ISD::SETNE);
28676     }
28677 
28678     Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
28679 
28680     return DAG.getMergeValues({Low, Ovf}, dl);
28681   }
28682 
28683   SDValue Low;
28684   SDValue High =
28685       LowervXi8MulWithUNPCK(A, B, dl, VT, IsSigned, Subtarget, DAG, &Low);
28686 
28687   SDValue Ovf;
28688   if (IsSigned) {
28689     // SMULO overflows if the high bits don't match the sign of the low.
28690     SDValue LowSign =
28691         DAG.getNode(ISD::SRA, dl, VT, Low, DAG.getConstant(7, dl, VT));
28692     Ovf = DAG.getSetCC(dl, SetccVT, LowSign, High, ISD::SETNE);
28693   } else {
28694     // UMULO overflows if the high bits are non-zero.
28695     Ovf =
28696         DAG.getSetCC(dl, SetccVT, High, DAG.getConstant(0, dl, VT), ISD::SETNE);
28697   }
28698 
28699   Ovf = DAG.getSExtOrTrunc(Ovf, dl, OvfVT);
28700 
28701   return DAG.getMergeValues({Low, Ovf}, dl);
28702 }
28703 
LowerWin64_i128OP(SDValue Op,SelectionDAG & DAG) const28704 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
28705   assert(Subtarget.isTargetWin64() && "Unexpected target");
28706   EVT VT = Op.getValueType();
28707   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
28708          "Unexpected return type for lowering");
28709 
28710   if (isa<ConstantSDNode>(Op->getOperand(1))) {
28711     SmallVector<SDValue> Result;
28712     if (expandDIVREMByConstant(Op.getNode(), Result, MVT::i64, DAG))
28713       return DAG.getNode(ISD::BUILD_PAIR, SDLoc(Op), VT, Result[0], Result[1]);
28714   }
28715 
28716   RTLIB::Libcall LC;
28717   bool isSigned;
28718   switch (Op->getOpcode()) {
28719   default: llvm_unreachable("Unexpected request for libcall!");
28720   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
28721   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
28722   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
28723   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
28724   }
28725 
28726   SDLoc dl(Op);
28727   SDValue InChain = DAG.getEntryNode();
28728 
28729   TargetLowering::ArgListTy Args;
28730   TargetLowering::ArgListEntry Entry;
28731   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
28732     EVT ArgVT = Op->getOperand(i).getValueType();
28733     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
28734            "Unexpected argument type for lowering");
28735     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
28736     int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
28737     MachinePointerInfo MPI =
28738         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
28739     Entry.Node = StackPtr;
28740     InChain =
28741         DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
28742     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
28743     Entry.Ty = PointerType::get(ArgTy,0);
28744     Entry.IsSExt = false;
28745     Entry.IsZExt = false;
28746     Args.push_back(Entry);
28747   }
28748 
28749   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
28750                                          getPointerTy(DAG.getDataLayout()));
28751 
28752   TargetLowering::CallLoweringInfo CLI(DAG);
28753   CLI.setDebugLoc(dl)
28754       .setChain(InChain)
28755       .setLibCallee(
28756           getLibcallCallingConv(LC),
28757           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
28758           std::move(Args))
28759       .setInRegister()
28760       .setSExtResult(isSigned)
28761       .setZExtResult(!isSigned);
28762 
28763   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
28764   return DAG.getBitcast(VT, CallInfo.first);
28765 }
28766 
LowerWin64_FP_TO_INT128(SDValue Op,SelectionDAG & DAG,SDValue & Chain) const28767 SDValue X86TargetLowering::LowerWin64_FP_TO_INT128(SDValue Op,
28768                                                    SelectionDAG &DAG,
28769                                                    SDValue &Chain) const {
28770   assert(Subtarget.isTargetWin64() && "Unexpected target");
28771   EVT VT = Op.getValueType();
28772   bool IsStrict = Op->isStrictFPOpcode();
28773 
28774   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
28775   EVT ArgVT = Arg.getValueType();
28776 
28777   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
28778          "Unexpected return type for lowering");
28779 
28780   RTLIB::Libcall LC;
28781   if (Op->getOpcode() == ISD::FP_TO_SINT ||
28782       Op->getOpcode() == ISD::STRICT_FP_TO_SINT)
28783     LC = RTLIB::getFPTOSINT(ArgVT, VT);
28784   else
28785     LC = RTLIB::getFPTOUINT(ArgVT, VT);
28786   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
28787 
28788   SDLoc dl(Op);
28789   MakeLibCallOptions CallOptions;
28790   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
28791 
28792   SDValue Result;
28793   // Expect the i128 argument returned as a v2i64 in xmm0, cast back to the
28794   // expected VT (i128).
28795   std::tie(Result, Chain) =
28796       makeLibCall(DAG, LC, MVT::v2i64, Arg, CallOptions, dl, Chain);
28797   Result = DAG.getBitcast(VT, Result);
28798   return Result;
28799 }
28800 
LowerWin64_INT128_TO_FP(SDValue Op,SelectionDAG & DAG) const28801 SDValue X86TargetLowering::LowerWin64_INT128_TO_FP(SDValue Op,
28802                                                    SelectionDAG &DAG) const {
28803   assert(Subtarget.isTargetWin64() && "Unexpected target");
28804   EVT VT = Op.getValueType();
28805   bool IsStrict = Op->isStrictFPOpcode();
28806 
28807   SDValue Arg = Op.getOperand(IsStrict ? 1 : 0);
28808   EVT ArgVT = Arg.getValueType();
28809 
28810   assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
28811          "Unexpected argument type for lowering");
28812 
28813   RTLIB::Libcall LC;
28814   if (Op->getOpcode() == ISD::SINT_TO_FP ||
28815       Op->getOpcode() == ISD::STRICT_SINT_TO_FP)
28816     LC = RTLIB::getSINTTOFP(ArgVT, VT);
28817   else
28818     LC = RTLIB::getUINTTOFP(ArgVT, VT);
28819   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
28820 
28821   SDLoc dl(Op);
28822   MakeLibCallOptions CallOptions;
28823   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
28824 
28825   // Pass the i128 argument as an indirect argument on the stack.
28826   SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
28827   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
28828   MachinePointerInfo MPI =
28829       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
28830   Chain = DAG.getStore(Chain, dl, Arg, StackPtr, MPI, Align(16));
28831 
28832   SDValue Result;
28833   std::tie(Result, Chain) =
28834       makeLibCall(DAG, LC, VT, StackPtr, CallOptions, dl, Chain);
28835   return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result;
28836 }
28837 
28838 // Return true if the required (according to Opcode) shift-imm form is natively
28839 // supported by the Subtarget
supportedVectorShiftWithImm(EVT VT,const X86Subtarget & Subtarget,unsigned Opcode)28840 static bool supportedVectorShiftWithImm(EVT VT, const X86Subtarget &Subtarget,
28841                                         unsigned Opcode) {
28842   if (!VT.isSimple())
28843     return false;
28844 
28845   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
28846     return false;
28847 
28848   if (VT.getScalarSizeInBits() < 16)
28849     return false;
28850 
28851   if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
28852       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
28853     return true;
28854 
28855   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
28856                 (VT.is256BitVector() && Subtarget.hasInt256());
28857 
28858   bool AShift = LShift && (Subtarget.hasAVX512() ||
28859                            (VT != MVT::v2i64 && VT != MVT::v4i64));
28860   return (Opcode == ISD::SRA) ? AShift : LShift;
28861 }
28862 
28863 // The shift amount is a variable, but it is the same for all vector lanes.
28864 // These instructions are defined together with shift-immediate.
28865 static
supportedVectorShiftWithBaseAmnt(EVT VT,const X86Subtarget & Subtarget,unsigned Opcode)28866 bool supportedVectorShiftWithBaseAmnt(EVT VT, const X86Subtarget &Subtarget,
28867                                       unsigned Opcode) {
28868   return supportedVectorShiftWithImm(VT, Subtarget, Opcode);
28869 }
28870 
28871 // Return true if the required (according to Opcode) variable-shift form is
28872 // natively supported by the Subtarget
supportedVectorVarShift(EVT VT,const X86Subtarget & Subtarget,unsigned Opcode)28873 static bool supportedVectorVarShift(EVT VT, const X86Subtarget &Subtarget,
28874                                     unsigned Opcode) {
28875   if (!VT.isSimple())
28876     return false;
28877 
28878   if (!(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))
28879     return false;
28880 
28881   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
28882     return false;
28883 
28884   // vXi16 supported only on AVX-512, BWI
28885   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
28886     return false;
28887 
28888   if (Subtarget.hasAVX512() &&
28889       (Subtarget.useAVX512Regs() || !VT.is512BitVector()))
28890     return true;
28891 
28892   bool LShift = VT.is128BitVector() || VT.is256BitVector();
28893   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
28894   return (Opcode == ISD::SRA) ? AShift : LShift;
28895 }
28896 
LowerShiftByScalarImmediate(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)28897 static SDValue LowerShiftByScalarImmediate(SDValue Op, SelectionDAG &DAG,
28898                                            const X86Subtarget &Subtarget) {
28899   MVT VT = Op.getSimpleValueType();
28900   SDLoc dl(Op);
28901   SDValue R = Op.getOperand(0);
28902   SDValue Amt = Op.getOperand(1);
28903   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
28904 
28905   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
28906     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
28907     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
28908     SDValue Ex = DAG.getBitcast(ExVT, R);
28909 
28910     // ashr(R, 63) === cmp_slt(R, 0)
28911     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
28912       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
28913              "Unsupported PCMPGT op");
28914       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
28915     }
28916 
28917     if (ShiftAmt >= 32) {
28918       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
28919       SDValue Upper =
28920           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
28921       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
28922                                                  ShiftAmt - 32, DAG);
28923       if (VT == MVT::v2i64)
28924         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
28925       if (VT == MVT::v4i64)
28926         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
28927                                   {9, 1, 11, 3, 13, 5, 15, 7});
28928     } else {
28929       // SRA upper i32, SRL whole i64 and select lower i32.
28930       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
28931                                                  ShiftAmt, DAG);
28932       SDValue Lower =
28933           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
28934       Lower = DAG.getBitcast(ExVT, Lower);
28935       if (VT == MVT::v2i64)
28936         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
28937       if (VT == MVT::v4i64)
28938         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
28939                                   {8, 1, 10, 3, 12, 5, 14, 7});
28940     }
28941     return DAG.getBitcast(VT, Ex);
28942   };
28943 
28944   // Optimize shl/srl/sra with constant shift amount.
28945   APInt APIntShiftAmt;
28946   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
28947     return SDValue();
28948 
28949   // If the shift amount is out of range, return undef.
28950   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
28951     return DAG.getUNDEF(VT);
28952 
28953   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
28954 
28955   if (supportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode())) {
28956     // Hardware support for vector shifts is sparse which makes us scalarize the
28957     // vector operations in many cases. Also, on sandybridge ADD is faster than
28958     // shl: (shl V, 1) -> (add (freeze V), (freeze V))
28959     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
28960       // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
28961       // must be 0). (add undef, undef) however can be any value. To make this
28962       // safe, we must freeze R to ensure that register allocation uses the same
28963       // register for an undefined value. This ensures that the result will
28964       // still be even and preserves the original semantics.
28965       R = DAG.getFreeze(R);
28966       return DAG.getNode(ISD::ADD, dl, VT, R, R);
28967     }
28968 
28969     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
28970   }
28971 
28972   // i64 SRA needs to be performed as partial shifts.
28973   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
28974        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
28975       Op.getOpcode() == ISD::SRA)
28976     return ArithmeticShiftRight64(ShiftAmt);
28977 
28978   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
28979       (Subtarget.hasBWI() && VT == MVT::v64i8)) {
28980     unsigned NumElts = VT.getVectorNumElements();
28981     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28982 
28983     // Simple i8 add case
28984     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1) {
28985       // R may be undef at run-time, but (shl R, 1) must be an even number (LSB
28986       // must be 0). (add undef, undef) however can be any value. To make this
28987       // safe, we must freeze R to ensure that register allocation uses the same
28988       // register for an undefined value. This ensures that the result will
28989       // still be even and preserves the original semantics.
28990       R = DAG.getFreeze(R);
28991       return DAG.getNode(ISD::ADD, dl, VT, R, R);
28992     }
28993 
28994     // ashr(R, 7)  === cmp_slt(R, 0)
28995     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
28996       SDValue Zeros = DAG.getConstant(0, dl, VT);
28997       if (VT.is512BitVector()) {
28998         assert(VT == MVT::v64i8 && "Unexpected element type!");
28999         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
29000         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
29001       }
29002       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
29003     }
29004 
29005     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
29006     if (VT == MVT::v16i8 && Subtarget.hasXOP())
29007       return SDValue();
29008 
29009     if (Op.getOpcode() == ISD::SHL) {
29010       // Make a large shift.
29011       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
29012                                                ShiftAmt, DAG);
29013       SHL = DAG.getBitcast(VT, SHL);
29014       // Zero out the rightmost bits.
29015       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
29016       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
29017     }
29018     if (Op.getOpcode() == ISD::SRL) {
29019       // Make a large shift.
29020       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
29021                                                ShiftAmt, DAG);
29022       SRL = DAG.getBitcast(VT, SRL);
29023       // Zero out the leftmost bits.
29024       APInt Mask = APInt::getLowBitsSet(8, 8 - ShiftAmt);
29025       return DAG.getNode(ISD::AND, dl, VT, SRL, DAG.getConstant(Mask, dl, VT));
29026     }
29027     if (Op.getOpcode() == ISD::SRA) {
29028       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
29029       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29030 
29031       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
29032       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
29033       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
29034       return Res;
29035     }
29036     llvm_unreachable("Unknown shift opcode.");
29037   }
29038 
29039   return SDValue();
29040 }
29041 
LowerShiftByScalarVariable(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)29042 static SDValue LowerShiftByScalarVariable(SDValue Op, SelectionDAG &DAG,
29043                                           const X86Subtarget &Subtarget) {
29044   MVT VT = Op.getSimpleValueType();
29045   SDLoc dl(Op);
29046   SDValue R = Op.getOperand(0);
29047   SDValue Amt = Op.getOperand(1);
29048   unsigned Opcode = Op.getOpcode();
29049   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
29050 
29051   int BaseShAmtIdx = -1;
29052   if (SDValue BaseShAmt = DAG.getSplatSourceVector(Amt, BaseShAmtIdx)) {
29053     if (supportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode))
29054       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, BaseShAmtIdx,
29055                                  Subtarget, DAG);
29056 
29057     // vXi8 shifts - shift as v8i16 + mask result.
29058     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
29059          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
29060          VT == MVT::v64i8) &&
29061         !Subtarget.hasXOP()) {
29062       unsigned NumElts = VT.getVectorNumElements();
29063       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
29064       if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
29065         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
29066         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
29067 
29068         // Create the mask using vXi16 shifts. For shift-rights we need to move
29069         // the upper byte down before splatting the vXi8 mask.
29070         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
29071         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
29072                                       BaseShAmt, BaseShAmtIdx, Subtarget, DAG);
29073         if (Opcode != ISD::SHL)
29074           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
29075                                                8, DAG);
29076         BitMask = DAG.getBitcast(VT, BitMask);
29077         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
29078                                        SmallVector<int, 64>(NumElts, 0));
29079 
29080         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
29081                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
29082                                           BaseShAmtIdx, Subtarget, DAG);
29083         Res = DAG.getBitcast(VT, Res);
29084         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
29085 
29086         if (Opcode == ISD::SRA) {
29087           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
29088           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
29089           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
29090           SignMask =
29091               getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask, BaseShAmt,
29092                                   BaseShAmtIdx, Subtarget, DAG);
29093           SignMask = DAG.getBitcast(VT, SignMask);
29094           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
29095           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
29096         }
29097         return Res;
29098       }
29099     }
29100   }
29101 
29102   return SDValue();
29103 }
29104 
29105 // Convert a shift/rotate left amount to a multiplication scale factor.
convertShiftLeftToScale(SDValue Amt,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)29106 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
29107                                        const X86Subtarget &Subtarget,
29108                                        SelectionDAG &DAG) {
29109   MVT VT = Amt.getSimpleValueType();
29110   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
29111         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
29112         (Subtarget.hasAVX512() && VT == MVT::v32i16) ||
29113         (!Subtarget.hasAVX512() && VT == MVT::v16i8) ||
29114         (Subtarget.hasInt256() && VT == MVT::v32i8) ||
29115         (Subtarget.hasBWI() && VT == MVT::v64i8)))
29116     return SDValue();
29117 
29118   MVT SVT = VT.getVectorElementType();
29119   unsigned SVTBits = SVT.getSizeInBits();
29120   unsigned NumElems = VT.getVectorNumElements();
29121 
29122   APInt UndefElts;
29123   SmallVector<APInt> EltBits;
29124   if (getTargetConstantBitsFromNode(Amt, SVTBits, UndefElts, EltBits)) {
29125     APInt One(SVTBits, 1);
29126     SmallVector<SDValue> Elts(NumElems, DAG.getUNDEF(SVT));
29127     for (unsigned I = 0; I != NumElems; ++I) {
29128       if (UndefElts[I] || EltBits[I].uge(SVTBits))
29129         continue;
29130       uint64_t ShAmt = EltBits[I].getZExtValue();
29131       Elts[I] = DAG.getConstant(One.shl(ShAmt), dl, SVT);
29132     }
29133     return DAG.getBuildVector(VT, dl, Elts);
29134   }
29135 
29136   // If the target doesn't support variable shifts, use either FP conversion
29137   // or integer multiplication to avoid shifting each element individually.
29138   if (VT == MVT::v4i32) {
29139     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
29140     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
29141                       DAG.getConstant(0x3f800000U, dl, VT));
29142     Amt = DAG.getBitcast(MVT::v4f32, Amt);
29143     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
29144   }
29145 
29146   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
29147   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
29148     SDValue Z = DAG.getConstant(0, dl, VT);
29149     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
29150     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
29151     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
29152     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
29153     if (Subtarget.hasSSE41())
29154       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
29155     return getPack(DAG, Subtarget, dl, VT, Lo, Hi);
29156   }
29157 
29158   return SDValue();
29159 }
29160 
LowerShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)29161 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
29162                           SelectionDAG &DAG) {
29163   MVT VT = Op.getSimpleValueType();
29164   SDLoc dl(Op);
29165   SDValue R = Op.getOperand(0);
29166   SDValue Amt = Op.getOperand(1);
29167   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29168   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29169 
29170   unsigned Opc = Op.getOpcode();
29171   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
29172   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
29173 
29174   assert(VT.isVector() && "Custom lowering only for vector shifts!");
29175   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
29176 
29177   if (SDValue V = LowerShiftByScalarImmediate(Op, DAG, Subtarget))
29178     return V;
29179 
29180   if (SDValue V = LowerShiftByScalarVariable(Op, DAG, Subtarget))
29181     return V;
29182 
29183   if (supportedVectorVarShift(VT, Subtarget, Opc))
29184     return Op;
29185 
29186   // i64 vector arithmetic shift can be emulated with the transform:
29187   // M = lshr(SIGN_MASK, Amt)
29188   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
29189   if (((VT == MVT::v2i64 && !Subtarget.hasXOP()) ||
29190        (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
29191       Opc == ISD::SRA) {
29192     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
29193     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
29194     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
29195     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
29196     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
29197     return R;
29198   }
29199 
29200   // XOP has 128-bit variable logical/arithmetic shifts.
29201   // +ve/-ve Amt = shift left/right.
29202   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
29203                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
29204     if (Opc == ISD::SRL || Opc == ISD::SRA) {
29205       SDValue Zero = DAG.getConstant(0, dl, VT);
29206       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
29207     }
29208     if (Opc == ISD::SHL || Opc == ISD::SRL)
29209       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
29210     if (Opc == ISD::SRA)
29211       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
29212   }
29213 
29214   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
29215   // shifts per-lane and then shuffle the partial results back together.
29216   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
29217     // Splat the shift amounts so the scalar shifts above will catch it.
29218     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
29219     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
29220     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
29221     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
29222     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
29223   }
29224 
29225   // If possible, lower this shift as a sequence of two shifts by
29226   // constant plus a BLENDing shuffle instead of scalarizing it.
29227   // Example:
29228   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
29229   //
29230   // Could be rewritten as:
29231   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
29232   //
29233   // The advantage is that the two shifts from the example would be
29234   // lowered as X86ISD::VSRLI nodes in parallel before blending.
29235   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
29236                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
29237     SDValue Amt1, Amt2;
29238     unsigned NumElts = VT.getVectorNumElements();
29239     SmallVector<int, 8> ShuffleMask;
29240     for (unsigned i = 0; i != NumElts; ++i) {
29241       SDValue A = Amt->getOperand(i);
29242       if (A.isUndef()) {
29243         ShuffleMask.push_back(SM_SentinelUndef);
29244         continue;
29245       }
29246       if (!Amt1 || Amt1 == A) {
29247         ShuffleMask.push_back(i);
29248         Amt1 = A;
29249         continue;
29250       }
29251       if (!Amt2 || Amt2 == A) {
29252         ShuffleMask.push_back(i + NumElts);
29253         Amt2 = A;
29254         continue;
29255       }
29256       break;
29257     }
29258 
29259     // Only perform this blend if we can perform it without loading a mask.
29260     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
29261         (VT != MVT::v16i16 ||
29262          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
29263         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
29264          canWidenShuffleElements(ShuffleMask))) {
29265       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
29266       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
29267       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
29268           Cst2->getAPIntValue().ult(EltSizeInBits)) {
29269         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
29270                                                     Cst1->getZExtValue(), DAG);
29271         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
29272                                                     Cst2->getZExtValue(), DAG);
29273         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
29274       }
29275     }
29276   }
29277 
29278   // If possible, lower this packed shift into a vector multiply instead of
29279   // expanding it into a sequence of scalar shifts.
29280   // For v32i8 cases, it might be quicker to split/extend to vXi16 shifts.
29281   if (Opc == ISD::SHL && !(VT == MVT::v32i8 && (Subtarget.hasXOP() ||
29282                                                 Subtarget.canExtendTo512BW())))
29283     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
29284       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
29285 
29286   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
29287   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
29288   if (Opc == ISD::SRL && ConstantAmt &&
29289       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
29290     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
29291     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
29292     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
29293       SDValue Zero = DAG.getConstant(0, dl, VT);
29294       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
29295       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
29296       return DAG.getSelect(dl, VT, ZAmt, R, Res);
29297     }
29298   }
29299 
29300   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
29301   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
29302   // TODO: Special case handling for shift by 0/1, really we can afford either
29303   // of these cases in pre-SSE41/XOP/AVX512 but not both.
29304   if (Opc == ISD::SRA && ConstantAmt &&
29305       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
29306       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
29307         !Subtarget.hasAVX512()) ||
29308        DAG.isKnownNeverZero(Amt))) {
29309     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
29310     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
29311     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
29312       SDValue Amt0 =
29313           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
29314       SDValue Amt1 =
29315           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
29316       SDValue Sra1 =
29317           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
29318       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
29319       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
29320       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
29321     }
29322   }
29323 
29324   // v4i32 Non Uniform Shifts.
29325   // If the shift amount is constant we can shift each lane using the SSE2
29326   // immediate shifts, else we need to zero-extend each lane to the lower i64
29327   // and shift using the SSE2 variable shifts.
29328   // The separate results can then be blended together.
29329   if (VT == MVT::v4i32) {
29330     SDValue Amt0, Amt1, Amt2, Amt3;
29331     if (ConstantAmt) {
29332       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
29333       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
29334       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
29335       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
29336     } else {
29337       // The SSE2 shifts use the lower i64 as the same shift amount for
29338       // all lanes and the upper i64 is ignored. On AVX we're better off
29339       // just zero-extending, but for SSE just duplicating the top 16-bits is
29340       // cheaper and has the same effect for out of range values.
29341       if (Subtarget.hasAVX()) {
29342         SDValue Z = DAG.getConstant(0, dl, VT);
29343         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
29344         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
29345         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
29346         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
29347       } else {
29348         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
29349         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
29350                                              {4, 5, 6, 7, -1, -1, -1, -1});
29351         SDValue Msk02 = getV4X86ShuffleImm8ForMask({0, 1, 1, 1}, dl, DAG);
29352         SDValue Msk13 = getV4X86ShuffleImm8ForMask({2, 3, 3, 3}, dl, DAG);
29353         Amt0 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk02);
29354         Amt1 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt01, Msk13);
29355         Amt2 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk02);
29356         Amt3 = DAG.getNode(X86ISD::PSHUFLW, dl, MVT::v8i16, Amt23, Msk13);
29357       }
29358     }
29359 
29360     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
29361     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
29362     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
29363     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
29364     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
29365 
29366     // Merge the shifted lane results optimally with/without PBLENDW.
29367     // TODO - ideally shuffle combining would handle this.
29368     if (Subtarget.hasSSE41()) {
29369       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
29370       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
29371       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
29372     }
29373     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
29374     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
29375     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
29376   }
29377 
29378   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
29379   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
29380   // make the existing SSE solution better.
29381   // NOTE: We honor prefered vector width before promoting to 512-bits.
29382   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
29383       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
29384       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
29385       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
29386       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
29387     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
29388            "Unexpected vector type");
29389     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
29390     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
29391     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
29392     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
29393     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
29394     return DAG.getNode(ISD::TRUNCATE, dl, VT,
29395                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
29396   }
29397 
29398   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
29399   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
29400   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
29401       (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
29402        (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
29403       !Subtarget.hasXOP()) {
29404     int NumElts = VT.getVectorNumElements();
29405     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
29406 
29407     // Extend constant shift amount to vXi16 (it doesn't matter if the type
29408     // isn't legal).
29409     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
29410     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
29411     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
29412     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
29413     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
29414            "Constant build vector expected");
29415 
29416     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
29417       bool IsSigned = Opc == ISD::SRA;
29418       R = DAG.getExtOrTrunc(IsSigned, R, dl, ExVT);
29419       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
29420       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
29421       return DAG.getZExtOrTrunc(R, dl, VT);
29422     }
29423 
29424     SmallVector<SDValue, 16> LoAmt, HiAmt;
29425     for (int i = 0; i != NumElts; i += 16) {
29426       for (int j = 0; j != 8; ++j) {
29427         LoAmt.push_back(Amt.getOperand(i + j));
29428         HiAmt.push_back(Amt.getOperand(i + j + 8));
29429       }
29430     }
29431 
29432     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
29433     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
29434     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
29435 
29436     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
29437     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
29438     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
29439     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
29440     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
29441     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
29442     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
29443     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
29444     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
29445   }
29446 
29447   if (VT == MVT::v16i8 ||
29448       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
29449       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
29450     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
29451 
29452     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
29453       if (VT.is512BitVector()) {
29454         // On AVX512BW targets we make use of the fact that VSELECT lowers
29455         // to a masked blend which selects bytes based just on the sign bit
29456         // extracted to a mask.
29457         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
29458         V0 = DAG.getBitcast(VT, V0);
29459         V1 = DAG.getBitcast(VT, V1);
29460         Sel = DAG.getBitcast(VT, Sel);
29461         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
29462                            ISD::SETGT);
29463         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
29464       } else if (Subtarget.hasSSE41()) {
29465         // On SSE41 targets we can use PBLENDVB which selects bytes based just
29466         // on the sign bit.
29467         V0 = DAG.getBitcast(VT, V0);
29468         V1 = DAG.getBitcast(VT, V1);
29469         Sel = DAG.getBitcast(VT, Sel);
29470         return DAG.getBitcast(SelVT,
29471                               DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
29472       }
29473       // On pre-SSE41 targets we test for the sign bit by comparing to
29474       // zero - a negative value will set all bits of the lanes to true
29475       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
29476       SDValue Z = DAG.getConstant(0, dl, SelVT);
29477       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
29478       return DAG.getSelect(dl, SelVT, C, V0, V1);
29479     };
29480 
29481     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
29482     // We can safely do this using i16 shifts as we're only interested in
29483     // the 3 lower bits of each byte.
29484     Amt = DAG.getBitcast(ExtVT, Amt);
29485     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
29486     Amt = DAG.getBitcast(VT, Amt);
29487 
29488     if (Opc == ISD::SHL || Opc == ISD::SRL) {
29489       // r = VSELECT(r, shift(r, 4), a);
29490       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
29491       R = SignBitSelect(VT, Amt, M, R);
29492 
29493       // a += a
29494       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29495 
29496       // r = VSELECT(r, shift(r, 2), a);
29497       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
29498       R = SignBitSelect(VT, Amt, M, R);
29499 
29500       // a += a
29501       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29502 
29503       // return VSELECT(r, shift(r, 1), a);
29504       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
29505       R = SignBitSelect(VT, Amt, M, R);
29506       return R;
29507     }
29508 
29509     if (Opc == ISD::SRA) {
29510       // For SRA we need to unpack each byte to the higher byte of a i16 vector
29511       // so we can correctly sign extend. We don't care what happens to the
29512       // lower byte.
29513       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
29514       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
29515       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
29516       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
29517       ALo = DAG.getBitcast(ExtVT, ALo);
29518       AHi = DAG.getBitcast(ExtVT, AHi);
29519       RLo = DAG.getBitcast(ExtVT, RLo);
29520       RHi = DAG.getBitcast(ExtVT, RHi);
29521 
29522       // r = VSELECT(r, shift(r, 4), a);
29523       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
29524       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
29525       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
29526       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
29527 
29528       // a += a
29529       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
29530       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
29531 
29532       // r = VSELECT(r, shift(r, 2), a);
29533       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
29534       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
29535       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
29536       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
29537 
29538       // a += a
29539       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
29540       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
29541 
29542       // r = VSELECT(r, shift(r, 1), a);
29543       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
29544       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
29545       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
29546       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
29547 
29548       // Logical shift the result back to the lower byte, leaving a zero upper
29549       // byte meaning that we can safely pack with PACKUSWB.
29550       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
29551       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
29552       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
29553     }
29554   }
29555 
29556   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
29557     MVT ExtVT = MVT::v8i32;
29558     SDValue Z = DAG.getConstant(0, dl, VT);
29559     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
29560     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
29561     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
29562     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
29563     ALo = DAG.getBitcast(ExtVT, ALo);
29564     AHi = DAG.getBitcast(ExtVT, AHi);
29565     RLo = DAG.getBitcast(ExtVT, RLo);
29566     RHi = DAG.getBitcast(ExtVT, RHi);
29567     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
29568     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
29569     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
29570     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
29571     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
29572   }
29573 
29574   if (VT == MVT::v8i16) {
29575     // If we have a constant shift amount, the non-SSE41 path is best as
29576     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
29577     bool UseSSE41 = Subtarget.hasSSE41() &&
29578                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29579 
29580     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
29581       // On SSE41 targets we can use PBLENDVB which selects bytes based just on
29582       // the sign bit.
29583       if (UseSSE41) {
29584         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
29585         V0 = DAG.getBitcast(ExtVT, V0);
29586         V1 = DAG.getBitcast(ExtVT, V1);
29587         Sel = DAG.getBitcast(ExtVT, Sel);
29588         return DAG.getBitcast(
29589             VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
29590       }
29591       // On pre-SSE41 targets we splat the sign bit - a negative value will
29592       // set all bits of the lanes to true and VSELECT uses that in
29593       // its OR(AND(V0,C),AND(V1,~C)) lowering.
29594       SDValue C =
29595           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
29596       return DAG.getSelect(dl, VT, C, V0, V1);
29597     };
29598 
29599     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
29600     if (UseSSE41) {
29601       // On SSE41 targets we need to replicate the shift mask in both
29602       // bytes for PBLENDVB.
29603       Amt = DAG.getNode(
29604           ISD::OR, dl, VT,
29605           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
29606           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
29607     } else {
29608       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
29609     }
29610 
29611     // r = VSELECT(r, shift(r, 8), a);
29612     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
29613     R = SignBitSelect(Amt, M, R);
29614 
29615     // a += a
29616     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29617 
29618     // r = VSELECT(r, shift(r, 4), a);
29619     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
29620     R = SignBitSelect(Amt, M, R);
29621 
29622     // a += a
29623     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29624 
29625     // r = VSELECT(r, shift(r, 2), a);
29626     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
29627     R = SignBitSelect(Amt, M, R);
29628 
29629     // a += a
29630     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
29631 
29632     // return VSELECT(r, shift(r, 1), a);
29633     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
29634     R = SignBitSelect(Amt, M, R);
29635     return R;
29636   }
29637 
29638   // Decompose 256-bit shifts into 128-bit shifts.
29639   if (VT.is256BitVector())
29640     return splitVectorIntBinary(Op, DAG);
29641 
29642   if (VT == MVT::v32i16 || VT == MVT::v64i8)
29643     return splitVectorIntBinary(Op, DAG);
29644 
29645   return SDValue();
29646 }
29647 
LowerFunnelShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)29648 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
29649                                 SelectionDAG &DAG) {
29650   MVT VT = Op.getSimpleValueType();
29651   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
29652          "Unexpected funnel shift opcode!");
29653 
29654   SDLoc DL(Op);
29655   SDValue Op0 = Op.getOperand(0);
29656   SDValue Op1 = Op.getOperand(1);
29657   SDValue Amt = Op.getOperand(2);
29658   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29659   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
29660 
29661   if (VT.isVector()) {
29662     APInt APIntShiftAmt;
29663     bool IsCstSplat = X86::isConstantSplat(Amt, APIntShiftAmt);
29664 
29665     if (Subtarget.hasVBMI2() && EltSizeInBits > 8) {
29666       if (IsFSHR)
29667         std::swap(Op0, Op1);
29668 
29669       if (IsCstSplat) {
29670         uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
29671         SDValue Imm = DAG.getTargetConstant(ShiftAmt, DL, MVT::i8);
29672         return getAVX512Node(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
29673                              {Op0, Op1, Imm}, DAG, Subtarget);
29674       }
29675       return getAVX512Node(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
29676                            {Op0, Op1, Amt}, DAG, Subtarget);
29677     }
29678     assert((VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8 ||
29679             VT == MVT::v8i16 || VT == MVT::v16i16 || VT == MVT::v32i16 ||
29680             VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) &&
29681            "Unexpected funnel shift type!");
29682 
29683     // fshl(x,y,z) -> unpack(y,x) << (z & (bw-1))) >> bw.
29684     // fshr(x,y,z) -> unpack(y,x) >> (z & (bw-1))).
29685     if (IsCstSplat) {
29686       // TODO: Can't use generic expansion as UNDEF amt elements can be
29687       // converted to other values when folded to shift amounts, losing the
29688       // splat.
29689       uint64_t ShiftAmt = APIntShiftAmt.urem(EltSizeInBits);
29690       uint64_t ShXAmt = IsFSHR ? (EltSizeInBits - ShiftAmt) : ShiftAmt;
29691       uint64_t ShYAmt = IsFSHR ? ShiftAmt : (EltSizeInBits - ShiftAmt);
29692       SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, Op0,
29693                                 DAG.getShiftAmountConstant(ShXAmt, VT, DL));
29694       SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Op1,
29695                                 DAG.getShiftAmountConstant(ShYAmt, VT, DL));
29696       return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
29697     }
29698 
29699     SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
29700     SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
29701     bool IsCst = ISD::isBuildVectorOfConstantSDNodes(AmtMod.getNode());
29702 
29703     // Constant vXi16 funnel shifts can be efficiently handled by default.
29704     if (IsCst && EltSizeInBits == 16)
29705       return SDValue();
29706 
29707     unsigned ShiftOpc = IsFSHR ? ISD::SRL : ISD::SHL;
29708     unsigned NumElts = VT.getVectorNumElements();
29709     MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
29710     MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
29711 
29712     // Split 256-bit integers on XOP/pre-AVX2 targets.
29713     // Split 512-bit integers on non 512-bit BWI targets.
29714     if ((VT.is256BitVector() && ((Subtarget.hasXOP() && EltSizeInBits < 16) ||
29715                                  !Subtarget.hasAVX2())) ||
29716         (VT.is512BitVector() && !Subtarget.useBWIRegs() &&
29717          EltSizeInBits < 32)) {
29718       // Pre-mask the amount modulo using the wider vector.
29719       Op = DAG.getNode(Op.getOpcode(), DL, VT, Op0, Op1, AmtMod);
29720       return splitVectorOp(Op, DAG);
29721     }
29722 
29723     // Attempt to fold scalar shift as unpack(y,x) << zext(splat(z))
29724     if (supportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, ShiftOpc)) {
29725       int ScalarAmtIdx = -1;
29726       if (SDValue ScalarAmt = DAG.getSplatSourceVector(AmtMod, ScalarAmtIdx)) {
29727         // Uniform vXi16 funnel shifts can be efficiently handled by default.
29728         if (EltSizeInBits == 16)
29729           return SDValue();
29730 
29731         SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
29732         SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
29733         Lo = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Lo, ScalarAmt,
29734                                  ScalarAmtIdx, Subtarget, DAG);
29735         Hi = getTargetVShiftNode(ShiftOpc, DL, ExtVT, Hi, ScalarAmt,
29736                                  ScalarAmtIdx, Subtarget, DAG);
29737         return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
29738       }
29739     }
29740 
29741     MVT WideSVT = MVT::getIntegerVT(
29742         std::min<unsigned>(EltSizeInBits * 2, Subtarget.hasBWI() ? 16 : 32));
29743     MVT WideVT = MVT::getVectorVT(WideSVT, NumElts);
29744 
29745     // If per-element shifts are legal, fallback to generic expansion.
29746     if (supportedVectorVarShift(VT, Subtarget, ShiftOpc) || Subtarget.hasXOP())
29747       return SDValue();
29748 
29749     // Attempt to fold as:
29750     // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
29751     // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
29752     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
29753         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
29754       Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Op0);
29755       Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Op1);
29756       AmtMod = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
29757       Op0 = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, Op0,
29758                                        EltSizeInBits, DAG);
29759       SDValue Res = DAG.getNode(ISD::OR, DL, WideVT, Op0, Op1);
29760       Res = DAG.getNode(ShiftOpc, DL, WideVT, Res, AmtMod);
29761       if (!IsFSHR)
29762         Res = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, Res,
29763                                          EltSizeInBits, DAG);
29764       return DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
29765     }
29766 
29767     // Attempt to fold per-element (ExtVT) shift as unpack(y,x) << zext(z)
29768     if (((IsCst || !Subtarget.hasAVX512()) && !IsFSHR && EltSizeInBits <= 16) ||
29769         supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc)) {
29770       SDValue Z = DAG.getConstant(0, DL, VT);
29771       SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, Op1, Op0));
29772       SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, Op1, Op0));
29773       SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
29774       SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
29775       SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
29776       SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
29777       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, !IsFSHR);
29778     }
29779 
29780     // Fallback to generic expansion.
29781     return SDValue();
29782   }
29783   assert(
29784       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
29785       "Unexpected funnel shift type!");
29786 
29787   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
29788   bool OptForSize = DAG.shouldOptForSize();
29789   bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
29790 
29791   // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
29792   // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
29793   if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
29794       !isa<ConstantSDNode>(Amt)) {
29795     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
29796     SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
29797     Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
29798     Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
29799     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
29800     SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
29801     Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
29802     if (IsFSHR) {
29803       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
29804     } else {
29805       Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
29806       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
29807     }
29808     return DAG.getZExtOrTrunc(Res, DL, VT);
29809   }
29810 
29811   if (VT == MVT::i8 || ExpandFunnel)
29812     return SDValue();
29813 
29814   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
29815   if (VT == MVT::i16) {
29816     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
29817                       DAG.getConstant(15, DL, Amt.getValueType()));
29818     unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
29819     return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
29820   }
29821 
29822   return Op;
29823 }
29824 
LowerRotate(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)29825 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
29826                            SelectionDAG &DAG) {
29827   MVT VT = Op.getSimpleValueType();
29828   assert(VT.isVector() && "Custom lowering only for vector rotates!");
29829 
29830   SDLoc DL(Op);
29831   SDValue R = Op.getOperand(0);
29832   SDValue Amt = Op.getOperand(1);
29833   unsigned Opcode = Op.getOpcode();
29834   unsigned EltSizeInBits = VT.getScalarSizeInBits();
29835   int NumElts = VT.getVectorNumElements();
29836   bool IsROTL = Opcode == ISD::ROTL;
29837 
29838   // Check for constant splat rotation amount.
29839   APInt CstSplatValue;
29840   bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
29841 
29842   // Check for splat rotate by zero.
29843   if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
29844     return R;
29845 
29846   // AVX512 implicitly uses modulo rotation amounts.
29847   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
29848     // Attempt to rotate by immediate.
29849     if (IsCstSplat) {
29850       unsigned RotOpc = IsROTL ? X86ISD::VROTLI : X86ISD::VROTRI;
29851       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
29852       return DAG.getNode(RotOpc, DL, VT, R,
29853                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
29854     }
29855 
29856     // Else, fall-back on VPROLV/VPRORV.
29857     return Op;
29858   }
29859 
29860   // AVX512 VBMI2 vXi16 - lower to funnel shifts.
29861   if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
29862     unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
29863     return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
29864   }
29865 
29866   SDValue Z = DAG.getConstant(0, DL, VT);
29867 
29868   if (!IsROTL) {
29869     // If the ISD::ROTR amount is constant, we're always better converting to
29870     // ISD::ROTL.
29871     if (SDValue NegAmt = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {Z, Amt}))
29872       return DAG.getNode(ISD::ROTL, DL, VT, R, NegAmt);
29873 
29874     // XOP targets always prefers ISD::ROTL.
29875     if (Subtarget.hasXOP())
29876       return DAG.getNode(ISD::ROTL, DL, VT, R,
29877                          DAG.getNode(ISD::SUB, DL, VT, Z, Amt));
29878   }
29879 
29880   // Split 256-bit integers on XOP/pre-AVX2 targets.
29881   if (VT.is256BitVector() && (Subtarget.hasXOP() || !Subtarget.hasAVX2()))
29882     return splitVectorIntBinary(Op, DAG);
29883 
29884   // XOP has 128-bit vector variable + immediate rotates.
29885   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
29886   // XOP implicitly uses modulo rotation amounts.
29887   if (Subtarget.hasXOP()) {
29888     assert(IsROTL && "Only ROTL expected");
29889     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
29890 
29891     // Attempt to rotate by immediate.
29892     if (IsCstSplat) {
29893       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
29894       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
29895                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
29896     }
29897 
29898     // Use general rotate by variable (per-element).
29899     return Op;
29900   }
29901 
29902   // Rotate by an uniform constant - expand back to shifts.
29903   // TODO: Can't use generic expansion as UNDEF amt elements can be converted
29904   // to other values when folded to shift amounts, losing the splat.
29905   if (IsCstSplat) {
29906     uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
29907     uint64_t ShlAmt = IsROTL ? RotAmt : (EltSizeInBits - RotAmt);
29908     uint64_t SrlAmt = IsROTL ? (EltSizeInBits - RotAmt) : RotAmt;
29909     SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, R,
29910                               DAG.getShiftAmountConstant(ShlAmt, VT, DL));
29911     SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, R,
29912                               DAG.getShiftAmountConstant(SrlAmt, VT, DL));
29913     return DAG.getNode(ISD::OR, DL, VT, Shl, Srl);
29914   }
29915 
29916   // Split 512-bit integers on non 512-bit BWI targets.
29917   if (VT.is512BitVector() && !Subtarget.useBWIRegs())
29918     return splitVectorIntBinary(Op, DAG);
29919 
29920   assert(
29921       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
29922        ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
29923         Subtarget.hasAVX2()) ||
29924        ((VT == MVT::v32i16 || VT == MVT::v64i8) && Subtarget.useBWIRegs())) &&
29925       "Only vXi32/vXi16/vXi8 vector rotates supported");
29926 
29927   MVT ExtSVT = MVT::getIntegerVT(2 * EltSizeInBits);
29928   MVT ExtVT = MVT::getVectorVT(ExtSVT, NumElts / 2);
29929 
29930   SDValue AmtMask = DAG.getConstant(EltSizeInBits - 1, DL, VT);
29931   SDValue AmtMod = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
29932 
29933   // Attempt to fold as unpack(x,x) << zext(splat(y)):
29934   // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
29935   // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
29936   if (EltSizeInBits == 8 || EltSizeInBits == 16 || EltSizeInBits == 32) {
29937     int BaseRotAmtIdx = -1;
29938     if (SDValue BaseRotAmt = DAG.getSplatSourceVector(AmtMod, BaseRotAmtIdx)) {
29939       if (EltSizeInBits == 16 && Subtarget.hasSSE41()) {
29940         unsigned FunnelOpc = IsROTL ? ISD::FSHL : ISD::FSHR;
29941         return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
29942       }
29943       unsigned ShiftX86Opc = IsROTL ? X86ISD::VSHLI : X86ISD::VSRLI;
29944       SDValue Lo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
29945       SDValue Hi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
29946       Lo = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Lo, BaseRotAmt,
29947                                BaseRotAmtIdx, Subtarget, DAG);
29948       Hi = getTargetVShiftNode(ShiftX86Opc, DL, ExtVT, Hi, BaseRotAmt,
29949                                BaseRotAmtIdx, Subtarget, DAG);
29950       return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
29951     }
29952   }
29953 
29954   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
29955   unsigned ShiftOpc = IsROTL ? ISD::SHL : ISD::SRL;
29956 
29957   // Attempt to fold as unpack(x,x) << zext(y):
29958   // rotl(x,y) -> (unpack(x,x) << (y & (bw-1))) >> bw.
29959   // rotr(x,y) -> (unpack(x,x) >> (y & (bw-1))).
29960   // Const vXi16/vXi32 are excluded in favor of MUL-based lowering.
29961   if (!(ConstantAmt && EltSizeInBits != 8) &&
29962       !supportedVectorVarShift(VT, Subtarget, ShiftOpc) &&
29963       (ConstantAmt || supportedVectorVarShift(ExtVT, Subtarget, ShiftOpc))) {
29964     SDValue RLo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, R, R));
29965     SDValue RHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, R, R));
29966     SDValue ALo = DAG.getBitcast(ExtVT, getUnpackl(DAG, DL, VT, AmtMod, Z));
29967     SDValue AHi = DAG.getBitcast(ExtVT, getUnpackh(DAG, DL, VT, AmtMod, Z));
29968     SDValue Lo = DAG.getNode(ShiftOpc, DL, ExtVT, RLo, ALo);
29969     SDValue Hi = DAG.getNode(ShiftOpc, DL, ExtVT, RHi, AHi);
29970     return getPack(DAG, Subtarget, DL, VT, Lo, Hi, IsROTL);
29971   }
29972 
29973   // v16i8/v32i8/v64i8: Split rotation into rot4/rot2/rot1 stages and select by
29974   // the amount bit.
29975   // TODO: We're doing nothing here that we couldn't do for funnel shifts.
29976   if (EltSizeInBits == 8) {
29977     MVT WideVT =
29978         MVT::getVectorVT(Subtarget.hasBWI() ? MVT::i16 : MVT::i32, NumElts);
29979 
29980     // Attempt to fold as:
29981     // rotl(x,y) -> (((aext(x) << bw) | zext(x)) << (y & (bw-1))) >> bw.
29982     // rotr(x,y) -> (((aext(x) << bw) | zext(x)) >> (y & (bw-1))).
29983     if (supportedVectorVarShift(WideVT, Subtarget, ShiftOpc) &&
29984         supportedVectorShiftWithImm(WideVT, Subtarget, ShiftOpc)) {
29985       // If we're rotating by constant, just use default promotion.
29986       if (ConstantAmt)
29987         return SDValue();
29988       // See if we can perform this by widening to vXi16 or vXi32.
29989       R = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, R);
29990       R = DAG.getNode(
29991           ISD::OR, DL, WideVT, R,
29992           getTargetVShiftByConstNode(X86ISD::VSHLI, DL, WideVT, R, 8, DAG));
29993       Amt = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, AmtMod);
29994       R = DAG.getNode(ShiftOpc, DL, WideVT, R, Amt);
29995       if (IsROTL)
29996         R = getTargetVShiftByConstNode(X86ISD::VSRLI, DL, WideVT, R, 8, DAG);
29997       return DAG.getNode(ISD::TRUNCATE, DL, VT, R);
29998     }
29999 
30000     // We don't need ModuloAmt here as we just peek at individual bits.
30001     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
30002       if (Subtarget.hasSSE41()) {
30003         // On SSE41 targets we can use PBLENDVB which selects bytes based just
30004         // on the sign bit.
30005         V0 = DAG.getBitcast(VT, V0);
30006         V1 = DAG.getBitcast(VT, V1);
30007         Sel = DAG.getBitcast(VT, Sel);
30008         return DAG.getBitcast(SelVT,
30009                               DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
30010       }
30011       // On pre-SSE41 targets we test for the sign bit by comparing to
30012       // zero - a negative value will set all bits of the lanes to true
30013       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
30014       SDValue Z = DAG.getConstant(0, DL, SelVT);
30015       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
30016       return DAG.getSelect(DL, SelVT, C, V0, V1);
30017     };
30018 
30019     // ISD::ROTR is currently only profitable on AVX512 targets with VPTERNLOG.
30020     if (!IsROTL && !useVPTERNLOG(Subtarget, VT)) {
30021       Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
30022       IsROTL = true;
30023     }
30024 
30025     unsigned ShiftLHS = IsROTL ? ISD::SHL : ISD::SRL;
30026     unsigned ShiftRHS = IsROTL ? ISD::SRL : ISD::SHL;
30027 
30028     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
30029     // We can safely do this using i16 shifts as we're only interested in
30030     // the 3 lower bits of each byte.
30031     Amt = DAG.getBitcast(ExtVT, Amt);
30032     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
30033     Amt = DAG.getBitcast(VT, Amt);
30034 
30035     // r = VSELECT(r, rot(r, 4), a);
30036     SDValue M;
30037     M = DAG.getNode(
30038         ISD::OR, DL, VT,
30039         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(4, DL, VT)),
30040         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(4, DL, VT)));
30041     R = SignBitSelect(VT, Amt, M, R);
30042 
30043     // a += a
30044     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
30045 
30046     // r = VSELECT(r, rot(r, 2), a);
30047     M = DAG.getNode(
30048         ISD::OR, DL, VT,
30049         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(2, DL, VT)),
30050         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(6, DL, VT)));
30051     R = SignBitSelect(VT, Amt, M, R);
30052 
30053     // a += a
30054     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
30055 
30056     // return VSELECT(r, rot(r, 1), a);
30057     M = DAG.getNode(
30058         ISD::OR, DL, VT,
30059         DAG.getNode(ShiftLHS, DL, VT, R, DAG.getConstant(1, DL, VT)),
30060         DAG.getNode(ShiftRHS, DL, VT, R, DAG.getConstant(7, DL, VT)));
30061     return SignBitSelect(VT, Amt, M, R);
30062   }
30063 
30064   bool IsSplatAmt = DAG.isSplatValue(Amt);
30065   bool LegalVarShifts = supportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
30066                         supportedVectorVarShift(VT, Subtarget, ISD::SRL);
30067 
30068   // Fallback for splats + all supported variable shifts.
30069   // Fallback for non-constants AVX2 vXi16 as well.
30070   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
30071     Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30072     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
30073     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
30074     SDValue SHL = DAG.getNode(IsROTL ? ISD::SHL : ISD::SRL, DL, VT, R, Amt);
30075     SDValue SRL = DAG.getNode(IsROTL ? ISD::SRL : ISD::SHL, DL, VT, R, AmtR);
30076     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
30077   }
30078 
30079   // Everything below assumes ISD::ROTL.
30080   if (!IsROTL) {
30081     Amt = DAG.getNode(ISD::SUB, DL, VT, Z, Amt);
30082     IsROTL = true;
30083   }
30084 
30085   // ISD::ROT* uses modulo rotate amounts.
30086   Amt = DAG.getNode(ISD::AND, DL, VT, Amt, AmtMask);
30087 
30088   assert(IsROTL && "Only ROTL supported");
30089 
30090   // As with shifts, attempt to convert the rotation amount to a multiplication
30091   // factor, fallback to general expansion.
30092   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
30093   if (!Scale)
30094     return SDValue();
30095 
30096   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
30097   if (EltSizeInBits == 16) {
30098     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
30099     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
30100     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
30101   }
30102 
30103   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
30104   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
30105   // that can then be OR'd with the lower 32-bits.
30106   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
30107   static const int OddMask[] = {1, -1, 3, -1};
30108   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
30109   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
30110 
30111   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
30112                               DAG.getBitcast(MVT::v2i64, R),
30113                               DAG.getBitcast(MVT::v2i64, Scale));
30114   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
30115                               DAG.getBitcast(MVT::v2i64, R13),
30116                               DAG.getBitcast(MVT::v2i64, Scale13));
30117   Res02 = DAG.getBitcast(VT, Res02);
30118   Res13 = DAG.getBitcast(VT, Res13);
30119 
30120   return DAG.getNode(ISD::OR, DL, VT,
30121                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
30122                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
30123 }
30124 
30125 /// Returns true if the operand type is exactly twice the native width, and
30126 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
30127 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
30128 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
needsCmpXchgNb(Type * MemType) const30129 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
30130   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
30131 
30132   if (OpWidth == 64)
30133     return Subtarget.canUseCMPXCHG8B() && !Subtarget.is64Bit();
30134   if (OpWidth == 128)
30135     return Subtarget.canUseCMPXCHG16B();
30136 
30137   return false;
30138 }
30139 
30140 TargetLoweringBase::AtomicExpansionKind
shouldExpandAtomicStoreInIR(StoreInst * SI) const30141 X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
30142   Type *MemType = SI->getValueOperand()->getType();
30143 
30144   bool NoImplicitFloatOps =
30145       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
30146   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
30147       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
30148       (Subtarget.hasSSE1() || Subtarget.hasX87()))
30149     return AtomicExpansionKind::None;
30150 
30151   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::Expand
30152                                  : AtomicExpansionKind::None;
30153 }
30154 
30155 // Note: this turns large loads into lock cmpxchg8b/16b.
30156 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
30157 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const30158 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
30159   Type *MemType = LI->getType();
30160 
30161   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
30162   // can use movq to do the load. If we have X87 we can load into an 80-bit
30163   // X87 register and store it to a stack temporary.
30164   bool NoImplicitFloatOps =
30165       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
30166   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
30167       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
30168       (Subtarget.hasSSE1() || Subtarget.hasX87()))
30169     return AtomicExpansionKind::None;
30170 
30171   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
30172                                  : AtomicExpansionKind::None;
30173 }
30174 
30175 enum BitTestKind : unsigned {
30176   UndefBit,
30177   ConstantBit,
30178   NotConstantBit,
30179   ShiftBit,
30180   NotShiftBit
30181 };
30182 
FindSingleBitChange(Value * V)30183 static std::pair<Value *, BitTestKind> FindSingleBitChange(Value *V) {
30184   using namespace llvm::PatternMatch;
30185   BitTestKind BTK = UndefBit;
30186   auto *C = dyn_cast<ConstantInt>(V);
30187   if (C) {
30188     // Check if V is a power of 2 or NOT power of 2.
30189     if (isPowerOf2_64(C->getZExtValue()))
30190       BTK = ConstantBit;
30191     else if (isPowerOf2_64((~C->getValue()).getZExtValue()))
30192       BTK = NotConstantBit;
30193     return {V, BTK};
30194   }
30195 
30196   // Check if V is some power of 2 pattern known to be non-zero
30197   auto *I = dyn_cast<Instruction>(V);
30198   if (I) {
30199     bool Not = false;
30200     // Check if we have a NOT
30201     Value *PeekI;
30202     if (match(I, m_c_Xor(m_Value(PeekI), m_AllOnes())) ||
30203         match(I, m_Sub(m_AllOnes(), m_Value(PeekI)))) {
30204       Not = true;
30205       I = dyn_cast<Instruction>(PeekI);
30206 
30207       // If I is constant, it will fold and we can evaluate later. If its an
30208       // argument or something of that nature, we can't analyze.
30209       if (I == nullptr)
30210         return {nullptr, UndefBit};
30211     }
30212     // We can only use 1 << X without more sophisticated analysis. C << X where
30213     // C is a power of 2 but not 1 can result in zero which cannot be translated
30214     // to bittest. Likewise any C >> X (either arith or logical) can be zero.
30215     if (I->getOpcode() == Instruction::Shl) {
30216       // Todo(1): The cmpxchg case is pretty costly so matching `BLSI(X)`, `X &
30217       // -X` and some other provable power of 2 patterns that we can use CTZ on
30218       // may be profitable.
30219       // Todo(2): It may be possible in some cases to prove that Shl(C, X) is
30220       // non-zero even where C != 1. Likewise LShr(C, X) and AShr(C, X) may also
30221       // be provably a non-zero power of 2.
30222       // Todo(3): ROTL and ROTR patterns on a power of 2 C should also be
30223       // transformable to bittest.
30224       auto *ShiftVal = dyn_cast<ConstantInt>(I->getOperand(0));
30225       if (!ShiftVal)
30226         return {nullptr, UndefBit};
30227       if (ShiftVal->equalsInt(1))
30228         BTK = Not ? NotShiftBit : ShiftBit;
30229 
30230       if (BTK == UndefBit)
30231         return {nullptr, UndefBit};
30232 
30233       Value *BitV = I->getOperand(1);
30234 
30235       Value *AndOp;
30236       const APInt *AndC;
30237       if (match(BitV, m_c_And(m_Value(AndOp), m_APInt(AndC)))) {
30238         // Read past a shiftmask instruction to find count
30239         if (*AndC == (I->getType()->getPrimitiveSizeInBits() - 1))
30240           BitV = AndOp;
30241       }
30242       return {BitV, BTK};
30243     }
30244   }
30245   return {nullptr, UndefBit};
30246 }
30247 
30248 TargetLowering::AtomicExpansionKind
shouldExpandLogicAtomicRMWInIR(AtomicRMWInst * AI) const30249 X86TargetLowering::shouldExpandLogicAtomicRMWInIR(AtomicRMWInst *AI) const {
30250   using namespace llvm::PatternMatch;
30251   // If the atomicrmw's result isn't actually used, we can just add a "lock"
30252   // prefix to a normal instruction for these operations.
30253   if (AI->use_empty())
30254     return AtomicExpansionKind::None;
30255 
30256   if (AI->getOperation() == AtomicRMWInst::Xor) {
30257     // A ^ SignBit -> A + SignBit. This allows us to use `xadd` which is
30258     // preferable to both `cmpxchg` and `btc`.
30259     if (match(AI->getOperand(1), m_SignMask()))
30260       return AtomicExpansionKind::None;
30261   }
30262 
30263   // If the atomicrmw's result is used by a single bit AND, we may use
30264   // bts/btr/btc instruction for these operations.
30265   // Note: InstCombinePass can cause a de-optimization here. It replaces the
30266   // SETCC(And(AtomicRMW(P, power_of_2), power_of_2)) with LShr and Xor
30267   // (depending on CC). This pattern can only use bts/btr/btc but we don't
30268   // detect it.
30269   Instruction *I = AI->user_back();
30270   auto BitChange = FindSingleBitChange(AI->getValOperand());
30271   if (BitChange.second == UndefBit || !AI->hasOneUse() ||
30272       I->getOpcode() != Instruction::And ||
30273       AI->getType()->getPrimitiveSizeInBits() == 8 ||
30274       AI->getParent() != I->getParent())
30275     return AtomicExpansionKind::CmpXChg;
30276 
30277   unsigned OtherIdx = I->getOperand(0) == AI ? 1 : 0;
30278 
30279   // This is a redundant AND, it should get cleaned up elsewhere.
30280   if (AI == I->getOperand(OtherIdx))
30281     return AtomicExpansionKind::CmpXChg;
30282 
30283   // The following instruction must be a AND single bit.
30284   if (BitChange.second == ConstantBit || BitChange.second == NotConstantBit) {
30285     auto *C1 = cast<ConstantInt>(AI->getValOperand());
30286     auto *C2 = dyn_cast<ConstantInt>(I->getOperand(OtherIdx));
30287     if (!C2 || !isPowerOf2_64(C2->getZExtValue())) {
30288       return AtomicExpansionKind::CmpXChg;
30289     }
30290     if (AI->getOperation() == AtomicRMWInst::And) {
30291       return ~C1->getValue() == C2->getValue()
30292                  ? AtomicExpansionKind::BitTestIntrinsic
30293                  : AtomicExpansionKind::CmpXChg;
30294     }
30295     return C1 == C2 ? AtomicExpansionKind::BitTestIntrinsic
30296                     : AtomicExpansionKind::CmpXChg;
30297   }
30298 
30299   assert(BitChange.second == ShiftBit || BitChange.second == NotShiftBit);
30300 
30301   auto BitTested = FindSingleBitChange(I->getOperand(OtherIdx));
30302   if (BitTested.second != ShiftBit && BitTested.second != NotShiftBit)
30303     return AtomicExpansionKind::CmpXChg;
30304 
30305   assert(BitChange.first != nullptr && BitTested.first != nullptr);
30306 
30307   // If shift amounts are not the same we can't use BitTestIntrinsic.
30308   if (BitChange.first != BitTested.first)
30309     return AtomicExpansionKind::CmpXChg;
30310 
30311   // If atomic AND need to be masking all be one bit and testing the one bit
30312   // unset in the mask.
30313   if (AI->getOperation() == AtomicRMWInst::And)
30314     return (BitChange.second == NotShiftBit && BitTested.second == ShiftBit)
30315                ? AtomicExpansionKind::BitTestIntrinsic
30316                : AtomicExpansionKind::CmpXChg;
30317 
30318   // If atomic XOR/OR need to be setting and testing the same bit.
30319   return (BitChange.second == ShiftBit && BitTested.second == ShiftBit)
30320              ? AtomicExpansionKind::BitTestIntrinsic
30321              : AtomicExpansionKind::CmpXChg;
30322 }
30323 
emitBitTestAtomicRMWIntrinsic(AtomicRMWInst * AI) const30324 void X86TargetLowering::emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
30325   IRBuilder<> Builder(AI);
30326   Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
30327   Intrinsic::ID IID_C = Intrinsic::not_intrinsic;
30328   Intrinsic::ID IID_I = Intrinsic::not_intrinsic;
30329   switch (AI->getOperation()) {
30330   default:
30331     llvm_unreachable("Unknown atomic operation");
30332   case AtomicRMWInst::Or:
30333     IID_C = Intrinsic::x86_atomic_bts;
30334     IID_I = Intrinsic::x86_atomic_bts_rm;
30335     break;
30336   case AtomicRMWInst::Xor:
30337     IID_C = Intrinsic::x86_atomic_btc;
30338     IID_I = Intrinsic::x86_atomic_btc_rm;
30339     break;
30340   case AtomicRMWInst::And:
30341     IID_C = Intrinsic::x86_atomic_btr;
30342     IID_I = Intrinsic::x86_atomic_btr_rm;
30343     break;
30344   }
30345   Instruction *I = AI->user_back();
30346   LLVMContext &Ctx = AI->getContext();
30347   Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
30348                                           PointerType::getUnqual(Ctx));
30349   Function *BitTest = nullptr;
30350   Value *Result = nullptr;
30351   auto BitTested = FindSingleBitChange(AI->getValOperand());
30352   assert(BitTested.first != nullptr);
30353 
30354   if (BitTested.second == ConstantBit || BitTested.second == NotConstantBit) {
30355     auto *C = cast<ConstantInt>(I->getOperand(I->getOperand(0) == AI ? 1 : 0));
30356 
30357     BitTest = Intrinsic::getDeclaration(AI->getModule(), IID_C, AI->getType());
30358 
30359     unsigned Imm = llvm::countr_zero(C->getZExtValue());
30360     Result = Builder.CreateCall(BitTest, {Addr, Builder.getInt8(Imm)});
30361   } else {
30362     BitTest = Intrinsic::getDeclaration(AI->getModule(), IID_I, AI->getType());
30363 
30364     assert(BitTested.second == ShiftBit || BitTested.second == NotShiftBit);
30365 
30366     Value *SI = BitTested.first;
30367     assert(SI != nullptr);
30368 
30369     // BT{S|R|C} on memory operand don't modulo bit position so we need to
30370     // mask it.
30371     unsigned ShiftBits = SI->getType()->getPrimitiveSizeInBits();
30372     Value *BitPos =
30373         Builder.CreateAnd(SI, Builder.getIntN(ShiftBits, ShiftBits - 1));
30374     // Todo(1): In many cases it may be provable that SI is less than
30375     // ShiftBits in which case this mask is unnecessary
30376     // Todo(2): In the fairly idiomatic case of P[X / sizeof_bits(X)] OP 1
30377     // << (X % sizeof_bits(X)) we can drop the shift mask and AGEN in
30378     // favor of just a raw BT{S|R|C}.
30379 
30380     Result = Builder.CreateCall(BitTest, {Addr, BitPos});
30381     Result = Builder.CreateZExtOrTrunc(Result, AI->getType());
30382 
30383     // If the result is only used for zero/non-zero status then we don't need to
30384     // shift value back. Otherwise do so.
30385     for (auto It = I->user_begin(); It != I->user_end(); ++It) {
30386       if (auto *ICmp = dyn_cast<ICmpInst>(*It)) {
30387         if (ICmp->isEquality()) {
30388           auto *C0 = dyn_cast<ConstantInt>(ICmp->getOperand(0));
30389           auto *C1 = dyn_cast<ConstantInt>(ICmp->getOperand(1));
30390           if (C0 || C1) {
30391             assert(C0 == nullptr || C1 == nullptr);
30392             if ((C0 ? C0 : C1)->isZero())
30393               continue;
30394           }
30395         }
30396       }
30397       Result = Builder.CreateShl(Result, BitPos);
30398       break;
30399     }
30400   }
30401 
30402   I->replaceAllUsesWith(Result);
30403   I->eraseFromParent();
30404   AI->eraseFromParent();
30405 }
30406 
shouldExpandCmpArithRMWInIR(AtomicRMWInst * AI)30407 static bool shouldExpandCmpArithRMWInIR(AtomicRMWInst *AI) {
30408   using namespace llvm::PatternMatch;
30409   if (!AI->hasOneUse())
30410     return false;
30411 
30412   Value *Op = AI->getOperand(1);
30413   ICmpInst::Predicate Pred;
30414   Instruction *I = AI->user_back();
30415   AtomicRMWInst::BinOp Opc = AI->getOperation();
30416   if (Opc == AtomicRMWInst::Add) {
30417     if (match(I, m_c_ICmp(Pred, m_Sub(m_ZeroInt(), m_Specific(Op)), m_Value())))
30418       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
30419     if (match(I, m_OneUse(m_c_Add(m_Specific(Op), m_Value())))) {
30420       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
30421         return Pred == CmpInst::ICMP_SLT;
30422       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
30423         return Pred == CmpInst::ICMP_SGT;
30424     }
30425     return false;
30426   }
30427   if (Opc == AtomicRMWInst::Sub) {
30428     if (match(I, m_c_ICmp(Pred, m_Specific(Op), m_Value())))
30429       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
30430     if (match(I, m_OneUse(m_Sub(m_Value(), m_Specific(Op))))) {
30431       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
30432         return Pred == CmpInst::ICMP_SLT;
30433       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
30434         return Pred == CmpInst::ICMP_SGT;
30435     }
30436     return false;
30437   }
30438   if ((Opc == AtomicRMWInst::Or &&
30439        match(I, m_OneUse(m_c_Or(m_Specific(Op), m_Value())))) ||
30440       (Opc == AtomicRMWInst::And &&
30441        match(I, m_OneUse(m_c_And(m_Specific(Op), m_Value()))))) {
30442     if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
30443       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE ||
30444              Pred == CmpInst::ICMP_SLT;
30445     if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
30446       return Pred == CmpInst::ICMP_SGT;
30447     return false;
30448   }
30449   if (Opc == AtomicRMWInst::Xor) {
30450     if (match(I, m_c_ICmp(Pred, m_Specific(Op), m_Value())))
30451       return Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE;
30452     if (match(I, m_OneUse(m_c_Xor(m_Specific(Op), m_Value())))) {
30453       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_ZeroInt())))
30454         return Pred == CmpInst::ICMP_SLT;
30455       if (match(I->user_back(), m_ICmp(Pred, m_Value(), m_AllOnes())))
30456         return Pred == CmpInst::ICMP_SGT;
30457     }
30458     return false;
30459   }
30460 
30461   return false;
30462 }
30463 
emitCmpArithAtomicRMWIntrinsic(AtomicRMWInst * AI) const30464 void X86TargetLowering::emitCmpArithAtomicRMWIntrinsic(
30465     AtomicRMWInst *AI) const {
30466   IRBuilder<> Builder(AI);
30467   Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
30468   Instruction *TempI = nullptr;
30469   LLVMContext &Ctx = AI->getContext();
30470   ICmpInst *ICI = dyn_cast<ICmpInst>(AI->user_back());
30471   if (!ICI) {
30472     TempI = AI->user_back();
30473     assert(TempI->hasOneUse() && "Must have one use");
30474     ICI = cast<ICmpInst>(TempI->user_back());
30475   }
30476   X86::CondCode CC = X86::COND_INVALID;
30477   ICmpInst::Predicate Pred = ICI->getPredicate();
30478   switch (Pred) {
30479   default:
30480     llvm_unreachable("Not supported Pred");
30481   case CmpInst::ICMP_EQ:
30482     CC = X86::COND_E;
30483     break;
30484   case CmpInst::ICMP_NE:
30485     CC = X86::COND_NE;
30486     break;
30487   case CmpInst::ICMP_SLT:
30488     CC = X86::COND_S;
30489     break;
30490   case CmpInst::ICMP_SGT:
30491     CC = X86::COND_NS;
30492     break;
30493   }
30494   Intrinsic::ID IID = Intrinsic::not_intrinsic;
30495   switch (AI->getOperation()) {
30496   default:
30497     llvm_unreachable("Unknown atomic operation");
30498   case AtomicRMWInst::Add:
30499     IID = Intrinsic::x86_atomic_add_cc;
30500     break;
30501   case AtomicRMWInst::Sub:
30502     IID = Intrinsic::x86_atomic_sub_cc;
30503     break;
30504   case AtomicRMWInst::Or:
30505     IID = Intrinsic::x86_atomic_or_cc;
30506     break;
30507   case AtomicRMWInst::And:
30508     IID = Intrinsic::x86_atomic_and_cc;
30509     break;
30510   case AtomicRMWInst::Xor:
30511     IID = Intrinsic::x86_atomic_xor_cc;
30512     break;
30513   }
30514   Function *CmpArith =
30515       Intrinsic::getDeclaration(AI->getModule(), IID, AI->getType());
30516   Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
30517                                           PointerType::getUnqual(Ctx));
30518   Value *Call = Builder.CreateCall(
30519       CmpArith, {Addr, AI->getValOperand(), Builder.getInt32((unsigned)CC)});
30520   Value *Result = Builder.CreateTrunc(Call, Type::getInt1Ty(Ctx));
30521   ICI->replaceAllUsesWith(Result);
30522   ICI->eraseFromParent();
30523   if (TempI)
30524     TempI->eraseFromParent();
30525   AI->eraseFromParent();
30526 }
30527 
30528 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const30529 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
30530   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
30531   Type *MemType = AI->getType();
30532 
30533   // If the operand is too big, we must see if cmpxchg8/16b is available
30534   // and default to library calls otherwise.
30535   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
30536     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
30537                                    : AtomicExpansionKind::None;
30538   }
30539 
30540   AtomicRMWInst::BinOp Op = AI->getOperation();
30541   switch (Op) {
30542   case AtomicRMWInst::Xchg:
30543     return AtomicExpansionKind::None;
30544   case AtomicRMWInst::Add:
30545   case AtomicRMWInst::Sub:
30546     if (shouldExpandCmpArithRMWInIR(AI))
30547       return AtomicExpansionKind::CmpArithIntrinsic;
30548     // It's better to use xadd, xsub or xchg for these in other cases.
30549     return AtomicExpansionKind::None;
30550   case AtomicRMWInst::Or:
30551   case AtomicRMWInst::And:
30552   case AtomicRMWInst::Xor:
30553     if (shouldExpandCmpArithRMWInIR(AI))
30554       return AtomicExpansionKind::CmpArithIntrinsic;
30555     return shouldExpandLogicAtomicRMWInIR(AI);
30556   case AtomicRMWInst::Nand:
30557   case AtomicRMWInst::Max:
30558   case AtomicRMWInst::Min:
30559   case AtomicRMWInst::UMax:
30560   case AtomicRMWInst::UMin:
30561   case AtomicRMWInst::FAdd:
30562   case AtomicRMWInst::FSub:
30563   case AtomicRMWInst::FMax:
30564   case AtomicRMWInst::FMin:
30565   case AtomicRMWInst::UIncWrap:
30566   case AtomicRMWInst::UDecWrap:
30567   default:
30568     // These always require a non-trivial set of data operations on x86. We must
30569     // use a cmpxchg loop.
30570     return AtomicExpansionKind::CmpXChg;
30571   }
30572 }
30573 
30574 LoadInst *
lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst * AI) const30575 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
30576   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
30577   Type *MemType = AI->getType();
30578   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
30579   // there is no benefit in turning such RMWs into loads, and it is actually
30580   // harmful as it introduces a mfence.
30581   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
30582     return nullptr;
30583 
30584   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
30585   // lowering available in lowerAtomicArith.
30586   // TODO: push more cases through this path.
30587   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
30588     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
30589         AI->use_empty())
30590       return nullptr;
30591 
30592   IRBuilder<> Builder(AI);
30593   Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
30594   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
30595   auto SSID = AI->getSyncScopeID();
30596   // We must restrict the ordering to avoid generating loads with Release or
30597   // ReleaseAcquire orderings.
30598   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
30599 
30600   // Before the load we need a fence. Here is an example lifted from
30601   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
30602   // is required:
30603   // Thread 0:
30604   //   x.store(1, relaxed);
30605   //   r1 = y.fetch_add(0, release);
30606   // Thread 1:
30607   //   y.fetch_add(42, acquire);
30608   //   r2 = x.load(relaxed);
30609   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
30610   // lowered to just a load without a fence. A mfence flushes the store buffer,
30611   // making the optimization clearly correct.
30612   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
30613   // otherwise, we might be able to be more aggressive on relaxed idempotent
30614   // rmw. In practice, they do not look useful, so we don't try to be
30615   // especially clever.
30616   if (SSID == SyncScope::SingleThread)
30617     // FIXME: we could just insert an ISD::MEMBARRIER here, except we are at
30618     // the IR level, so we must wrap it in an intrinsic.
30619     return nullptr;
30620 
30621   if (!Subtarget.hasMFence())
30622     // FIXME: it might make sense to use a locked operation here but on a
30623     // different cache-line to prevent cache-line bouncing. In practice it
30624     // is probably a small win, and x86 processors without mfence are rare
30625     // enough that we do not bother.
30626     return nullptr;
30627 
30628   Function *MFence =
30629       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
30630   Builder.CreateCall(MFence, {});
30631 
30632   // Finally we can emit the atomic load.
30633   LoadInst *Loaded = Builder.CreateAlignedLoad(
30634       AI->getType(), AI->getPointerOperand(), AI->getAlign());
30635   Loaded->setAtomic(Order, SSID);
30636   AI->replaceAllUsesWith(Loaded);
30637   AI->eraseFromParent();
30638   return Loaded;
30639 }
30640 
30641 /// Emit a locked operation on a stack location which does not change any
30642 /// memory location, but does involve a lock prefix.  Location is chosen to be
30643 /// a) very likely accessed only by a single thread to minimize cache traffic,
30644 /// and b) definitely dereferenceable.  Returns the new Chain result.
emitLockedStackOp(SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue Chain,const SDLoc & DL)30645 static SDValue emitLockedStackOp(SelectionDAG &DAG,
30646                                  const X86Subtarget &Subtarget, SDValue Chain,
30647                                  const SDLoc &DL) {
30648   // Implementation notes:
30649   // 1) LOCK prefix creates a full read/write reordering barrier for memory
30650   // operations issued by the current processor.  As such, the location
30651   // referenced is not relevant for the ordering properties of the instruction.
30652   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
30653   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
30654   // 2) Using an immediate operand appears to be the best encoding choice
30655   // here since it doesn't require an extra register.
30656   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
30657   // is small enough it might just be measurement noise.)
30658   // 4) When choosing offsets, there are several contributing factors:
30659   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
30660   //      line aligned stack object to improve this case.)
30661   //   b) To minimize our chances of introducing a false dependence, we prefer
30662   //      to offset the stack usage from TOS slightly.
30663   //   c) To minimize concerns about cross thread stack usage - in particular,
30664   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
30665   //      captures state in the TOS frame and accesses it from many threads -
30666   //      we want to use an offset such that the offset is in a distinct cache
30667   //      line from the TOS frame.
30668   //
30669   // For a general discussion of the tradeoffs and benchmark results, see:
30670   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
30671 
30672   auto &MF = DAG.getMachineFunction();
30673   auto &TFL = *Subtarget.getFrameLowering();
30674   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
30675 
30676   if (Subtarget.is64Bit()) {
30677     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
30678     SDValue Ops[] = {
30679       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
30680       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
30681       DAG.getRegister(0, MVT::i64),                         // Index
30682       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
30683       DAG.getRegister(0, MVT::i16),                         // Segment.
30684       Zero,
30685       Chain};
30686     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
30687                                      MVT::Other, Ops);
30688     return SDValue(Res, 1);
30689   }
30690 
30691   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
30692   SDValue Ops[] = {
30693     DAG.getRegister(X86::ESP, MVT::i32),            // Base
30694     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
30695     DAG.getRegister(0, MVT::i32),                   // Index
30696     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
30697     DAG.getRegister(0, MVT::i16),                   // Segment.
30698     Zero,
30699     Chain
30700   };
30701   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
30702                                    MVT::Other, Ops);
30703   return SDValue(Res, 1);
30704 }
30705 
LowerATOMIC_FENCE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)30706 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
30707                                  SelectionDAG &DAG) {
30708   SDLoc dl(Op);
30709   AtomicOrdering FenceOrdering =
30710       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
30711   SyncScope::ID FenceSSID =
30712       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
30713 
30714   // The only fence that needs an instruction is a sequentially-consistent
30715   // cross-thread fence.
30716   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
30717       FenceSSID == SyncScope::System) {
30718     if (Subtarget.hasMFence())
30719       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
30720 
30721     SDValue Chain = Op.getOperand(0);
30722     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
30723   }
30724 
30725   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
30726   return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
30727 }
30728 
LowerCMP_SWAP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)30729 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
30730                              SelectionDAG &DAG) {
30731   MVT T = Op.getSimpleValueType();
30732   SDLoc DL(Op);
30733   unsigned Reg = 0;
30734   unsigned size = 0;
30735   switch(T.SimpleTy) {
30736   default: llvm_unreachable("Invalid value type!");
30737   case MVT::i8:  Reg = X86::AL;  size = 1; break;
30738   case MVT::i16: Reg = X86::AX;  size = 2; break;
30739   case MVT::i32: Reg = X86::EAX; size = 4; break;
30740   case MVT::i64:
30741     assert(Subtarget.is64Bit() && "Node not type legal!");
30742     Reg = X86::RAX; size = 8;
30743     break;
30744   }
30745   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
30746                                   Op.getOperand(2), SDValue());
30747   SDValue Ops[] = { cpIn.getValue(0),
30748                     Op.getOperand(1),
30749                     Op.getOperand(3),
30750                     DAG.getTargetConstant(size, DL, MVT::i8),
30751                     cpIn.getValue(1) };
30752   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
30753   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
30754   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
30755                                            Ops, T, MMO);
30756 
30757   SDValue cpOut =
30758     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
30759   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
30760                                       MVT::i32, cpOut.getValue(2));
30761   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
30762 
30763   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
30764                      cpOut, Success, EFLAGS.getValue(1));
30765 }
30766 
30767 // Create MOVMSKB, taking into account whether we need to split for AVX1.
getPMOVMSKB(const SDLoc & DL,SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)30768 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
30769                            const X86Subtarget &Subtarget) {
30770   MVT InVT = V.getSimpleValueType();
30771 
30772   if (InVT == MVT::v64i8) {
30773     SDValue Lo, Hi;
30774     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
30775     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
30776     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
30777     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
30778     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
30779     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
30780                      DAG.getConstant(32, DL, MVT::i8));
30781     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
30782   }
30783   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
30784     SDValue Lo, Hi;
30785     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
30786     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
30787     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
30788     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
30789                      DAG.getConstant(16, DL, MVT::i8));
30790     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
30791   }
30792 
30793   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
30794 }
30795 
LowerBITCAST(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)30796 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
30797                             SelectionDAG &DAG) {
30798   SDValue Src = Op.getOperand(0);
30799   MVT SrcVT = Src.getSimpleValueType();
30800   MVT DstVT = Op.getSimpleValueType();
30801 
30802   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
30803   // half to v32i1 and concatenating the result.
30804   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
30805     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
30806     assert(Subtarget.hasBWI() && "Expected BWI target");
30807     SDLoc dl(Op);
30808     SDValue Lo, Hi;
30809     std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::i32, MVT::i32);
30810     Lo = DAG.getBitcast(MVT::v32i1, Lo);
30811     Hi = DAG.getBitcast(MVT::v32i1, Hi);
30812     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
30813   }
30814 
30815   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
30816   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
30817     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
30818     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
30819     SDLoc DL(Op);
30820     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
30821     V = getPMOVMSKB(DL, V, DAG, Subtarget);
30822     return DAG.getZExtOrTrunc(V, DL, DstVT);
30823   }
30824 
30825   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
30826           SrcVT == MVT::i64) && "Unexpected VT!");
30827 
30828   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30829   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
30830       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
30831     // This conversion needs to be expanded.
30832     return SDValue();
30833 
30834   SDLoc dl(Op);
30835   if (SrcVT.isVector()) {
30836     // Widen the vector in input in the case of MVT::v2i32.
30837     // Example: from MVT::v2i32 to MVT::v4i32.
30838     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
30839                                  SrcVT.getVectorNumElements() * 2);
30840     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
30841                       DAG.getUNDEF(SrcVT));
30842   } else {
30843     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
30844            "Unexpected source type in LowerBITCAST");
30845     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
30846   }
30847 
30848   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
30849   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
30850 
30851   if (DstVT == MVT::x86mmx)
30852     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
30853 
30854   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
30855                      DAG.getIntPtrConstant(0, dl));
30856 }
30857 
30858 /// Compute the horizontal sum of bytes in V for the elements of VT.
30859 ///
30860 /// Requires V to be a byte vector and VT to be an integer vector type with
30861 /// wider elements than V's type. The width of the elements of VT determines
30862 /// how many bytes of V are summed horizontally to produce each element of the
30863 /// result.
LowerHorizontalByteSum(SDValue V,MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG)30864 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
30865                                       const X86Subtarget &Subtarget,
30866                                       SelectionDAG &DAG) {
30867   SDLoc DL(V);
30868   MVT ByteVecVT = V.getSimpleValueType();
30869   MVT EltVT = VT.getVectorElementType();
30870   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
30871          "Expected value to have byte element type.");
30872   assert(EltVT != MVT::i8 &&
30873          "Horizontal byte sum only makes sense for wider elements!");
30874   unsigned VecSize = VT.getSizeInBits();
30875   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
30876 
30877   // PSADBW instruction horizontally add all bytes and leave the result in i64
30878   // chunks, thus directly computes the pop count for v2i64 and v4i64.
30879   if (EltVT == MVT::i64) {
30880     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
30881     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
30882     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
30883     return DAG.getBitcast(VT, V);
30884   }
30885 
30886   if (EltVT == MVT::i32) {
30887     // We unpack the low half and high half into i32s interleaved with zeros so
30888     // that we can use PSADBW to horizontally sum them. The most useful part of
30889     // this is that it lines up the results of two PSADBW instructions to be
30890     // two v2i64 vectors which concatenated are the 4 population counts. We can
30891     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
30892     SDValue Zeros = DAG.getConstant(0, DL, VT);
30893     SDValue V32 = DAG.getBitcast(VT, V);
30894     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
30895     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
30896 
30897     // Do the horizontal sums into two v2i64s.
30898     Zeros = DAG.getConstant(0, DL, ByteVecVT);
30899     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
30900     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
30901                       DAG.getBitcast(ByteVecVT, Low), Zeros);
30902     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
30903                        DAG.getBitcast(ByteVecVT, High), Zeros);
30904 
30905     // Merge them together.
30906     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
30907     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
30908                     DAG.getBitcast(ShortVecVT, Low),
30909                     DAG.getBitcast(ShortVecVT, High));
30910 
30911     return DAG.getBitcast(VT, V);
30912   }
30913 
30914   // The only element type left is i16.
30915   assert(EltVT == MVT::i16 && "Unknown how to handle type");
30916 
30917   // To obtain pop count for each i16 element starting from the pop count for
30918   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
30919   // right by 8. It is important to shift as i16s as i8 vector shift isn't
30920   // directly supported.
30921   SDValue ShifterV = DAG.getConstant(8, DL, VT);
30922   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
30923   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
30924                   DAG.getBitcast(ByteVecVT, V));
30925   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
30926 }
30927 
LowerVectorCTPOPInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)30928 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
30929                                         const X86Subtarget &Subtarget,
30930                                         SelectionDAG &DAG) {
30931   MVT VT = Op.getSimpleValueType();
30932   MVT EltVT = VT.getVectorElementType();
30933   int NumElts = VT.getVectorNumElements();
30934   (void)EltVT;
30935   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
30936 
30937   // Implement a lookup table in register by using an algorithm based on:
30938   // http://wm.ite.pl/articles/sse-popcount.html
30939   //
30940   // The general idea is that every lower byte nibble in the input vector is an
30941   // index into a in-register pre-computed pop count table. We then split up the
30942   // input vector in two new ones: (1) a vector with only the shifted-right
30943   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
30944   // masked out higher ones) for each byte. PSHUFB is used separately with both
30945   // to index the in-register table. Next, both are added and the result is a
30946   // i8 vector where each element contains the pop count for input byte.
30947   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
30948                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
30949                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
30950                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
30951 
30952   SmallVector<SDValue, 64> LUTVec;
30953   for (int i = 0; i < NumElts; ++i)
30954     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
30955   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
30956   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
30957 
30958   // High nibbles
30959   SDValue FourV = DAG.getConstant(4, DL, VT);
30960   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
30961 
30962   // Low nibbles
30963   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
30964 
30965   // The input vector is used as the shuffle mask that index elements into the
30966   // LUT. After counting low and high nibbles, add the vector to obtain the
30967   // final pop count per i8 element.
30968   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
30969   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
30970   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
30971 }
30972 
30973 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
30974 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
LowerVectorCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)30975 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
30976                                 SelectionDAG &DAG) {
30977   MVT VT = Op.getSimpleValueType();
30978   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
30979          "Unknown CTPOP type to handle");
30980   SDLoc DL(Op.getNode());
30981   SDValue Op0 = Op.getOperand(0);
30982 
30983   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
30984   if (Subtarget.hasVPOPCNTDQ()) {
30985     unsigned NumElems = VT.getVectorNumElements();
30986     assert((VT.getVectorElementType() == MVT::i8 ||
30987             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
30988     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
30989       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
30990       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
30991       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
30992       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
30993     }
30994   }
30995 
30996   // Decompose 256-bit ops into smaller 128-bit ops.
30997   if (VT.is256BitVector() && !Subtarget.hasInt256())
30998     return splitVectorIntUnary(Op, DAG);
30999 
31000   // Decompose 512-bit ops into smaller 256-bit ops.
31001   if (VT.is512BitVector() && !Subtarget.hasBWI())
31002     return splitVectorIntUnary(Op, DAG);
31003 
31004   // For element types greater than i8, do vXi8 pop counts and a bytesum.
31005   if (VT.getScalarType() != MVT::i8) {
31006     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
31007     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
31008     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
31009     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
31010   }
31011 
31012   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
31013   if (!Subtarget.hasSSSE3())
31014     return SDValue();
31015 
31016   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
31017 }
31018 
LowerCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31019 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
31020                           SelectionDAG &DAG) {
31021   assert(Op.getSimpleValueType().isVector() &&
31022          "We only do custom lowering for vector population count.");
31023   return LowerVectorCTPOP(Op, Subtarget, DAG);
31024 }
31025 
LowerBITREVERSE_XOP(SDValue Op,SelectionDAG & DAG)31026 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
31027   MVT VT = Op.getSimpleValueType();
31028   SDValue In = Op.getOperand(0);
31029   SDLoc DL(Op);
31030 
31031   // For scalars, its still beneficial to transfer to/from the SIMD unit to
31032   // perform the BITREVERSE.
31033   if (!VT.isVector()) {
31034     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
31035     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
31036     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
31037     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
31038                        DAG.getIntPtrConstant(0, DL));
31039   }
31040 
31041   int NumElts = VT.getVectorNumElements();
31042   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
31043 
31044   // Decompose 256-bit ops into smaller 128-bit ops.
31045   if (VT.is256BitVector())
31046     return splitVectorIntUnary(Op, DAG);
31047 
31048   assert(VT.is128BitVector() &&
31049          "Only 128-bit vector bitreverse lowering supported.");
31050 
31051   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
31052   // perform the BSWAP in the shuffle.
31053   // Its best to shuffle using the second operand as this will implicitly allow
31054   // memory folding for multiple vectors.
31055   SmallVector<SDValue, 16> MaskElts;
31056   for (int i = 0; i != NumElts; ++i) {
31057     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
31058       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
31059       int PermuteByte = SourceByte | (2 << 5);
31060       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
31061     }
31062   }
31063 
31064   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
31065   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
31066   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
31067                     Res, Mask);
31068   return DAG.getBitcast(VT, Res);
31069 }
31070 
LowerBITREVERSE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31071 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
31072                                SelectionDAG &DAG) {
31073   MVT VT = Op.getSimpleValueType();
31074 
31075   if (Subtarget.hasXOP() && !VT.is512BitVector())
31076     return LowerBITREVERSE_XOP(Op, DAG);
31077 
31078   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
31079 
31080   SDValue In = Op.getOperand(0);
31081   SDLoc DL(Op);
31082 
31083   assert(VT.getScalarType() == MVT::i8 &&
31084          "Only byte vector BITREVERSE supported");
31085 
31086   // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
31087   if (VT == MVT::v64i8 && !Subtarget.hasBWI())
31088     return splitVectorIntUnary(Op, DAG);
31089 
31090   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
31091   if (VT == MVT::v32i8 && !Subtarget.hasInt256())
31092     return splitVectorIntUnary(Op, DAG);
31093 
31094   unsigned NumElts = VT.getVectorNumElements();
31095 
31096   // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
31097   if (Subtarget.hasGFNI()) {
31098     MVT MatrixVT = MVT::getVectorVT(MVT::i64, NumElts / 8);
31099     SDValue Matrix = DAG.getConstant(0x8040201008040201ULL, DL, MatrixVT);
31100     Matrix = DAG.getBitcast(VT, Matrix);
31101     return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
31102                        DAG.getTargetConstant(0, DL, MVT::i8));
31103   }
31104 
31105   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
31106   // two nibbles and a PSHUFB lookup to find the bitreverse of each
31107   // 0-15 value (moved to the other nibble).
31108   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
31109   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
31110   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
31111 
31112   const int LoLUT[16] = {
31113       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
31114       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
31115       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
31116       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
31117   const int HiLUT[16] = {
31118       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
31119       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
31120       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
31121       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
31122 
31123   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
31124   for (unsigned i = 0; i < NumElts; ++i) {
31125     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
31126     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
31127   }
31128 
31129   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
31130   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
31131   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
31132   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
31133   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
31134 }
31135 
LowerPARITY(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31136 static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
31137                            SelectionDAG &DAG) {
31138   SDLoc DL(Op);
31139   SDValue X = Op.getOperand(0);
31140   MVT VT = Op.getSimpleValueType();
31141 
31142   // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
31143   if (VT == MVT::i8 ||
31144       DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
31145     X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
31146     SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
31147                                 DAG.getConstant(0, DL, MVT::i8));
31148     // Copy the inverse of the parity flag into a register with setcc.
31149     SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
31150     // Extend to the original type.
31151     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
31152   }
31153 
31154   // If we have POPCNT, use the default expansion.
31155   if (Subtarget.hasPOPCNT())
31156     return SDValue();
31157 
31158   if (VT == MVT::i64) {
31159     // Xor the high and low 16-bits together using a 32-bit operation.
31160     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
31161                              DAG.getNode(ISD::SRL, DL, MVT::i64, X,
31162                                          DAG.getConstant(32, DL, MVT::i8)));
31163     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
31164     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
31165   }
31166 
31167   if (VT != MVT::i16) {
31168     // Xor the high and low 16-bits together using a 32-bit operation.
31169     SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
31170                                DAG.getConstant(16, DL, MVT::i8));
31171     X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
31172   } else {
31173     // If the input is 16-bits, we need to extend to use an i32 shift below.
31174     X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
31175   }
31176 
31177   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
31178   // This should allow an h-reg to be used to save a shift.
31179   SDValue Hi = DAG.getNode(
31180       ISD::TRUNCATE, DL, MVT::i8,
31181       DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
31182   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
31183   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
31184   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
31185 
31186   // Copy the inverse of the parity flag into a register with setcc.
31187   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
31188   // Extend to the original type.
31189   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
31190 }
31191 
lowerAtomicArithWithLOCK(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)31192 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
31193                                         const X86Subtarget &Subtarget) {
31194   unsigned NewOpc = 0;
31195   switch (N->getOpcode()) {
31196   case ISD::ATOMIC_LOAD_ADD:
31197     NewOpc = X86ISD::LADD;
31198     break;
31199   case ISD::ATOMIC_LOAD_SUB:
31200     NewOpc = X86ISD::LSUB;
31201     break;
31202   case ISD::ATOMIC_LOAD_OR:
31203     NewOpc = X86ISD::LOR;
31204     break;
31205   case ISD::ATOMIC_LOAD_XOR:
31206     NewOpc = X86ISD::LXOR;
31207     break;
31208   case ISD::ATOMIC_LOAD_AND:
31209     NewOpc = X86ISD::LAND;
31210     break;
31211   default:
31212     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
31213   }
31214 
31215   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
31216 
31217   return DAG.getMemIntrinsicNode(
31218       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
31219       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
31220       /*MemVT=*/N->getSimpleValueType(0), MMO);
31221 }
31222 
31223 /// Lower atomic_load_ops into LOCK-prefixed operations.
lowerAtomicArith(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)31224 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
31225                                 const X86Subtarget &Subtarget) {
31226   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
31227   SDValue Chain = N->getOperand(0);
31228   SDValue LHS = N->getOperand(1);
31229   SDValue RHS = N->getOperand(2);
31230   unsigned Opc = N->getOpcode();
31231   MVT VT = N->getSimpleValueType(0);
31232   SDLoc DL(N);
31233 
31234   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
31235   // can only be lowered when the result is unused.  They should have already
31236   // been transformed into a cmpxchg loop in AtomicExpand.
31237   if (N->hasAnyUseOfValue(0)) {
31238     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
31239     // select LXADD if LOCK_SUB can't be selected.
31240     // Handle (atomic_load_xor p, SignBit) as (atomic_load_add p, SignBit) so we
31241     // can use LXADD as opposed to cmpxchg.
31242     if (Opc == ISD::ATOMIC_LOAD_SUB ||
31243         (Opc == ISD::ATOMIC_LOAD_XOR && isMinSignedConstant(RHS))) {
31244       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
31245       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS, RHS,
31246                            AN->getMemOperand());
31247     }
31248     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
31249            "Used AtomicRMW ops other than Add should have been expanded!");
31250     return N;
31251   }
31252 
31253   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
31254   // The core idea here is that since the memory location isn't actually
31255   // changing, all we need is a lowering for the *ordering* impacts of the
31256   // atomicrmw.  As such, we can chose a different operation and memory
31257   // location to minimize impact on other code.
31258   // The above holds unless the node is marked volatile in which
31259   // case it needs to be preserved according to the langref.
31260   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS) && !AN->isVolatile()) {
31261     // On X86, the only ordering which actually requires an instruction is
31262     // seq_cst which isn't SingleThread, everything just needs to be preserved
31263     // during codegen and then dropped. Note that we expect (but don't assume),
31264     // that orderings other than seq_cst and acq_rel have been canonicalized to
31265     // a store or load.
31266     if (AN->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent &&
31267         AN->getSyncScopeID() == SyncScope::System) {
31268       // Prefer a locked operation against a stack location to minimize cache
31269       // traffic.  This assumes that stack locations are very likely to be
31270       // accessed only by the owning thread.
31271       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
31272       assert(!N->hasAnyUseOfValue(0));
31273       // NOTE: The getUNDEF is needed to give something for the unused result 0.
31274       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
31275                          DAG.getUNDEF(VT), NewChain);
31276     }
31277     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
31278     SDValue NewChain = DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Chain);
31279     assert(!N->hasAnyUseOfValue(0));
31280     // NOTE: The getUNDEF is needed to give something for the unused result 0.
31281     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
31282                        DAG.getUNDEF(VT), NewChain);
31283   }
31284 
31285   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
31286   // RAUW the chain, but don't worry about the result, as it's unused.
31287   assert(!N->hasAnyUseOfValue(0));
31288   // NOTE: The getUNDEF is needed to give something for the unused result 0.
31289   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
31290                      DAG.getUNDEF(VT), LockOp.getValue(1));
31291 }
31292 
LowerATOMIC_STORE(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)31293 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
31294                                  const X86Subtarget &Subtarget) {
31295   auto *Node = cast<AtomicSDNode>(Op.getNode());
31296   SDLoc dl(Node);
31297   EVT VT = Node->getMemoryVT();
31298 
31299   bool IsSeqCst =
31300       Node->getSuccessOrdering() == AtomicOrdering::SequentiallyConsistent;
31301   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
31302 
31303   // If this store is not sequentially consistent and the type is legal
31304   // we can just keep it.
31305   if (!IsSeqCst && IsTypeLegal)
31306     return Op;
31307 
31308   if (VT == MVT::i64 && !IsTypeLegal) {
31309     // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
31310     // is enabled.
31311     bool NoImplicitFloatOps =
31312         DAG.getMachineFunction().getFunction().hasFnAttribute(
31313             Attribute::NoImplicitFloat);
31314     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
31315       SDValue Chain;
31316       if (Subtarget.hasSSE1()) {
31317         SDValue SclToVec =
31318             DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Node->getVal());
31319         MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
31320         SclToVec = DAG.getBitcast(StVT, SclToVec);
31321         SDVTList Tys = DAG.getVTList(MVT::Other);
31322         SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
31323         Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
31324                                         MVT::i64, Node->getMemOperand());
31325       } else if (Subtarget.hasX87()) {
31326         // First load this into an 80-bit X87 register using a stack temporary.
31327         // This will put the whole integer into the significand.
31328         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
31329         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
31330         MachinePointerInfo MPI =
31331             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
31332         Chain = DAG.getStore(Node->getChain(), dl, Node->getVal(), StackPtr,
31333                              MPI, MaybeAlign(), MachineMemOperand::MOStore);
31334         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
31335         SDValue LdOps[] = {Chain, StackPtr};
31336         SDValue Value = DAG.getMemIntrinsicNode(
31337             X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
31338             /*Align*/ std::nullopt, MachineMemOperand::MOLoad);
31339         Chain = Value.getValue(1);
31340 
31341         // Now use an FIST to do the atomic store.
31342         SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
31343         Chain =
31344             DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
31345                                     StoreOps, MVT::i64, Node->getMemOperand());
31346       }
31347 
31348       if (Chain) {
31349         // If this is a sequentially consistent store, also emit an appropriate
31350         // barrier.
31351         if (IsSeqCst)
31352           Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
31353 
31354         return Chain;
31355       }
31356     }
31357   }
31358 
31359   // Convert seq_cst store -> xchg
31360   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
31361   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
31362   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl, Node->getMemoryVT(),
31363                                Node->getOperand(0), Node->getOperand(2),
31364                                Node->getOperand(1), Node->getMemOperand());
31365   return Swap.getValue(1);
31366 }
31367 
LowerADDSUBO_CARRY(SDValue Op,SelectionDAG & DAG)31368 static SDValue LowerADDSUBO_CARRY(SDValue Op, SelectionDAG &DAG) {
31369   SDNode *N = Op.getNode();
31370   MVT VT = N->getSimpleValueType(0);
31371   unsigned Opc = Op.getOpcode();
31372 
31373   // Let legalize expand this if it isn't a legal type yet.
31374   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
31375     return SDValue();
31376 
31377   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
31378   SDLoc DL(N);
31379 
31380   // Set the carry flag.
31381   SDValue Carry = Op.getOperand(2);
31382   EVT CarryVT = Carry.getValueType();
31383   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
31384                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
31385 
31386   bool IsAdd = Opc == ISD::UADDO_CARRY || Opc == ISD::SADDO_CARRY;
31387   SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
31388                             Op.getOperand(0), Op.getOperand(1),
31389                             Carry.getValue(1));
31390 
31391   bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
31392   SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
31393                            Sum.getValue(1), DL, DAG);
31394   if (N->getValueType(1) == MVT::i1)
31395     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
31396 
31397   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
31398 }
31399 
LowerFSINCOS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31400 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
31401                             SelectionDAG &DAG) {
31402   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
31403 
31404   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
31405   // which returns the values as { float, float } (in XMM0) or
31406   // { double, double } (which is returned in XMM0, XMM1).
31407   SDLoc dl(Op);
31408   SDValue Arg = Op.getOperand(0);
31409   EVT ArgVT = Arg.getValueType();
31410   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
31411 
31412   TargetLowering::ArgListTy Args;
31413   TargetLowering::ArgListEntry Entry;
31414 
31415   Entry.Node = Arg;
31416   Entry.Ty = ArgTy;
31417   Entry.IsSExt = false;
31418   Entry.IsZExt = false;
31419   Args.push_back(Entry);
31420 
31421   bool isF64 = ArgVT == MVT::f64;
31422   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
31423   // the small struct {f32, f32} is returned in (eax, edx). For f64,
31424   // the results are returned via SRet in memory.
31425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31426   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
31427   const char *LibcallName = TLI.getLibcallName(LC);
31428   SDValue Callee =
31429       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
31430 
31431   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
31432                       : (Type *)FixedVectorType::get(ArgTy, 4);
31433 
31434   TargetLowering::CallLoweringInfo CLI(DAG);
31435   CLI.setDebugLoc(dl)
31436       .setChain(DAG.getEntryNode())
31437       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
31438 
31439   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
31440 
31441   if (isF64)
31442     // Returned in xmm0 and xmm1.
31443     return CallResult.first;
31444 
31445   // Returned in bits 0:31 and 32:64 xmm0.
31446   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
31447                                CallResult.first, DAG.getIntPtrConstant(0, dl));
31448   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
31449                                CallResult.first, DAG.getIntPtrConstant(1, dl));
31450   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
31451   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
31452 }
31453 
31454 /// Widen a vector input to a vector of NVT.  The
31455 /// input vector must have the same element type as NVT.
ExtendToType(SDValue InOp,MVT NVT,SelectionDAG & DAG,bool FillWithZeroes=false)31456 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
31457                             bool FillWithZeroes = false) {
31458   // Check if InOp already has the right width.
31459   MVT InVT = InOp.getSimpleValueType();
31460   if (InVT == NVT)
31461     return InOp;
31462 
31463   if (InOp.isUndef())
31464     return DAG.getUNDEF(NVT);
31465 
31466   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
31467          "input and widen element type must match");
31468 
31469   unsigned InNumElts = InVT.getVectorNumElements();
31470   unsigned WidenNumElts = NVT.getVectorNumElements();
31471   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
31472          "Unexpected request for vector widening");
31473 
31474   SDLoc dl(InOp);
31475   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
31476       InOp.getNumOperands() == 2) {
31477     SDValue N1 = InOp.getOperand(1);
31478     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
31479         N1.isUndef()) {
31480       InOp = InOp.getOperand(0);
31481       InVT = InOp.getSimpleValueType();
31482       InNumElts = InVT.getVectorNumElements();
31483     }
31484   }
31485   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
31486       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
31487     SmallVector<SDValue, 16> Ops;
31488     for (unsigned i = 0; i < InNumElts; ++i)
31489       Ops.push_back(InOp.getOperand(i));
31490 
31491     EVT EltVT = InOp.getOperand(0).getValueType();
31492 
31493     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
31494       DAG.getUNDEF(EltVT);
31495     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
31496       Ops.push_back(FillVal);
31497     return DAG.getBuildVector(NVT, dl, Ops);
31498   }
31499   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
31500     DAG.getUNDEF(NVT);
31501   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
31502                      InOp, DAG.getIntPtrConstant(0, dl));
31503 }
31504 
LowerMSCATTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31505 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
31506                              SelectionDAG &DAG) {
31507   assert(Subtarget.hasAVX512() &&
31508          "MGATHER/MSCATTER are supported on AVX-512 arch only");
31509 
31510   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
31511   SDValue Src = N->getValue();
31512   MVT VT = Src.getSimpleValueType();
31513   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
31514   SDLoc dl(Op);
31515 
31516   SDValue Scale = N->getScale();
31517   SDValue Index = N->getIndex();
31518   SDValue Mask = N->getMask();
31519   SDValue Chain = N->getChain();
31520   SDValue BasePtr = N->getBasePtr();
31521 
31522   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
31523     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
31524     // If the index is v2i64 and we have VLX we can use xmm for data and index.
31525     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
31526       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
31527       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
31528       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
31529       SDVTList VTs = DAG.getVTList(MVT::Other);
31530       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
31531       return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
31532                                      N->getMemoryVT(), N->getMemOperand());
31533     }
31534     return SDValue();
31535   }
31536 
31537   MVT IndexVT = Index.getSimpleValueType();
31538 
31539   // If the index is v2i32, we're being called by type legalization and we
31540   // should just let the default handling take care of it.
31541   if (IndexVT == MVT::v2i32)
31542     return SDValue();
31543 
31544   // If we don't have VLX and neither the passthru or index is 512-bits, we
31545   // need to widen until one is.
31546   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
31547       !Index.getSimpleValueType().is512BitVector()) {
31548     // Determine how much we need to widen by to get a 512-bit type.
31549     unsigned Factor = std::min(512/VT.getSizeInBits(),
31550                                512/IndexVT.getSizeInBits());
31551     unsigned NumElts = VT.getVectorNumElements() * Factor;
31552 
31553     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
31554     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
31555     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
31556 
31557     Src = ExtendToType(Src, VT, DAG);
31558     Index = ExtendToType(Index, IndexVT, DAG);
31559     Mask = ExtendToType(Mask, MaskVT, DAG, true);
31560   }
31561 
31562   SDVTList VTs = DAG.getVTList(MVT::Other);
31563   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
31564   return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
31565                                  N->getMemoryVT(), N->getMemOperand());
31566 }
31567 
LowerMLOAD(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31568 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
31569                           SelectionDAG &DAG) {
31570 
31571   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
31572   MVT VT = Op.getSimpleValueType();
31573   MVT ScalarVT = VT.getScalarType();
31574   SDValue Mask = N->getMask();
31575   MVT MaskVT = Mask.getSimpleValueType();
31576   SDValue PassThru = N->getPassThru();
31577   SDLoc dl(Op);
31578 
31579   // Handle AVX masked loads which don't support passthru other than 0.
31580   if (MaskVT.getVectorElementType() != MVT::i1) {
31581     // We also allow undef in the isel pattern.
31582     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
31583       return Op;
31584 
31585     SDValue NewLoad = DAG.getMaskedLoad(
31586         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
31587         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
31588         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
31589         N->isExpandingLoad());
31590     // Emit a blend.
31591     SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
31592     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
31593   }
31594 
31595   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
31596          "Expanding masked load is supported on AVX-512 target only!");
31597 
31598   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
31599          "Expanding masked load is supported for 32 and 64-bit types only!");
31600 
31601   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
31602          "Cannot lower masked load op.");
31603 
31604   assert((ScalarVT.getSizeInBits() >= 32 ||
31605           (Subtarget.hasBWI() &&
31606               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
31607          "Unsupported masked load op.");
31608 
31609   // This operation is legal for targets with VLX, but without
31610   // VLX the vector should be widened to 512 bit
31611   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
31612   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
31613   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
31614 
31615   // Mask element has to be i1.
31616   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
31617          "Unexpected mask type");
31618 
31619   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
31620 
31621   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
31622   SDValue NewLoad = DAG.getMaskedLoad(
31623       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
31624       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
31625       N->getExtensionType(), N->isExpandingLoad());
31626 
31627   SDValue Extract =
31628       DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
31629                   DAG.getIntPtrConstant(0, dl));
31630   SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
31631   return DAG.getMergeValues(RetOps, dl);
31632 }
31633 
LowerMSTORE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31634 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
31635                            SelectionDAG &DAG) {
31636   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
31637   SDValue DataToStore = N->getValue();
31638   MVT VT = DataToStore.getSimpleValueType();
31639   MVT ScalarVT = VT.getScalarType();
31640   SDValue Mask = N->getMask();
31641   SDLoc dl(Op);
31642 
31643   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
31644          "Expanding masked load is supported on AVX-512 target only!");
31645 
31646   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
31647          "Expanding masked load is supported for 32 and 64-bit types only!");
31648 
31649   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
31650          "Cannot lower masked store op.");
31651 
31652   assert((ScalarVT.getSizeInBits() >= 32 ||
31653           (Subtarget.hasBWI() &&
31654               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
31655           "Unsupported masked store op.");
31656 
31657   // This operation is legal for targets with VLX, but without
31658   // VLX the vector should be widened to 512 bit
31659   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
31660   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
31661 
31662   // Mask element has to be i1.
31663   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
31664          "Unexpected mask type");
31665 
31666   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
31667 
31668   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
31669   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
31670   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
31671                             N->getOffset(), Mask, N->getMemoryVT(),
31672                             N->getMemOperand(), N->getAddressingMode(),
31673                             N->isTruncatingStore(), N->isCompressingStore());
31674 }
31675 
LowerMGATHER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31676 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
31677                             SelectionDAG &DAG) {
31678   assert(Subtarget.hasAVX2() &&
31679          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
31680 
31681   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
31682   SDLoc dl(Op);
31683   MVT VT = Op.getSimpleValueType();
31684   SDValue Index = N->getIndex();
31685   SDValue Mask = N->getMask();
31686   SDValue PassThru = N->getPassThru();
31687   MVT IndexVT = Index.getSimpleValueType();
31688 
31689   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
31690 
31691   // If the index is v2i32, we're being called by type legalization.
31692   if (IndexVT == MVT::v2i32)
31693     return SDValue();
31694 
31695   // If we don't have VLX and neither the passthru or index is 512-bits, we
31696   // need to widen until one is.
31697   MVT OrigVT = VT;
31698   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
31699       !IndexVT.is512BitVector()) {
31700     // Determine how much we need to widen by to get a 512-bit type.
31701     unsigned Factor = std::min(512/VT.getSizeInBits(),
31702                                512/IndexVT.getSizeInBits());
31703 
31704     unsigned NumElts = VT.getVectorNumElements() * Factor;
31705 
31706     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
31707     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
31708     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
31709 
31710     PassThru = ExtendToType(PassThru, VT, DAG);
31711     Index = ExtendToType(Index, IndexVT, DAG);
31712     Mask = ExtendToType(Mask, MaskVT, DAG, true);
31713   }
31714 
31715   // Break dependency on the data register.
31716   if (PassThru.isUndef())
31717     PassThru = getZeroVector(VT, Subtarget, DAG, dl);
31718 
31719   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
31720                     N->getScale() };
31721   SDValue NewGather = DAG.getMemIntrinsicNode(
31722       X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
31723       N->getMemOperand());
31724   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
31725                                 NewGather, DAG.getIntPtrConstant(0, dl));
31726   return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
31727 }
31728 
LowerADDRSPACECAST(SDValue Op,SelectionDAG & DAG)31729 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
31730   SDLoc dl(Op);
31731   SDValue Src = Op.getOperand(0);
31732   MVT DstVT = Op.getSimpleValueType();
31733 
31734   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
31735   unsigned SrcAS = N->getSrcAddressSpace();
31736 
31737   assert(SrcAS != N->getDestAddressSpace() &&
31738          "addrspacecast must be between different address spaces");
31739 
31740   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
31741     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
31742   } else if (DstVT == MVT::i64) {
31743     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
31744   } else if (DstVT == MVT::i32) {
31745     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
31746   } else {
31747     report_fatal_error("Bad address space in addrspacecast");
31748   }
31749   return Op;
31750 }
31751 
LowerGC_TRANSITION(SDValue Op,SelectionDAG & DAG) const31752 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
31753                                               SelectionDAG &DAG) const {
31754   // TODO: Eventually, the lowering of these nodes should be informed by or
31755   // deferred to the GC strategy for the function in which they appear. For
31756   // now, however, they must be lowered to something. Since they are logically
31757   // no-ops in the case of a null GC strategy (or a GC strategy which does not
31758   // require special handling for these nodes), lower them as literal NOOPs for
31759   // the time being.
31760   SmallVector<SDValue, 2> Ops;
31761   Ops.push_back(Op.getOperand(0));
31762   if (Op->getGluedNode())
31763     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
31764 
31765   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
31766   return SDValue(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
31767 }
31768 
31769 // Custom split CVTPS2PH with wide types.
LowerCVTPS2PH(SDValue Op,SelectionDAG & DAG)31770 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
31771   SDLoc dl(Op);
31772   EVT VT = Op.getValueType();
31773   SDValue Lo, Hi;
31774   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
31775   EVT LoVT, HiVT;
31776   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
31777   SDValue RC = Op.getOperand(1);
31778   Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
31779   Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
31780   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
31781 }
31782 
LowerPREFETCH(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)31783 static SDValue LowerPREFETCH(SDValue Op, const X86Subtarget &Subtarget,
31784                              SelectionDAG &DAG) {
31785   unsigned IsData = Op.getConstantOperandVal(4);
31786 
31787   // We don't support non-data prefetch without PREFETCHI.
31788   // Just preserve the chain.
31789   if (!IsData && !Subtarget.hasPREFETCHI())
31790     return Op.getOperand(0);
31791 
31792   return Op;
31793 }
31794 
getInstrStrFromOpNo(const SmallVectorImpl<StringRef> & AsmStrs,unsigned OpNo)31795 static StringRef getInstrStrFromOpNo(const SmallVectorImpl<StringRef> &AsmStrs,
31796                                      unsigned OpNo) {
31797   const APInt Operand(32, OpNo);
31798   std::string OpNoStr = llvm::toString(Operand, 10, false);
31799   std::string Str(" $");
31800 
31801   std::string OpNoStr1(Str + OpNoStr);             // e.g. " $1" (OpNo=1)
31802   std::string OpNoStr2(Str + "{" + OpNoStr + ":"); // With modifier, e.g. ${1:P}
31803 
31804   auto I = StringRef::npos;
31805   for (auto &AsmStr : AsmStrs) {
31806     // Match the OpNo string. We should match exactly to exclude match
31807     // sub-string, e.g. "$12" contain "$1"
31808     if (AsmStr.ends_with(OpNoStr1))
31809       I = AsmStr.size() - OpNoStr1.size();
31810 
31811     // Get the index of operand in AsmStr.
31812     if (I == StringRef::npos)
31813       I = AsmStr.find(OpNoStr1 + ",");
31814     if (I == StringRef::npos)
31815       I = AsmStr.find(OpNoStr2);
31816 
31817     if (I == StringRef::npos)
31818       continue;
31819 
31820     assert(I > 0 && "Unexpected inline asm string!");
31821     // Remove the operand string and label (if exsit).
31822     // For example:
31823     // ".L__MSASMLABEL_.${:uid}__l:call dword ptr ${0:P}"
31824     // ==>
31825     // ".L__MSASMLABEL_.${:uid}__l:call dword ptr "
31826     // ==>
31827     // "call dword ptr "
31828     auto TmpStr = AsmStr.substr(0, I);
31829     I = TmpStr.rfind(':');
31830     if (I != StringRef::npos)
31831       TmpStr = TmpStr.substr(I + 1);
31832     return TmpStr.take_while(llvm::isAlpha);
31833   }
31834 
31835   return StringRef();
31836 }
31837 
isInlineAsmTargetBranch(const SmallVectorImpl<StringRef> & AsmStrs,unsigned OpNo) const31838 bool X86TargetLowering::isInlineAsmTargetBranch(
31839     const SmallVectorImpl<StringRef> &AsmStrs, unsigned OpNo) const {
31840   // In a __asm block, __asm inst foo where inst is CALL or JMP should be
31841   // changed from indirect TargetLowering::C_Memory to direct
31842   // TargetLowering::C_Address.
31843   // We don't need to special case LOOP* and Jcc, which cannot target a memory
31844   // location.
31845   StringRef Inst = getInstrStrFromOpNo(AsmStrs, OpNo);
31846   return Inst.equals_insensitive("call") || Inst.equals_insensitive("jmp");
31847 }
31848 
31849 /// Provide custom lowering hooks for some operations.
LowerOperation(SDValue Op,SelectionDAG & DAG) const31850 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
31851   switch (Op.getOpcode()) {
31852   default: llvm_unreachable("Should not custom lower this!");
31853   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
31854   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
31855     return LowerCMP_SWAP(Op, Subtarget, DAG);
31856   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
31857   case ISD::ATOMIC_LOAD_ADD:
31858   case ISD::ATOMIC_LOAD_SUB:
31859   case ISD::ATOMIC_LOAD_OR:
31860   case ISD::ATOMIC_LOAD_XOR:
31861   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
31862   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
31863   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
31864   case ISD::PARITY:             return LowerPARITY(Op, Subtarget, DAG);
31865   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
31866   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
31867   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
31868   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
31869   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
31870   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
31871   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
31872   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
31873   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
31874   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
31875   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
31876   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
31877   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
31878   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
31879   case ISD::SHL_PARTS:
31880   case ISD::SRA_PARTS:
31881   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
31882   case ISD::FSHL:
31883   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
31884   case ISD::STRICT_SINT_TO_FP:
31885   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
31886   case ISD::STRICT_UINT_TO_FP:
31887   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
31888   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
31889   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
31890   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
31891   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
31892   case ISD::ZERO_EXTEND_VECTOR_INREG:
31893   case ISD::SIGN_EXTEND_VECTOR_INREG:
31894     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
31895   case ISD::FP_TO_SINT:
31896   case ISD::STRICT_FP_TO_SINT:
31897   case ISD::FP_TO_UINT:
31898   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
31899   case ISD::FP_TO_SINT_SAT:
31900   case ISD::FP_TO_UINT_SAT:     return LowerFP_TO_INT_SAT(Op, DAG);
31901   case ISD::FP_EXTEND:
31902   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
31903   case ISD::FP_ROUND:
31904   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
31905   case ISD::FP16_TO_FP:
31906   case ISD::STRICT_FP16_TO_FP:  return LowerFP16_TO_FP(Op, DAG);
31907   case ISD::FP_TO_FP16:
31908   case ISD::STRICT_FP_TO_FP16:  return LowerFP_TO_FP16(Op, DAG);
31909   case ISD::FP_TO_BF16:         return LowerFP_TO_BF16(Op, DAG);
31910   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
31911   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
31912   case ISD::FADD:
31913   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
31914   case ISD::FROUND:             return LowerFROUND(Op, DAG);
31915   case ISD::FABS:
31916   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
31917   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
31918   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
31919   case ISD::LRINT:
31920   case ISD::LLRINT:             return LowerLRINT_LLRINT(Op, DAG);
31921   case ISD::SETCC:
31922   case ISD::STRICT_FSETCC:
31923   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
31924   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
31925   case ISD::SELECT:             return LowerSELECT(Op, DAG);
31926   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
31927   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
31928   case ISD::VASTART:            return LowerVASTART(Op, DAG);
31929   case ISD::VAARG:              return LowerVAARG(Op, DAG);
31930   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
31931   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
31932   case ISD::INTRINSIC_VOID:
31933   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
31934   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
31935   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
31936   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
31937   case ISD::FRAME_TO_ARGS_OFFSET:
31938                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
31939   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
31940   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
31941   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
31942   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
31943   case ISD::EH_SJLJ_SETUP_DISPATCH:
31944     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
31945   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
31946   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
31947   case ISD::GET_ROUNDING:       return LowerGET_ROUNDING(Op, DAG);
31948   case ISD::SET_ROUNDING:       return LowerSET_ROUNDING(Op, DAG);
31949   case ISD::GET_FPENV_MEM:      return LowerGET_FPENV_MEM(Op, DAG);
31950   case ISD::SET_FPENV_MEM:      return LowerSET_FPENV_MEM(Op, DAG);
31951   case ISD::RESET_FPENV:        return LowerRESET_FPENV(Op, DAG);
31952   case ISD::CTLZ:
31953   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
31954   case ISD::CTTZ:
31955   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
31956   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
31957   case ISD::MULHS:
31958   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
31959   case ISD::ROTL:
31960   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
31961   case ISD::SRA:
31962   case ISD::SRL:
31963   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
31964   case ISD::SADDO:
31965   case ISD::UADDO:
31966   case ISD::SSUBO:
31967   case ISD::USUBO:              return LowerXALUO(Op, DAG);
31968   case ISD::SMULO:
31969   case ISD::UMULO:              return LowerMULO(Op, Subtarget, DAG);
31970   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
31971   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
31972   case ISD::SADDO_CARRY:
31973   case ISD::SSUBO_CARRY:
31974   case ISD::UADDO_CARRY:
31975   case ISD::USUBO_CARRY:        return LowerADDSUBO_CARRY(Op, DAG);
31976   case ISD::ADD:
31977   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
31978   case ISD::UADDSAT:
31979   case ISD::SADDSAT:
31980   case ISD::USUBSAT:
31981   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
31982   case ISD::SMAX:
31983   case ISD::SMIN:
31984   case ISD::UMAX:
31985   case ISD::UMIN:               return LowerMINMAX(Op, Subtarget, DAG);
31986   case ISD::FMINIMUM:
31987   case ISD::FMAXIMUM:
31988     return LowerFMINIMUM_FMAXIMUM(Op, Subtarget, DAG);
31989   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
31990   case ISD::ABDS:
31991   case ISD::ABDU:               return LowerABD(Op, Subtarget, DAG);
31992   case ISD::AVGCEILU:           return LowerAVG(Op, Subtarget, DAG);
31993   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
31994   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
31995   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
31996   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
31997   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
31998   case ISD::GC_TRANSITION_START:
31999   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
32000   case ISD::ADDRSPACECAST:      return LowerADDRSPACECAST(Op, DAG);
32001   case X86ISD::CVTPS2PH:        return LowerCVTPS2PH(Op, DAG);
32002   case ISD::PREFETCH:           return LowerPREFETCH(Op, Subtarget, DAG);
32003   }
32004 }
32005 
32006 /// Replace a node with an illegal result type with a new node built out of
32007 /// custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const32008 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
32009                                            SmallVectorImpl<SDValue>&Results,
32010                                            SelectionDAG &DAG) const {
32011   SDLoc dl(N);
32012   switch (N->getOpcode()) {
32013   default:
32014 #ifndef NDEBUG
32015     dbgs() << "ReplaceNodeResults: ";
32016     N->dump(&DAG);
32017 #endif
32018     llvm_unreachable("Do not know how to custom type legalize this operation!");
32019   case X86ISD::CVTPH2PS: {
32020     EVT VT = N->getValueType(0);
32021     SDValue Lo, Hi;
32022     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
32023     EVT LoVT, HiVT;
32024     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
32025     Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
32026     Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
32027     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32028     Results.push_back(Res);
32029     return;
32030   }
32031   case X86ISD::STRICT_CVTPH2PS: {
32032     EVT VT = N->getValueType(0);
32033     SDValue Lo, Hi;
32034     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
32035     EVT LoVT, HiVT;
32036     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
32037     Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
32038                      {N->getOperand(0), Lo});
32039     Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
32040                      {N->getOperand(0), Hi});
32041     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
32042                                 Lo.getValue(1), Hi.getValue(1));
32043     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32044     Results.push_back(Res);
32045     Results.push_back(Chain);
32046     return;
32047   }
32048   case X86ISD::CVTPS2PH:
32049     Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
32050     return;
32051   case ISD::CTPOP: {
32052     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
32053     // Use a v2i64 if possible.
32054     bool NoImplicitFloatOps =
32055         DAG.getMachineFunction().getFunction().hasFnAttribute(
32056             Attribute::NoImplicitFloat);
32057     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
32058       SDValue Wide =
32059           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
32060       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
32061       // Bit count should fit in 32-bits, extract it as that and then zero
32062       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
32063       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
32064       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
32065                          DAG.getIntPtrConstant(0, dl));
32066       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
32067       Results.push_back(Wide);
32068     }
32069     return;
32070   }
32071   case ISD::MUL: {
32072     EVT VT = N->getValueType(0);
32073     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32074            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
32075     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
32076     // elements are needed.
32077     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
32078     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
32079     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
32080     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
32081     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
32082     unsigned NumConcats = 16 / VT.getVectorNumElements();
32083     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
32084     ConcatOps[0] = Res;
32085     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
32086     Results.push_back(Res);
32087     return;
32088   }
32089   case ISD::SMULO:
32090   case ISD::UMULO: {
32091     EVT VT = N->getValueType(0);
32092     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32093            VT == MVT::v2i32 && "Unexpected VT!");
32094     bool IsSigned = N->getOpcode() == ISD::SMULO;
32095     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
32096     SDValue Op0 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(0));
32097     SDValue Op1 = DAG.getNode(ExtOpc, dl, MVT::v2i64, N->getOperand(1));
32098     SDValue Res = DAG.getNode(ISD::MUL, dl, MVT::v2i64, Op0, Op1);
32099     // Extract the high 32 bits from each result using PSHUFD.
32100     // TODO: Could use SRL+TRUNCATE but that doesn't become a PSHUFD.
32101     SDValue Hi = DAG.getBitcast(MVT::v4i32, Res);
32102     Hi = DAG.getVectorShuffle(MVT::v4i32, dl, Hi, Hi, {1, 3, -1, -1});
32103     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Hi,
32104                      DAG.getIntPtrConstant(0, dl));
32105 
32106     // Truncate the low bits of the result. This will become PSHUFD.
32107     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
32108 
32109     SDValue HiCmp;
32110     if (IsSigned) {
32111       // SMULO overflows if the high bits don't match the sign of the low.
32112       HiCmp = DAG.getNode(ISD::SRA, dl, VT, Res, DAG.getConstant(31, dl, VT));
32113     } else {
32114       // UMULO overflows if the high bits are non-zero.
32115       HiCmp = DAG.getConstant(0, dl, VT);
32116     }
32117     SDValue Ovf = DAG.getSetCC(dl, N->getValueType(1), Hi, HiCmp, ISD::SETNE);
32118 
32119     // Widen the result with by padding with undef.
32120     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
32121                       DAG.getUNDEF(VT));
32122     Results.push_back(Res);
32123     Results.push_back(Ovf);
32124     return;
32125   }
32126   case X86ISD::VPMADDWD: {
32127     // Legalize types for X86ISD::VPMADDWD by widening.
32128     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32129 
32130     EVT VT = N->getValueType(0);
32131     EVT InVT = N->getOperand(0).getValueType();
32132     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
32133            "Expected a VT that divides into 128 bits.");
32134     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32135            "Unexpected type action!");
32136     unsigned NumConcat = 128 / InVT.getSizeInBits();
32137 
32138     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
32139                                     InVT.getVectorElementType(),
32140                                     NumConcat * InVT.getVectorNumElements());
32141     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
32142                                   VT.getVectorElementType(),
32143                                   NumConcat * VT.getVectorNumElements());
32144 
32145     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
32146     Ops[0] = N->getOperand(0);
32147     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
32148     Ops[0] = N->getOperand(1);
32149     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
32150 
32151     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
32152     Results.push_back(Res);
32153     return;
32154   }
32155   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
32156   case X86ISD::FMINC:
32157   case X86ISD::FMIN:
32158   case X86ISD::FMAXC:
32159   case X86ISD::FMAX: {
32160     EVT VT = N->getValueType(0);
32161     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
32162     SDValue UNDEF = DAG.getUNDEF(VT);
32163     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
32164                               N->getOperand(0), UNDEF);
32165     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
32166                               N->getOperand(1), UNDEF);
32167     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
32168     return;
32169   }
32170   case ISD::SDIV:
32171   case ISD::UDIV:
32172   case ISD::SREM:
32173   case ISD::UREM: {
32174     EVT VT = N->getValueType(0);
32175     if (VT.isVector()) {
32176       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32177              "Unexpected type action!");
32178       // If this RHS is a constant splat vector we can widen this and let
32179       // division/remainder by constant optimize it.
32180       // TODO: Can we do something for non-splat?
32181       APInt SplatVal;
32182       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
32183         unsigned NumConcats = 128 / VT.getSizeInBits();
32184         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
32185         Ops0[0] = N->getOperand(0);
32186         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
32187         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
32188         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
32189         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
32190         Results.push_back(Res);
32191       }
32192       return;
32193     }
32194 
32195     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
32196     Results.push_back(V);
32197     return;
32198   }
32199   case ISD::TRUNCATE: {
32200     MVT VT = N->getSimpleValueType(0);
32201     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
32202       return;
32203 
32204     // The generic legalizer will try to widen the input type to the same
32205     // number of elements as the widened result type. But this isn't always
32206     // the best thing so do some custom legalization to avoid some cases.
32207     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
32208     SDValue In = N->getOperand(0);
32209     EVT InVT = In.getValueType();
32210     EVT InEltVT = InVT.getVectorElementType();
32211     EVT EltVT = VT.getVectorElementType();
32212     unsigned MinElts = VT.getVectorNumElements();
32213     unsigned WidenNumElts = WidenVT.getVectorNumElements();
32214     unsigned InBits = InVT.getSizeInBits();
32215 
32216     // See if there are sufficient leading bits to perform a PACKUS/PACKSS.
32217     unsigned PackOpcode;
32218     if (SDValue Src =
32219             matchTruncateWithPACK(PackOpcode, VT, In, dl, DAG, Subtarget)) {
32220       if (SDValue Res = truncateVectorWithPACK(PackOpcode, VT, Src,
32221                                                dl, DAG, Subtarget)) {
32222         Res = widenSubVector(WidenVT, Res, false, Subtarget, DAG, dl);
32223         Results.push_back(Res);
32224         return;
32225       }
32226     }
32227 
32228     if (128 % InBits == 0) {
32229       // 128 bit and smaller inputs should avoid truncate all together and
32230       // just use a build_vector that will become a shuffle.
32231       // TODO: Widen and use a shuffle directly?
32232       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
32233       // Use the original element count so we don't do more scalar opts than
32234       // necessary.
32235       for (unsigned i=0; i < MinElts; ++i) {
32236         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
32237                                   DAG.getIntPtrConstant(i, dl));
32238         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
32239       }
32240       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
32241       return;
32242     }
32243 
32244     // With AVX512 there are some cases that can use a target specific
32245     // truncate node to go from 256/512 to less than 128 with zeros in the
32246     // upper elements of the 128 bit result.
32247     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
32248       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
32249       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
32250         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
32251         return;
32252       }
32253       // There's one case we can widen to 512 bits and use VTRUNC.
32254       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
32255         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
32256                          DAG.getUNDEF(MVT::v4i64));
32257         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
32258         return;
32259       }
32260     }
32261     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
32262         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
32263         isTypeLegal(MVT::v4i64)) {
32264       // Input needs to be split and output needs to widened. Let's use two
32265       // VTRUNCs, and shuffle their results together into the wider type.
32266       SDValue Lo, Hi;
32267       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
32268 
32269       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
32270       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
32271       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
32272                                          { 0,  1,  2,  3, 16, 17, 18, 19,
32273                                           -1, -1, -1, -1, -1, -1, -1, -1 });
32274       Results.push_back(Res);
32275       return;
32276     }
32277 
32278     // Attempt to widen the truncation input vector to let LowerTRUNCATE handle
32279     // this via type legalization.
32280     if ((InEltVT == MVT::i16 || InEltVT == MVT::i32 || InEltVT == MVT::i64) &&
32281         (EltVT == MVT::i8 || EltVT == MVT::i16 || EltVT == MVT::i32) &&
32282         (!Subtarget.hasSSSE3() ||
32283          (!isTypeLegal(InVT) &&
32284           !(MinElts <= 4 && InEltVT == MVT::i64 && EltVT == MVT::i8)))) {
32285       SDValue WidenIn = widenSubVector(In, false, Subtarget, DAG, dl,
32286                                        InEltVT.getSizeInBits() * WidenNumElts);
32287       Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, WidenVT, WidenIn));
32288       return;
32289     }
32290 
32291     return;
32292   }
32293   case ISD::ANY_EXTEND:
32294     // Right now, only MVT::v8i8 has Custom action for an illegal type.
32295     // It's intended to custom handle the input type.
32296     assert(N->getValueType(0) == MVT::v8i8 &&
32297            "Do not know how to legalize this Node");
32298     return;
32299   case ISD::SIGN_EXTEND:
32300   case ISD::ZERO_EXTEND: {
32301     EVT VT = N->getValueType(0);
32302     SDValue In = N->getOperand(0);
32303     EVT InVT = In.getValueType();
32304     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
32305         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
32306       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
32307              "Unexpected type action!");
32308       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
32309       // Custom split this so we can extend i8/i16->i32 invec. This is better
32310       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
32311       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
32312       // we allow the sra from the extend to i32 to be shared by the split.
32313       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
32314 
32315       // Fill a vector with sign bits for each element.
32316       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
32317       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
32318 
32319       // Create an unpackl and unpackh to interleave the sign bits then bitcast
32320       // to v2i64.
32321       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
32322                                         {0, 4, 1, 5});
32323       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
32324       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
32325                                         {2, 6, 3, 7});
32326       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
32327 
32328       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32329       Results.push_back(Res);
32330       return;
32331     }
32332 
32333     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
32334       if (!InVT.is128BitVector()) {
32335         // Not a 128 bit vector, but maybe type legalization will promote
32336         // it to 128 bits.
32337         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
32338           return;
32339         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
32340         if (!InVT.is128BitVector())
32341           return;
32342 
32343         // Promote the input to 128 bits. Type legalization will turn this into
32344         // zext_inreg/sext_inreg.
32345         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
32346       }
32347 
32348       // Perform custom splitting instead of the two stage extend we would get
32349       // by default.
32350       EVT LoVT, HiVT;
32351       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
32352       assert(isTypeLegal(LoVT) && "Split VT not legal?");
32353 
32354       SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
32355 
32356       // We need to shift the input over by half the number of elements.
32357       unsigned NumElts = InVT.getVectorNumElements();
32358       unsigned HalfNumElts = NumElts / 2;
32359       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
32360       for (unsigned i = 0; i != HalfNumElts; ++i)
32361         ShufMask[i] = i + HalfNumElts;
32362 
32363       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
32364       Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
32365 
32366       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
32367       Results.push_back(Res);
32368     }
32369     return;
32370   }
32371   case ISD::FP_TO_SINT:
32372   case ISD::STRICT_FP_TO_SINT:
32373   case ISD::FP_TO_UINT:
32374   case ISD::STRICT_FP_TO_UINT: {
32375     bool IsStrict = N->isStrictFPOpcode();
32376     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
32377                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
32378     EVT VT = N->getValueType(0);
32379     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32380     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
32381     EVT SrcVT = Src.getValueType();
32382 
32383     SDValue Res;
32384     if (isSoftF16(SrcVT, Subtarget)) {
32385       EVT NVT = VT.isVector() ? VT.changeVectorElementType(MVT::f32) : MVT::f32;
32386       if (IsStrict) {
32387         Res =
32388             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
32389                         {Chain, DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
32390                                             {NVT, MVT::Other}, {Chain, Src})});
32391         Chain = Res.getValue(1);
32392       } else {
32393         Res = DAG.getNode(N->getOpcode(), dl, VT,
32394                           DAG.getNode(ISD::FP_EXTEND, dl, NVT, Src));
32395       }
32396       Results.push_back(Res);
32397       if (IsStrict)
32398         Results.push_back(Chain);
32399 
32400       return;
32401     }
32402 
32403     if (VT.isVector() && Subtarget.hasFP16() &&
32404         SrcVT.getVectorElementType() == MVT::f16) {
32405       EVT EleVT = VT.getVectorElementType();
32406       EVT ResVT = EleVT == MVT::i32 ? MVT::v4i32 : MVT::v8i16;
32407 
32408       if (SrcVT != MVT::v8f16) {
32409         SDValue Tmp =
32410             IsStrict ? DAG.getConstantFP(0.0, dl, SrcVT) : DAG.getUNDEF(SrcVT);
32411         SmallVector<SDValue, 4> Ops(SrcVT == MVT::v2f16 ? 4 : 2, Tmp);
32412         Ops[0] = Src;
32413         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f16, Ops);
32414       }
32415 
32416       if (IsStrict) {
32417         unsigned Opc =
32418             IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32419         Res =
32420             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {N->getOperand(0), Src});
32421         Chain = Res.getValue(1);
32422       } else {
32423         unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32424         Res = DAG.getNode(Opc, dl, ResVT, Src);
32425       }
32426 
32427       // TODO: Need to add exception check code for strict FP.
32428       if (EleVT.getSizeInBits() < 16) {
32429         MVT TmpVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8);
32430         Res = DAG.getNode(ISD::TRUNCATE, dl, TmpVT, Res);
32431 
32432         // Now widen to 128 bits.
32433         unsigned NumConcats = 128 / TmpVT.getSizeInBits();
32434         MVT ConcatVT = MVT::getVectorVT(EleVT.getSimpleVT(), 8 * NumConcats);
32435         SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(TmpVT));
32436         ConcatOps[0] = Res;
32437         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
32438       }
32439 
32440       Results.push_back(Res);
32441       if (IsStrict)
32442         Results.push_back(Chain);
32443 
32444       return;
32445     }
32446 
32447     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
32448       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32449              "Unexpected type action!");
32450 
32451       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
32452       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
32453       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
32454                                        VT.getVectorNumElements());
32455       SDValue Res;
32456       SDValue Chain;
32457       if (IsStrict) {
32458         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
32459                           {N->getOperand(0), Src});
32460         Chain = Res.getValue(1);
32461       } else
32462         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
32463 
32464       // Preserve what we know about the size of the original result. If the
32465       // result is v2i32, we have to manually widen the assert.
32466       if (PromoteVT == MVT::v2i32)
32467         Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Res,
32468                           DAG.getUNDEF(MVT::v2i32));
32469 
32470       Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext, dl,
32471                         Res.getValueType(), Res,
32472                         DAG.getValueType(VT.getVectorElementType()));
32473 
32474       if (PromoteVT == MVT::v2i32)
32475         Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
32476                           DAG.getIntPtrConstant(0, dl));
32477 
32478       // Truncate back to the original width.
32479       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
32480 
32481       // Now widen to 128 bits.
32482       unsigned NumConcats = 128 / VT.getSizeInBits();
32483       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
32484                                       VT.getVectorNumElements() * NumConcats);
32485       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
32486       ConcatOps[0] = Res;
32487       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
32488       Results.push_back(Res);
32489       if (IsStrict)
32490         Results.push_back(Chain);
32491       return;
32492     }
32493 
32494 
32495     if (VT == MVT::v2i32) {
32496       assert((!IsStrict || IsSigned || Subtarget.hasAVX512()) &&
32497              "Strict unsigned conversion requires AVX512");
32498       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32499       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
32500              "Unexpected type action!");
32501       if (Src.getValueType() == MVT::v2f64) {
32502         if (!IsSigned && !Subtarget.hasAVX512()) {
32503           SDValue Res =
32504               expandFP_TO_UINT_SSE(MVT::v4i32, Src, dl, DAG, Subtarget);
32505           Results.push_back(Res);
32506           return;
32507         }
32508 
32509         unsigned Opc;
32510         if (IsStrict)
32511           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32512         else
32513           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32514 
32515         // If we have VLX we can emit a target specific FP_TO_UINT node,.
32516         if (!IsSigned && !Subtarget.hasVLX()) {
32517           // Otherwise we can defer to the generic legalizer which will widen
32518           // the input as well. This will be further widened during op
32519           // legalization to v8i32<-v8f64.
32520           // For strict nodes we'll need to widen ourselves.
32521           // FIXME: Fix the type legalizer to safely widen strict nodes?
32522           if (!IsStrict)
32523             return;
32524           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
32525                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
32526           Opc = N->getOpcode();
32527         }
32528         SDValue Res;
32529         SDValue Chain;
32530         if (IsStrict) {
32531           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
32532                             {N->getOperand(0), Src});
32533           Chain = Res.getValue(1);
32534         } else {
32535           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
32536         }
32537         Results.push_back(Res);
32538         if (IsStrict)
32539           Results.push_back(Chain);
32540         return;
32541       }
32542 
32543       // Custom widen strict v2f32->v2i32 by padding with zeros.
32544       // FIXME: Should generic type legalizer do this?
32545       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
32546         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
32547                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
32548         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
32549                                   {N->getOperand(0), Src});
32550         Results.push_back(Res);
32551         Results.push_back(Res.getValue(1));
32552         return;
32553       }
32554 
32555       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
32556       // so early out here.
32557       return;
32558     }
32559 
32560     assert(!VT.isVector() && "Vectors should have been handled above!");
32561 
32562     if ((Subtarget.hasDQI() && VT == MVT::i64 &&
32563          (SrcVT == MVT::f32 || SrcVT == MVT::f64)) ||
32564         (Subtarget.hasFP16() && SrcVT == MVT::f16)) {
32565       assert(!Subtarget.is64Bit() && "i64 should be legal");
32566       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
32567       // If we use a 128-bit result we might need to use a target specific node.
32568       unsigned SrcElts =
32569           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
32570       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
32571       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
32572       unsigned Opc = N->getOpcode();
32573       if (NumElts != SrcElts) {
32574         if (IsStrict)
32575           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
32576         else
32577           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
32578       }
32579 
32580       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
32581       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
32582                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
32583                                 ZeroIdx);
32584       SDValue Chain;
32585       if (IsStrict) {
32586         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
32587         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
32588         Chain = Res.getValue(1);
32589       } else
32590         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
32591       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
32592       Results.push_back(Res);
32593       if (IsStrict)
32594         Results.push_back(Chain);
32595       return;
32596     }
32597 
32598     if (VT == MVT::i128 && Subtarget.isTargetWin64()) {
32599       SDValue Chain;
32600       SDValue V = LowerWin64_FP_TO_INT128(SDValue(N, 0), DAG, Chain);
32601       Results.push_back(V);
32602       if (IsStrict)
32603         Results.push_back(Chain);
32604       return;
32605     }
32606 
32607     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
32608       Results.push_back(V);
32609       if (IsStrict)
32610         Results.push_back(Chain);
32611     }
32612     return;
32613   }
32614   case ISD::LRINT:
32615   case ISD::LLRINT: {
32616     if (SDValue V = LRINT_LLRINTHelper(N, DAG))
32617       Results.push_back(V);
32618     return;
32619   }
32620 
32621   case ISD::SINT_TO_FP:
32622   case ISD::STRICT_SINT_TO_FP:
32623   case ISD::UINT_TO_FP:
32624   case ISD::STRICT_UINT_TO_FP: {
32625     bool IsStrict = N->isStrictFPOpcode();
32626     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
32627                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
32628     EVT VT = N->getValueType(0);
32629     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32630     if (VT.getVectorElementType() == MVT::f16 && Subtarget.hasFP16() &&
32631         Subtarget.hasVLX()) {
32632       if (Src.getValueType().getVectorElementType() == MVT::i16)
32633         return;
32634 
32635       if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2i32)
32636         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
32637                           IsStrict ? DAG.getConstant(0, dl, MVT::v2i32)
32638                                    : DAG.getUNDEF(MVT::v2i32));
32639       if (IsStrict) {
32640         unsigned Opc =
32641             IsSigned ? X86ISD::STRICT_CVTSI2P : X86ISD::STRICT_CVTUI2P;
32642         SDValue Res = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
32643                                   {N->getOperand(0), Src});
32644         Results.push_back(Res);
32645         Results.push_back(Res.getValue(1));
32646       } else {
32647         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
32648         Results.push_back(DAG.getNode(Opc, dl, MVT::v8f16, Src));
32649       }
32650       return;
32651     }
32652     if (VT != MVT::v2f32)
32653       return;
32654     EVT SrcVT = Src.getValueType();
32655     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
32656       if (IsStrict) {
32657         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
32658                                 : X86ISD::STRICT_CVTUI2P;
32659         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
32660                                   {N->getOperand(0), Src});
32661         Results.push_back(Res);
32662         Results.push_back(Res.getValue(1));
32663       } else {
32664         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
32665         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
32666       }
32667       return;
32668     }
32669     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
32670         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
32671       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
32672       SDValue One  = DAG.getConstant(1, dl, SrcVT);
32673       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
32674                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
32675                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
32676       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
32677       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
32678       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
32679       for (int i = 0; i != 2; ++i) {
32680         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
32681                                   SignSrc, DAG.getIntPtrConstant(i, dl));
32682         if (IsStrict)
32683           SignCvts[i] =
32684               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
32685                           {N->getOperand(0), Elt});
32686         else
32687           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
32688       };
32689       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
32690       SDValue Slow, Chain;
32691       if (IsStrict) {
32692         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
32693                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
32694         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
32695                            {Chain, SignCvt, SignCvt});
32696         Chain = Slow.getValue(1);
32697       } else {
32698         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
32699       }
32700       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
32701       IsNeg =
32702           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
32703       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
32704       Results.push_back(Cvt);
32705       if (IsStrict)
32706         Results.push_back(Chain);
32707       return;
32708     }
32709 
32710     if (SrcVT != MVT::v2i32)
32711       return;
32712 
32713     if (IsSigned || Subtarget.hasAVX512()) {
32714       if (!IsStrict)
32715         return;
32716 
32717       // Custom widen strict v2i32->v2f32 to avoid scalarization.
32718       // FIXME: Should generic type legalizer do this?
32719       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
32720                         DAG.getConstant(0, dl, MVT::v2i32));
32721       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
32722                                 {N->getOperand(0), Src});
32723       Results.push_back(Res);
32724       Results.push_back(Res.getValue(1));
32725       return;
32726     }
32727 
32728     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32729     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
32730     SDValue VBias = DAG.getConstantFP(
32731         llvm::bit_cast<double>(0x4330000000000000ULL), dl, MVT::v2f64);
32732     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
32733                              DAG.getBitcast(MVT::v2i64, VBias));
32734     Or = DAG.getBitcast(MVT::v2f64, Or);
32735     if (IsStrict) {
32736       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
32737                                 {N->getOperand(0), Or, VBias});
32738       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
32739                                 {MVT::v4f32, MVT::Other},
32740                                 {Sub.getValue(1), Sub});
32741       Results.push_back(Res);
32742       Results.push_back(Res.getValue(1));
32743     } else {
32744       // TODO: Are there any fast-math-flags to propagate here?
32745       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
32746       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
32747     }
32748     return;
32749   }
32750   case ISD::STRICT_FP_ROUND:
32751   case ISD::FP_ROUND: {
32752     bool IsStrict = N->isStrictFPOpcode();
32753     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
32754     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32755     SDValue Rnd = N->getOperand(IsStrict ? 2 : 1);
32756     EVT SrcVT = Src.getValueType();
32757     EVT VT = N->getValueType(0);
32758     SDValue V;
32759     if (VT == MVT::v2f16 && Src.getValueType() == MVT::v2f32) {
32760       SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f32)
32761                              : DAG.getUNDEF(MVT::v2f32);
32762       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src, Ext);
32763     }
32764     if (!Subtarget.hasFP16() && VT.getVectorElementType() == MVT::f16) {
32765       assert(Subtarget.hasF16C() && "Cannot widen f16 without F16C");
32766       if (SrcVT.getVectorElementType() != MVT::f32)
32767         return;
32768 
32769       if (IsStrict)
32770         V = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
32771                         {Chain, Src, Rnd});
32772       else
32773         V = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Src, Rnd);
32774 
32775       Results.push_back(DAG.getBitcast(MVT::v8f16, V));
32776       if (IsStrict)
32777         Results.push_back(V.getValue(1));
32778       return;
32779     }
32780     if (!isTypeLegal(Src.getValueType()))
32781       return;
32782     EVT NewVT = VT.getVectorElementType() == MVT::f16 ? MVT::v8f16 : MVT::v4f32;
32783     if (IsStrict)
32784       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {NewVT, MVT::Other},
32785                       {Chain, Src});
32786     else
32787       V = DAG.getNode(X86ISD::VFPROUND, dl, NewVT, Src);
32788     Results.push_back(V);
32789     if (IsStrict)
32790       Results.push_back(V.getValue(1));
32791     return;
32792   }
32793   case ISD::FP_EXTEND:
32794   case ISD::STRICT_FP_EXTEND: {
32795     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
32796     // No other ValueType for FP_EXTEND should reach this point.
32797     assert(N->getValueType(0) == MVT::v2f32 &&
32798            "Do not know how to legalize this Node");
32799     if (!Subtarget.hasFP16() || !Subtarget.hasVLX())
32800       return;
32801     bool IsStrict = N->isStrictFPOpcode();
32802     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
32803     SDValue Ext = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v2f16)
32804                            : DAG.getUNDEF(MVT::v2f16);
32805     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f16, Src, Ext);
32806     if (IsStrict)
32807       V = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::v4f32, MVT::Other},
32808                       {N->getOperand(0), V});
32809     else
32810       V = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, V);
32811     Results.push_back(V);
32812     if (IsStrict)
32813       Results.push_back(V.getValue(1));
32814     return;
32815   }
32816   case ISD::INTRINSIC_W_CHAIN: {
32817     unsigned IntNo = N->getConstantOperandVal(1);
32818     switch (IntNo) {
32819     default : llvm_unreachable("Do not know how to custom type "
32820                                "legalize this intrinsic operation!");
32821     case Intrinsic::x86_rdtsc:
32822       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
32823                                      Results);
32824     case Intrinsic::x86_rdtscp:
32825       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
32826                                      Results);
32827     case Intrinsic::x86_rdpmc:
32828       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
32829                                   Results);
32830       return;
32831     case Intrinsic::x86_rdpru:
32832       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPRU, X86::ECX, Subtarget,
32833         Results);
32834       return;
32835     case Intrinsic::x86_xgetbv:
32836       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
32837                                   Results);
32838       return;
32839     }
32840   }
32841   case ISD::READCYCLECOUNTER: {
32842     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
32843   }
32844   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
32845     EVT T = N->getValueType(0);
32846     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
32847     bool Regs64bit = T == MVT::i128;
32848     assert((!Regs64bit || Subtarget.canUseCMPXCHG16B()) &&
32849            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
32850     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
32851     SDValue cpInL, cpInH;
32852     std::tie(cpInL, cpInH) =
32853         DAG.SplitScalar(N->getOperand(2), dl, HalfT, HalfT);
32854     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
32855                              Regs64bit ? X86::RAX : X86::EAX, cpInL, SDValue());
32856     cpInH =
32857         DAG.getCopyToReg(cpInL.getValue(0), dl, Regs64bit ? X86::RDX : X86::EDX,
32858                          cpInH, cpInL.getValue(1));
32859     SDValue swapInL, swapInH;
32860     std::tie(swapInL, swapInH) =
32861         DAG.SplitScalar(N->getOperand(3), dl, HalfT, HalfT);
32862     swapInH =
32863         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
32864                          swapInH, cpInH.getValue(1));
32865 
32866     // In 64-bit mode we might need the base pointer in RBX, but we can't know
32867     // until later. So we keep the RBX input in a vreg and use a custom
32868     // inserter.
32869     // Since RBX will be a reserved register the register allocator will not
32870     // make sure its value will be properly saved and restored around this
32871     // live-range.
32872     SDValue Result;
32873     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
32874     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
32875     if (Regs64bit) {
32876       SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
32877                        swapInH.getValue(1)};
32878       Result =
32879           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
32880     } else {
32881       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
32882                                  swapInH.getValue(1));
32883       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
32884                        swapInL.getValue(1)};
32885       Result =
32886           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
32887     }
32888 
32889     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
32890                                         Regs64bit ? X86::RAX : X86::EAX,
32891                                         HalfT, Result.getValue(1));
32892     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
32893                                         Regs64bit ? X86::RDX : X86::EDX,
32894                                         HalfT, cpOutL.getValue(2));
32895     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
32896 
32897     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
32898                                         MVT::i32, cpOutH.getValue(2));
32899     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
32900     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
32901 
32902     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
32903     Results.push_back(Success);
32904     Results.push_back(EFLAGS.getValue(1));
32905     return;
32906   }
32907   case ISD::ATOMIC_LOAD: {
32908     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
32909     bool NoImplicitFloatOps =
32910         DAG.getMachineFunction().getFunction().hasFnAttribute(
32911             Attribute::NoImplicitFloat);
32912     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
32913       auto *Node = cast<AtomicSDNode>(N);
32914       if (Subtarget.hasSSE1()) {
32915         // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
32916         // Then extract the lower 64-bits.
32917         MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
32918         SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
32919         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
32920         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
32921                                              MVT::i64, Node->getMemOperand());
32922         if (Subtarget.hasSSE2()) {
32923           SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
32924                                     DAG.getIntPtrConstant(0, dl));
32925           Results.push_back(Res);
32926           Results.push_back(Ld.getValue(1));
32927           return;
32928         }
32929         // We use an alternative sequence for SSE1 that extracts as v2f32 and
32930         // then casts to i64. This avoids a 128-bit stack temporary being
32931         // created by type legalization if we were to cast v4f32->v2i64.
32932         SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
32933                                   DAG.getIntPtrConstant(0, dl));
32934         Res = DAG.getBitcast(MVT::i64, Res);
32935         Results.push_back(Res);
32936         Results.push_back(Ld.getValue(1));
32937         return;
32938       }
32939       if (Subtarget.hasX87()) {
32940         // First load this into an 80-bit X87 register. This will put the whole
32941         // integer into the significand.
32942         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
32943         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
32944         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
32945                                                  dl, Tys, Ops, MVT::i64,
32946                                                  Node->getMemOperand());
32947         SDValue Chain = Result.getValue(1);
32948 
32949         // Now store the X87 register to a stack temporary and convert to i64.
32950         // This store is not atomic and doesn't need to be.
32951         // FIXME: We don't need a stack temporary if the result of the load
32952         // is already being stored. We could just directly store there.
32953         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
32954         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
32955         MachinePointerInfo MPI =
32956             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
32957         SDValue StoreOps[] = { Chain, Result, StackPtr };
32958         Chain = DAG.getMemIntrinsicNode(
32959             X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
32960             MPI, std::nullopt /*Align*/, MachineMemOperand::MOStore);
32961 
32962         // Finally load the value back from the stack temporary and return it.
32963         // This load is not atomic and doesn't need to be.
32964         // This load will be further type legalized.
32965         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
32966         Results.push_back(Result);
32967         Results.push_back(Result.getValue(1));
32968         return;
32969       }
32970     }
32971     // TODO: Use MOVLPS when SSE1 is available?
32972     // Delegate to generic TypeLegalization. Situations we can really handle
32973     // should have already been dealt with by AtomicExpandPass.cpp.
32974     break;
32975   }
32976   case ISD::ATOMIC_SWAP:
32977   case ISD::ATOMIC_LOAD_ADD:
32978   case ISD::ATOMIC_LOAD_SUB:
32979   case ISD::ATOMIC_LOAD_AND:
32980   case ISD::ATOMIC_LOAD_OR:
32981   case ISD::ATOMIC_LOAD_XOR:
32982   case ISD::ATOMIC_LOAD_NAND:
32983   case ISD::ATOMIC_LOAD_MIN:
32984   case ISD::ATOMIC_LOAD_MAX:
32985   case ISD::ATOMIC_LOAD_UMIN:
32986   case ISD::ATOMIC_LOAD_UMAX:
32987     // Delegate to generic TypeLegalization. Situations we can really handle
32988     // should have already been dealt with by AtomicExpandPass.cpp.
32989     break;
32990 
32991   case ISD::BITCAST: {
32992     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
32993     EVT DstVT = N->getValueType(0);
32994     EVT SrcVT = N->getOperand(0).getValueType();
32995 
32996     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
32997     // we can split using the k-register rather than memory.
32998     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
32999       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
33000       SDValue Lo, Hi;
33001       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
33002       Lo = DAG.getBitcast(MVT::i32, Lo);
33003       Hi = DAG.getBitcast(MVT::i32, Hi);
33004       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
33005       Results.push_back(Res);
33006       return;
33007     }
33008 
33009     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
33010       // FIXME: Use v4f32 for SSE1?
33011       assert(Subtarget.hasSSE2() && "Requires SSE2");
33012       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
33013              "Unexpected type action!");
33014       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
33015       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
33016                                 N->getOperand(0));
33017       Res = DAG.getBitcast(WideVT, Res);
33018       Results.push_back(Res);
33019       return;
33020     }
33021 
33022     return;
33023   }
33024   case ISD::MGATHER: {
33025     EVT VT = N->getValueType(0);
33026     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
33027         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
33028       auto *Gather = cast<MaskedGatherSDNode>(N);
33029       SDValue Index = Gather->getIndex();
33030       if (Index.getValueType() != MVT::v2i64)
33031         return;
33032       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33033              "Unexpected type action!");
33034       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
33035       SDValue Mask = Gather->getMask();
33036       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
33037       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
33038                                      Gather->getPassThru(),
33039                                      DAG.getUNDEF(VT));
33040       if (!Subtarget.hasVLX()) {
33041         // We need to widen the mask, but the instruction will only use 2
33042         // of its elements. So we can use undef.
33043         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
33044                            DAG.getUNDEF(MVT::v2i1));
33045         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
33046       }
33047       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
33048                         Gather->getBasePtr(), Index, Gather->getScale() };
33049       SDValue Res = DAG.getMemIntrinsicNode(
33050           X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
33051           Gather->getMemoryVT(), Gather->getMemOperand());
33052       Results.push_back(Res);
33053       Results.push_back(Res.getValue(1));
33054       return;
33055     }
33056     return;
33057   }
33058   case ISD::LOAD: {
33059     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
33060     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
33061     // cast since type legalization will try to use an i64 load.
33062     MVT VT = N->getSimpleValueType(0);
33063     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
33064     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
33065            "Unexpected type action!");
33066     if (!ISD::isNON_EXTLoad(N))
33067       return;
33068     auto *Ld = cast<LoadSDNode>(N);
33069     if (Subtarget.hasSSE2()) {
33070       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
33071       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
33072                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
33073                                 Ld->getMemOperand()->getFlags());
33074       SDValue Chain = Res.getValue(1);
33075       MVT VecVT = MVT::getVectorVT(LdVT, 2);
33076       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
33077       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
33078       Res = DAG.getBitcast(WideVT, Res);
33079       Results.push_back(Res);
33080       Results.push_back(Chain);
33081       return;
33082     }
33083     assert(Subtarget.hasSSE1() && "Expected SSE");
33084     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
33085     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
33086     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
33087                                           MVT::i64, Ld->getMemOperand());
33088     Results.push_back(Res);
33089     Results.push_back(Res.getValue(1));
33090     return;
33091   }
33092   case ISD::ADDRSPACECAST: {
33093     SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
33094     Results.push_back(V);
33095     return;
33096   }
33097   case ISD::BITREVERSE: {
33098     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
33099     assert(Subtarget.hasXOP() && "Expected XOP");
33100     // We can use VPPERM by copying to a vector register and back. We'll need
33101     // to move the scalar in two i32 pieces.
33102     Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
33103     return;
33104   }
33105   case ISD::EXTRACT_VECTOR_ELT: {
33106     // f16 = extract vXf16 %vec, i64 %idx
33107     assert(N->getSimpleValueType(0) == MVT::f16 &&
33108            "Unexpected Value type of EXTRACT_VECTOR_ELT!");
33109     assert(Subtarget.hasFP16() && "Expected FP16");
33110     SDValue VecOp = N->getOperand(0);
33111     EVT ExtVT = VecOp.getValueType().changeVectorElementTypeToInteger();
33112     SDValue Split = DAG.getBitcast(ExtVT, N->getOperand(0));
33113     Split = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Split,
33114                         N->getOperand(1));
33115     Split = DAG.getBitcast(MVT::f16, Split);
33116     Results.push_back(Split);
33117     return;
33118   }
33119   }
33120 }
33121 
getTargetNodeName(unsigned Opcode) const33122 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
33123   switch ((X86ISD::NodeType)Opcode) {
33124   case X86ISD::FIRST_NUMBER:       break;
33125 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
33126   NODE_NAME_CASE(BSF)
33127   NODE_NAME_CASE(BSR)
33128   NODE_NAME_CASE(FSHL)
33129   NODE_NAME_CASE(FSHR)
33130   NODE_NAME_CASE(FAND)
33131   NODE_NAME_CASE(FANDN)
33132   NODE_NAME_CASE(FOR)
33133   NODE_NAME_CASE(FXOR)
33134   NODE_NAME_CASE(FILD)
33135   NODE_NAME_CASE(FIST)
33136   NODE_NAME_CASE(FP_TO_INT_IN_MEM)
33137   NODE_NAME_CASE(FLD)
33138   NODE_NAME_CASE(FST)
33139   NODE_NAME_CASE(CALL)
33140   NODE_NAME_CASE(CALL_RVMARKER)
33141   NODE_NAME_CASE(BT)
33142   NODE_NAME_CASE(CMP)
33143   NODE_NAME_CASE(FCMP)
33144   NODE_NAME_CASE(STRICT_FCMP)
33145   NODE_NAME_CASE(STRICT_FCMPS)
33146   NODE_NAME_CASE(COMI)
33147   NODE_NAME_CASE(UCOMI)
33148   NODE_NAME_CASE(CMPM)
33149   NODE_NAME_CASE(CMPMM)
33150   NODE_NAME_CASE(STRICT_CMPM)
33151   NODE_NAME_CASE(CMPMM_SAE)
33152   NODE_NAME_CASE(SETCC)
33153   NODE_NAME_CASE(SETCC_CARRY)
33154   NODE_NAME_CASE(FSETCC)
33155   NODE_NAME_CASE(FSETCCM)
33156   NODE_NAME_CASE(FSETCCM_SAE)
33157   NODE_NAME_CASE(CMOV)
33158   NODE_NAME_CASE(BRCOND)
33159   NODE_NAME_CASE(RET_GLUE)
33160   NODE_NAME_CASE(IRET)
33161   NODE_NAME_CASE(REP_STOS)
33162   NODE_NAME_CASE(REP_MOVS)
33163   NODE_NAME_CASE(GlobalBaseReg)
33164   NODE_NAME_CASE(Wrapper)
33165   NODE_NAME_CASE(WrapperRIP)
33166   NODE_NAME_CASE(MOVQ2DQ)
33167   NODE_NAME_CASE(MOVDQ2Q)
33168   NODE_NAME_CASE(MMX_MOVD2W)
33169   NODE_NAME_CASE(MMX_MOVW2D)
33170   NODE_NAME_CASE(PEXTRB)
33171   NODE_NAME_CASE(PEXTRW)
33172   NODE_NAME_CASE(INSERTPS)
33173   NODE_NAME_CASE(PINSRB)
33174   NODE_NAME_CASE(PINSRW)
33175   NODE_NAME_CASE(PSHUFB)
33176   NODE_NAME_CASE(ANDNP)
33177   NODE_NAME_CASE(BLENDI)
33178   NODE_NAME_CASE(BLENDV)
33179   NODE_NAME_CASE(HADD)
33180   NODE_NAME_CASE(HSUB)
33181   NODE_NAME_CASE(FHADD)
33182   NODE_NAME_CASE(FHSUB)
33183   NODE_NAME_CASE(CONFLICT)
33184   NODE_NAME_CASE(FMAX)
33185   NODE_NAME_CASE(FMAXS)
33186   NODE_NAME_CASE(FMAX_SAE)
33187   NODE_NAME_CASE(FMAXS_SAE)
33188   NODE_NAME_CASE(FMIN)
33189   NODE_NAME_CASE(FMINS)
33190   NODE_NAME_CASE(FMIN_SAE)
33191   NODE_NAME_CASE(FMINS_SAE)
33192   NODE_NAME_CASE(FMAXC)
33193   NODE_NAME_CASE(FMINC)
33194   NODE_NAME_CASE(FRSQRT)
33195   NODE_NAME_CASE(FRCP)
33196   NODE_NAME_CASE(EXTRQI)
33197   NODE_NAME_CASE(INSERTQI)
33198   NODE_NAME_CASE(TLSADDR)
33199   NODE_NAME_CASE(TLSBASEADDR)
33200   NODE_NAME_CASE(TLSCALL)
33201   NODE_NAME_CASE(EH_SJLJ_SETJMP)
33202   NODE_NAME_CASE(EH_SJLJ_LONGJMP)
33203   NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
33204   NODE_NAME_CASE(EH_RETURN)
33205   NODE_NAME_CASE(TC_RETURN)
33206   NODE_NAME_CASE(FNSTCW16m)
33207   NODE_NAME_CASE(FLDCW16m)
33208   NODE_NAME_CASE(FNSTENVm)
33209   NODE_NAME_CASE(FLDENVm)
33210   NODE_NAME_CASE(LCMPXCHG_DAG)
33211   NODE_NAME_CASE(LCMPXCHG8_DAG)
33212   NODE_NAME_CASE(LCMPXCHG16_DAG)
33213   NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
33214   NODE_NAME_CASE(LADD)
33215   NODE_NAME_CASE(LSUB)
33216   NODE_NAME_CASE(LOR)
33217   NODE_NAME_CASE(LXOR)
33218   NODE_NAME_CASE(LAND)
33219   NODE_NAME_CASE(LBTS)
33220   NODE_NAME_CASE(LBTC)
33221   NODE_NAME_CASE(LBTR)
33222   NODE_NAME_CASE(LBTS_RM)
33223   NODE_NAME_CASE(LBTC_RM)
33224   NODE_NAME_CASE(LBTR_RM)
33225   NODE_NAME_CASE(AADD)
33226   NODE_NAME_CASE(AOR)
33227   NODE_NAME_CASE(AXOR)
33228   NODE_NAME_CASE(AAND)
33229   NODE_NAME_CASE(VZEXT_MOVL)
33230   NODE_NAME_CASE(VZEXT_LOAD)
33231   NODE_NAME_CASE(VEXTRACT_STORE)
33232   NODE_NAME_CASE(VTRUNC)
33233   NODE_NAME_CASE(VTRUNCS)
33234   NODE_NAME_CASE(VTRUNCUS)
33235   NODE_NAME_CASE(VMTRUNC)
33236   NODE_NAME_CASE(VMTRUNCS)
33237   NODE_NAME_CASE(VMTRUNCUS)
33238   NODE_NAME_CASE(VTRUNCSTORES)
33239   NODE_NAME_CASE(VTRUNCSTOREUS)
33240   NODE_NAME_CASE(VMTRUNCSTORES)
33241   NODE_NAME_CASE(VMTRUNCSTOREUS)
33242   NODE_NAME_CASE(VFPEXT)
33243   NODE_NAME_CASE(STRICT_VFPEXT)
33244   NODE_NAME_CASE(VFPEXT_SAE)
33245   NODE_NAME_CASE(VFPEXTS)
33246   NODE_NAME_CASE(VFPEXTS_SAE)
33247   NODE_NAME_CASE(VFPROUND)
33248   NODE_NAME_CASE(STRICT_VFPROUND)
33249   NODE_NAME_CASE(VMFPROUND)
33250   NODE_NAME_CASE(VFPROUND_RND)
33251   NODE_NAME_CASE(VFPROUNDS)
33252   NODE_NAME_CASE(VFPROUNDS_RND)
33253   NODE_NAME_CASE(VSHLDQ)
33254   NODE_NAME_CASE(VSRLDQ)
33255   NODE_NAME_CASE(VSHL)
33256   NODE_NAME_CASE(VSRL)
33257   NODE_NAME_CASE(VSRA)
33258   NODE_NAME_CASE(VSHLI)
33259   NODE_NAME_CASE(VSRLI)
33260   NODE_NAME_CASE(VSRAI)
33261   NODE_NAME_CASE(VSHLV)
33262   NODE_NAME_CASE(VSRLV)
33263   NODE_NAME_CASE(VSRAV)
33264   NODE_NAME_CASE(VROTLI)
33265   NODE_NAME_CASE(VROTRI)
33266   NODE_NAME_CASE(VPPERM)
33267   NODE_NAME_CASE(CMPP)
33268   NODE_NAME_CASE(STRICT_CMPP)
33269   NODE_NAME_CASE(PCMPEQ)
33270   NODE_NAME_CASE(PCMPGT)
33271   NODE_NAME_CASE(PHMINPOS)
33272   NODE_NAME_CASE(ADD)
33273   NODE_NAME_CASE(SUB)
33274   NODE_NAME_CASE(ADC)
33275   NODE_NAME_CASE(SBB)
33276   NODE_NAME_CASE(SMUL)
33277   NODE_NAME_CASE(UMUL)
33278   NODE_NAME_CASE(OR)
33279   NODE_NAME_CASE(XOR)
33280   NODE_NAME_CASE(AND)
33281   NODE_NAME_CASE(BEXTR)
33282   NODE_NAME_CASE(BEXTRI)
33283   NODE_NAME_CASE(BZHI)
33284   NODE_NAME_CASE(PDEP)
33285   NODE_NAME_CASE(PEXT)
33286   NODE_NAME_CASE(MUL_IMM)
33287   NODE_NAME_CASE(MOVMSK)
33288   NODE_NAME_CASE(PTEST)
33289   NODE_NAME_CASE(TESTP)
33290   NODE_NAME_CASE(KORTEST)
33291   NODE_NAME_CASE(KTEST)
33292   NODE_NAME_CASE(KADD)
33293   NODE_NAME_CASE(KSHIFTL)
33294   NODE_NAME_CASE(KSHIFTR)
33295   NODE_NAME_CASE(PACKSS)
33296   NODE_NAME_CASE(PACKUS)
33297   NODE_NAME_CASE(PALIGNR)
33298   NODE_NAME_CASE(VALIGN)
33299   NODE_NAME_CASE(VSHLD)
33300   NODE_NAME_CASE(VSHRD)
33301   NODE_NAME_CASE(VSHLDV)
33302   NODE_NAME_CASE(VSHRDV)
33303   NODE_NAME_CASE(PSHUFD)
33304   NODE_NAME_CASE(PSHUFHW)
33305   NODE_NAME_CASE(PSHUFLW)
33306   NODE_NAME_CASE(SHUFP)
33307   NODE_NAME_CASE(SHUF128)
33308   NODE_NAME_CASE(MOVLHPS)
33309   NODE_NAME_CASE(MOVHLPS)
33310   NODE_NAME_CASE(MOVDDUP)
33311   NODE_NAME_CASE(MOVSHDUP)
33312   NODE_NAME_CASE(MOVSLDUP)
33313   NODE_NAME_CASE(MOVSD)
33314   NODE_NAME_CASE(MOVSS)
33315   NODE_NAME_CASE(MOVSH)
33316   NODE_NAME_CASE(UNPCKL)
33317   NODE_NAME_CASE(UNPCKH)
33318   NODE_NAME_CASE(VBROADCAST)
33319   NODE_NAME_CASE(VBROADCAST_LOAD)
33320   NODE_NAME_CASE(VBROADCASTM)
33321   NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
33322   NODE_NAME_CASE(VPERMILPV)
33323   NODE_NAME_CASE(VPERMILPI)
33324   NODE_NAME_CASE(VPERM2X128)
33325   NODE_NAME_CASE(VPERMV)
33326   NODE_NAME_CASE(VPERMV3)
33327   NODE_NAME_CASE(VPERMI)
33328   NODE_NAME_CASE(VPTERNLOG)
33329   NODE_NAME_CASE(VFIXUPIMM)
33330   NODE_NAME_CASE(VFIXUPIMM_SAE)
33331   NODE_NAME_CASE(VFIXUPIMMS)
33332   NODE_NAME_CASE(VFIXUPIMMS_SAE)
33333   NODE_NAME_CASE(VRANGE)
33334   NODE_NAME_CASE(VRANGE_SAE)
33335   NODE_NAME_CASE(VRANGES)
33336   NODE_NAME_CASE(VRANGES_SAE)
33337   NODE_NAME_CASE(PMULUDQ)
33338   NODE_NAME_CASE(PMULDQ)
33339   NODE_NAME_CASE(PSADBW)
33340   NODE_NAME_CASE(DBPSADBW)
33341   NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
33342   NODE_NAME_CASE(VAARG_64)
33343   NODE_NAME_CASE(VAARG_X32)
33344   NODE_NAME_CASE(DYN_ALLOCA)
33345   NODE_NAME_CASE(MFENCE)
33346   NODE_NAME_CASE(SEG_ALLOCA)
33347   NODE_NAME_CASE(PROBED_ALLOCA)
33348   NODE_NAME_CASE(RDRAND)
33349   NODE_NAME_CASE(RDSEED)
33350   NODE_NAME_CASE(RDPKRU)
33351   NODE_NAME_CASE(WRPKRU)
33352   NODE_NAME_CASE(VPMADDUBSW)
33353   NODE_NAME_CASE(VPMADDWD)
33354   NODE_NAME_CASE(VPSHA)
33355   NODE_NAME_CASE(VPSHL)
33356   NODE_NAME_CASE(VPCOM)
33357   NODE_NAME_CASE(VPCOMU)
33358   NODE_NAME_CASE(VPERMIL2)
33359   NODE_NAME_CASE(FMSUB)
33360   NODE_NAME_CASE(STRICT_FMSUB)
33361   NODE_NAME_CASE(FNMADD)
33362   NODE_NAME_CASE(STRICT_FNMADD)
33363   NODE_NAME_CASE(FNMSUB)
33364   NODE_NAME_CASE(STRICT_FNMSUB)
33365   NODE_NAME_CASE(FMADDSUB)
33366   NODE_NAME_CASE(FMSUBADD)
33367   NODE_NAME_CASE(FMADD_RND)
33368   NODE_NAME_CASE(FNMADD_RND)
33369   NODE_NAME_CASE(FMSUB_RND)
33370   NODE_NAME_CASE(FNMSUB_RND)
33371   NODE_NAME_CASE(FMADDSUB_RND)
33372   NODE_NAME_CASE(FMSUBADD_RND)
33373   NODE_NAME_CASE(VFMADDC)
33374   NODE_NAME_CASE(VFMADDC_RND)
33375   NODE_NAME_CASE(VFCMADDC)
33376   NODE_NAME_CASE(VFCMADDC_RND)
33377   NODE_NAME_CASE(VFMULC)
33378   NODE_NAME_CASE(VFMULC_RND)
33379   NODE_NAME_CASE(VFCMULC)
33380   NODE_NAME_CASE(VFCMULC_RND)
33381   NODE_NAME_CASE(VFMULCSH)
33382   NODE_NAME_CASE(VFMULCSH_RND)
33383   NODE_NAME_CASE(VFCMULCSH)
33384   NODE_NAME_CASE(VFCMULCSH_RND)
33385   NODE_NAME_CASE(VFMADDCSH)
33386   NODE_NAME_CASE(VFMADDCSH_RND)
33387   NODE_NAME_CASE(VFCMADDCSH)
33388   NODE_NAME_CASE(VFCMADDCSH_RND)
33389   NODE_NAME_CASE(VPMADD52H)
33390   NODE_NAME_CASE(VPMADD52L)
33391   NODE_NAME_CASE(VRNDSCALE)
33392   NODE_NAME_CASE(STRICT_VRNDSCALE)
33393   NODE_NAME_CASE(VRNDSCALE_SAE)
33394   NODE_NAME_CASE(VRNDSCALES)
33395   NODE_NAME_CASE(VRNDSCALES_SAE)
33396   NODE_NAME_CASE(VREDUCE)
33397   NODE_NAME_CASE(VREDUCE_SAE)
33398   NODE_NAME_CASE(VREDUCES)
33399   NODE_NAME_CASE(VREDUCES_SAE)
33400   NODE_NAME_CASE(VGETMANT)
33401   NODE_NAME_CASE(VGETMANT_SAE)
33402   NODE_NAME_CASE(VGETMANTS)
33403   NODE_NAME_CASE(VGETMANTS_SAE)
33404   NODE_NAME_CASE(PCMPESTR)
33405   NODE_NAME_CASE(PCMPISTR)
33406   NODE_NAME_CASE(XTEST)
33407   NODE_NAME_CASE(COMPRESS)
33408   NODE_NAME_CASE(EXPAND)
33409   NODE_NAME_CASE(SELECTS)
33410   NODE_NAME_CASE(ADDSUB)
33411   NODE_NAME_CASE(RCP14)
33412   NODE_NAME_CASE(RCP14S)
33413   NODE_NAME_CASE(RCP28)
33414   NODE_NAME_CASE(RCP28_SAE)
33415   NODE_NAME_CASE(RCP28S)
33416   NODE_NAME_CASE(RCP28S_SAE)
33417   NODE_NAME_CASE(EXP2)
33418   NODE_NAME_CASE(EXP2_SAE)
33419   NODE_NAME_CASE(RSQRT14)
33420   NODE_NAME_CASE(RSQRT14S)
33421   NODE_NAME_CASE(RSQRT28)
33422   NODE_NAME_CASE(RSQRT28_SAE)
33423   NODE_NAME_CASE(RSQRT28S)
33424   NODE_NAME_CASE(RSQRT28S_SAE)
33425   NODE_NAME_CASE(FADD_RND)
33426   NODE_NAME_CASE(FADDS)
33427   NODE_NAME_CASE(FADDS_RND)
33428   NODE_NAME_CASE(FSUB_RND)
33429   NODE_NAME_CASE(FSUBS)
33430   NODE_NAME_CASE(FSUBS_RND)
33431   NODE_NAME_CASE(FMUL_RND)
33432   NODE_NAME_CASE(FMULS)
33433   NODE_NAME_CASE(FMULS_RND)
33434   NODE_NAME_CASE(FDIV_RND)
33435   NODE_NAME_CASE(FDIVS)
33436   NODE_NAME_CASE(FDIVS_RND)
33437   NODE_NAME_CASE(FSQRT_RND)
33438   NODE_NAME_CASE(FSQRTS)
33439   NODE_NAME_CASE(FSQRTS_RND)
33440   NODE_NAME_CASE(FGETEXP)
33441   NODE_NAME_CASE(FGETEXP_SAE)
33442   NODE_NAME_CASE(FGETEXPS)
33443   NODE_NAME_CASE(FGETEXPS_SAE)
33444   NODE_NAME_CASE(SCALEF)
33445   NODE_NAME_CASE(SCALEF_RND)
33446   NODE_NAME_CASE(SCALEFS)
33447   NODE_NAME_CASE(SCALEFS_RND)
33448   NODE_NAME_CASE(MULHRS)
33449   NODE_NAME_CASE(SINT_TO_FP_RND)
33450   NODE_NAME_CASE(UINT_TO_FP_RND)
33451   NODE_NAME_CASE(CVTTP2SI)
33452   NODE_NAME_CASE(CVTTP2UI)
33453   NODE_NAME_CASE(STRICT_CVTTP2SI)
33454   NODE_NAME_CASE(STRICT_CVTTP2UI)
33455   NODE_NAME_CASE(MCVTTP2SI)
33456   NODE_NAME_CASE(MCVTTP2UI)
33457   NODE_NAME_CASE(CVTTP2SI_SAE)
33458   NODE_NAME_CASE(CVTTP2UI_SAE)
33459   NODE_NAME_CASE(CVTTS2SI)
33460   NODE_NAME_CASE(CVTTS2UI)
33461   NODE_NAME_CASE(CVTTS2SI_SAE)
33462   NODE_NAME_CASE(CVTTS2UI_SAE)
33463   NODE_NAME_CASE(CVTSI2P)
33464   NODE_NAME_CASE(CVTUI2P)
33465   NODE_NAME_CASE(STRICT_CVTSI2P)
33466   NODE_NAME_CASE(STRICT_CVTUI2P)
33467   NODE_NAME_CASE(MCVTSI2P)
33468   NODE_NAME_CASE(MCVTUI2P)
33469   NODE_NAME_CASE(VFPCLASS)
33470   NODE_NAME_CASE(VFPCLASSS)
33471   NODE_NAME_CASE(MULTISHIFT)
33472   NODE_NAME_CASE(SCALAR_SINT_TO_FP)
33473   NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
33474   NODE_NAME_CASE(SCALAR_UINT_TO_FP)
33475   NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
33476   NODE_NAME_CASE(CVTPS2PH)
33477   NODE_NAME_CASE(STRICT_CVTPS2PH)
33478   NODE_NAME_CASE(CVTPS2PH_SAE)
33479   NODE_NAME_CASE(MCVTPS2PH)
33480   NODE_NAME_CASE(MCVTPS2PH_SAE)
33481   NODE_NAME_CASE(CVTPH2PS)
33482   NODE_NAME_CASE(STRICT_CVTPH2PS)
33483   NODE_NAME_CASE(CVTPH2PS_SAE)
33484   NODE_NAME_CASE(CVTP2SI)
33485   NODE_NAME_CASE(CVTP2UI)
33486   NODE_NAME_CASE(MCVTP2SI)
33487   NODE_NAME_CASE(MCVTP2UI)
33488   NODE_NAME_CASE(CVTP2SI_RND)
33489   NODE_NAME_CASE(CVTP2UI_RND)
33490   NODE_NAME_CASE(CVTS2SI)
33491   NODE_NAME_CASE(CVTS2UI)
33492   NODE_NAME_CASE(CVTS2SI_RND)
33493   NODE_NAME_CASE(CVTS2UI_RND)
33494   NODE_NAME_CASE(CVTNE2PS2BF16)
33495   NODE_NAME_CASE(CVTNEPS2BF16)
33496   NODE_NAME_CASE(MCVTNEPS2BF16)
33497   NODE_NAME_CASE(DPBF16PS)
33498   NODE_NAME_CASE(LWPINS)
33499   NODE_NAME_CASE(MGATHER)
33500   NODE_NAME_CASE(MSCATTER)
33501   NODE_NAME_CASE(VPDPBUSD)
33502   NODE_NAME_CASE(VPDPBUSDS)
33503   NODE_NAME_CASE(VPDPWSSD)
33504   NODE_NAME_CASE(VPDPWSSDS)
33505   NODE_NAME_CASE(VPSHUFBITQMB)
33506   NODE_NAME_CASE(GF2P8MULB)
33507   NODE_NAME_CASE(GF2P8AFFINEQB)
33508   NODE_NAME_CASE(GF2P8AFFINEINVQB)
33509   NODE_NAME_CASE(NT_CALL)
33510   NODE_NAME_CASE(NT_BRIND)
33511   NODE_NAME_CASE(UMWAIT)
33512   NODE_NAME_CASE(TPAUSE)
33513   NODE_NAME_CASE(ENQCMD)
33514   NODE_NAME_CASE(ENQCMDS)
33515   NODE_NAME_CASE(VP2INTERSECT)
33516   NODE_NAME_CASE(VPDPBSUD)
33517   NODE_NAME_CASE(VPDPBSUDS)
33518   NODE_NAME_CASE(VPDPBUUD)
33519   NODE_NAME_CASE(VPDPBUUDS)
33520   NODE_NAME_CASE(VPDPBSSD)
33521   NODE_NAME_CASE(VPDPBSSDS)
33522   NODE_NAME_CASE(AESENC128KL)
33523   NODE_NAME_CASE(AESDEC128KL)
33524   NODE_NAME_CASE(AESENC256KL)
33525   NODE_NAME_CASE(AESDEC256KL)
33526   NODE_NAME_CASE(AESENCWIDE128KL)
33527   NODE_NAME_CASE(AESDECWIDE128KL)
33528   NODE_NAME_CASE(AESENCWIDE256KL)
33529   NODE_NAME_CASE(AESDECWIDE256KL)
33530   NODE_NAME_CASE(CMPCCXADD)
33531   NODE_NAME_CASE(TESTUI)
33532   NODE_NAME_CASE(FP80_ADD)
33533   NODE_NAME_CASE(STRICT_FP80_ADD)
33534   }
33535   return nullptr;
33536 #undef NODE_NAME_CASE
33537 }
33538 
33539 /// Return true if the addressing mode represented by AM is legal for this
33540 /// target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const33541 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
33542                                               const AddrMode &AM, Type *Ty,
33543                                               unsigned AS,
33544                                               Instruction *I) const {
33545   // X86 supports extremely general addressing modes.
33546   CodeModel::Model M = getTargetMachine().getCodeModel();
33547 
33548   // X86 allows a sign-extended 32-bit immediate field as a displacement.
33549   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
33550     return false;
33551 
33552   if (AM.BaseGV) {
33553     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
33554 
33555     // If a reference to this global requires an extra load, we can't fold it.
33556     if (isGlobalStubReference(GVFlags))
33557       return false;
33558 
33559     // If BaseGV requires a register for the PIC base, we cannot also have a
33560     // BaseReg specified.
33561     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
33562       return false;
33563 
33564     // If lower 4G is not available, then we must use rip-relative addressing.
33565     if ((M != CodeModel::Small || isPositionIndependent()) &&
33566         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
33567       return false;
33568   }
33569 
33570   switch (AM.Scale) {
33571   case 0:
33572   case 1:
33573   case 2:
33574   case 4:
33575   case 8:
33576     // These scales always work.
33577     break;
33578   case 3:
33579   case 5:
33580   case 9:
33581     // These scales are formed with basereg+scalereg.  Only accept if there is
33582     // no basereg yet.
33583     if (AM.HasBaseReg)
33584       return false;
33585     break;
33586   default:  // Other stuff never works.
33587     return false;
33588   }
33589 
33590   return true;
33591 }
33592 
isVectorShiftByScalarCheap(Type * Ty) const33593 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
33594   unsigned Bits = Ty->getScalarSizeInBits();
33595 
33596   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
33597   // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
33598   if (Subtarget.hasXOP() &&
33599       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
33600     return false;
33601 
33602   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
33603   // shifts just as cheap as scalar ones.
33604   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
33605     return false;
33606 
33607   // AVX512BW has shifts such as vpsllvw.
33608   if (Subtarget.hasBWI() && Bits == 16)
33609     return false;
33610 
33611   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
33612   // fully general vector.
33613   return true;
33614 }
33615 
isBinOp(unsigned Opcode) const33616 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
33617   switch (Opcode) {
33618   // These are non-commutative binops.
33619   // TODO: Add more X86ISD opcodes once we have test coverage.
33620   case X86ISD::ANDNP:
33621   case X86ISD::PCMPGT:
33622   case X86ISD::FMAX:
33623   case X86ISD::FMIN:
33624   case X86ISD::FANDN:
33625   case X86ISD::VPSHA:
33626   case X86ISD::VPSHL:
33627   case X86ISD::VSHLV:
33628   case X86ISD::VSRLV:
33629   case X86ISD::VSRAV:
33630     return true;
33631   }
33632 
33633   return TargetLoweringBase::isBinOp(Opcode);
33634 }
33635 
isCommutativeBinOp(unsigned Opcode) const33636 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
33637   switch (Opcode) {
33638   // TODO: Add more X86ISD opcodes once we have test coverage.
33639   case X86ISD::PCMPEQ:
33640   case X86ISD::PMULDQ:
33641   case X86ISD::PMULUDQ:
33642   case X86ISD::FMAXC:
33643   case X86ISD::FMINC:
33644   case X86ISD::FAND:
33645   case X86ISD::FOR:
33646   case X86ISD::FXOR:
33647     return true;
33648   }
33649 
33650   return TargetLoweringBase::isCommutativeBinOp(Opcode);
33651 }
33652 
isTruncateFree(Type * Ty1,Type * Ty2) const33653 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
33654   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
33655     return false;
33656   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
33657   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
33658   return NumBits1 > NumBits2;
33659 }
33660 
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const33661 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
33662   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
33663     return false;
33664 
33665   if (!isTypeLegal(EVT::getEVT(Ty1)))
33666     return false;
33667 
33668   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
33669 
33670   // Assuming the caller doesn't have a zeroext or signext return parameter,
33671   // truncation all the way down to i1 is valid.
33672   return true;
33673 }
33674 
isLegalICmpImmediate(int64_t Imm) const33675 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
33676   return isInt<32>(Imm);
33677 }
33678 
isLegalAddImmediate(int64_t Imm) const33679 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
33680   // Can also use sub to handle negated immediates.
33681   return isInt<32>(Imm);
33682 }
33683 
isLegalStoreImmediate(int64_t Imm) const33684 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
33685   return isInt<32>(Imm);
33686 }
33687 
isTruncateFree(EVT VT1,EVT VT2) const33688 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
33689   if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
33690     return false;
33691   unsigned NumBits1 = VT1.getSizeInBits();
33692   unsigned NumBits2 = VT2.getSizeInBits();
33693   return NumBits1 > NumBits2;
33694 }
33695 
isZExtFree(Type * Ty1,Type * Ty2) const33696 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
33697   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
33698   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
33699 }
33700 
isZExtFree(EVT VT1,EVT VT2) const33701 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
33702   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
33703   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
33704 }
33705 
isZExtFree(SDValue Val,EVT VT2) const33706 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
33707   EVT VT1 = Val.getValueType();
33708   if (isZExtFree(VT1, VT2))
33709     return true;
33710 
33711   if (Val.getOpcode() != ISD::LOAD)
33712     return false;
33713 
33714   if (!VT1.isSimple() || !VT1.isInteger() ||
33715       !VT2.isSimple() || !VT2.isInteger())
33716     return false;
33717 
33718   switch (VT1.getSimpleVT().SimpleTy) {
33719   default: break;
33720   case MVT::i8:
33721   case MVT::i16:
33722   case MVT::i32:
33723     // X86 has 8, 16, and 32-bit zero-extending loads.
33724     return true;
33725   }
33726 
33727   return false;
33728 }
33729 
shouldSinkOperands(Instruction * I,SmallVectorImpl<Use * > & Ops) const33730 bool X86TargetLowering::shouldSinkOperands(Instruction *I,
33731                                            SmallVectorImpl<Use *> &Ops) const {
33732   using namespace llvm::PatternMatch;
33733 
33734   FixedVectorType *VTy = dyn_cast<FixedVectorType>(I->getType());
33735   if (!VTy)
33736     return false;
33737 
33738   if (I->getOpcode() == Instruction::Mul &&
33739       VTy->getElementType()->isIntegerTy(64)) {
33740     for (auto &Op : I->operands()) {
33741       // Make sure we are not already sinking this operand
33742       if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
33743         continue;
33744 
33745       // Look for PMULDQ pattern where the input is a sext_inreg from vXi32 or
33746       // the PMULUDQ pattern where the input is a zext_inreg from vXi32.
33747       if (Subtarget.hasSSE41() &&
33748           match(Op.get(), m_AShr(m_Shl(m_Value(), m_SpecificInt(32)),
33749                                  m_SpecificInt(32)))) {
33750         Ops.push_back(&cast<Instruction>(Op)->getOperandUse(0));
33751         Ops.push_back(&Op);
33752       } else if (Subtarget.hasSSE2() &&
33753                  match(Op.get(),
33754                        m_And(m_Value(), m_SpecificInt(UINT64_C(0xffffffff))))) {
33755         Ops.push_back(&Op);
33756       }
33757     }
33758 
33759     return !Ops.empty();
33760   }
33761 
33762   // A uniform shift amount in a vector shift or funnel shift may be much
33763   // cheaper than a generic variable vector shift, so make that pattern visible
33764   // to SDAG by sinking the shuffle instruction next to the shift.
33765   int ShiftAmountOpNum = -1;
33766   if (I->isShift())
33767     ShiftAmountOpNum = 1;
33768   else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
33769     if (II->getIntrinsicID() == Intrinsic::fshl ||
33770         II->getIntrinsicID() == Intrinsic::fshr)
33771       ShiftAmountOpNum = 2;
33772   }
33773 
33774   if (ShiftAmountOpNum == -1)
33775     return false;
33776 
33777   auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
33778   if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
33779       isVectorShiftByScalarCheap(I->getType())) {
33780     Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
33781     return true;
33782   }
33783 
33784   return false;
33785 }
33786 
shouldConvertPhiType(Type * From,Type * To) const33787 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
33788   if (!Subtarget.is64Bit())
33789     return false;
33790   return TargetLowering::shouldConvertPhiType(From, To);
33791 }
33792 
isVectorLoadExtDesirable(SDValue ExtVal) const33793 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
33794   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
33795     return false;
33796 
33797   EVT SrcVT = ExtVal.getOperand(0).getValueType();
33798 
33799   // There is no extending load for vXi1.
33800   if (SrcVT.getScalarType() == MVT::i1)
33801     return false;
33802 
33803   return true;
33804 }
33805 
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const33806 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
33807                                                    EVT VT) const {
33808   if (!Subtarget.hasAnyFMA())
33809     return false;
33810 
33811   VT = VT.getScalarType();
33812 
33813   if (!VT.isSimple())
33814     return false;
33815 
33816   switch (VT.getSimpleVT().SimpleTy) {
33817   case MVT::f16:
33818     return Subtarget.hasFP16();
33819   case MVT::f32:
33820   case MVT::f64:
33821     return true;
33822   default:
33823     break;
33824   }
33825 
33826   return false;
33827 }
33828 
isNarrowingProfitable(EVT SrcVT,EVT DestVT) const33829 bool X86TargetLowering::isNarrowingProfitable(EVT SrcVT, EVT DestVT) const {
33830   // i16 instructions are longer (0x66 prefix) and potentially slower.
33831   return !(SrcVT == MVT::i32 && DestVT == MVT::i16);
33832 }
33833 
shouldFoldSelectWithIdentityConstant(unsigned Opcode,EVT VT) const33834 bool X86TargetLowering::shouldFoldSelectWithIdentityConstant(unsigned Opcode,
33835                                                              EVT VT) const {
33836   // TODO: This is too general. There are cases where pre-AVX512 codegen would
33837   //       benefit. The transform may also be profitable for scalar code.
33838   if (!Subtarget.hasAVX512())
33839     return false;
33840   if (!Subtarget.hasVLX() && !VT.is512BitVector())
33841     return false;
33842   if (!VT.isVector() || VT.getScalarType() == MVT::i1)
33843     return false;
33844 
33845   return true;
33846 }
33847 
33848 /// Targets can use this to indicate that they only support *some*
33849 /// VECTOR_SHUFFLE operations, those with specific masks.
33850 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
33851 /// are assumed to be legal.
isShuffleMaskLegal(ArrayRef<int> Mask,EVT VT) const33852 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
33853   if (!VT.isSimple())
33854     return false;
33855 
33856   // Not for i1 vectors
33857   if (VT.getSimpleVT().getScalarType() == MVT::i1)
33858     return false;
33859 
33860   // Very little shuffling can be done for 64-bit vectors right now.
33861   if (VT.getSimpleVT().getSizeInBits() == 64)
33862     return false;
33863 
33864   // We only care that the types being shuffled are legal. The lowering can
33865   // handle any possible shuffle mask that results.
33866   return isTypeLegal(VT.getSimpleVT());
33867 }
33868 
isVectorClearMaskLegal(ArrayRef<int> Mask,EVT VT) const33869 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
33870                                                EVT VT) const {
33871   // Don't convert an 'and' into a shuffle that we don't directly support.
33872   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
33873   if (!Subtarget.hasAVX2())
33874     if (VT == MVT::v32i8 || VT == MVT::v16i16)
33875       return false;
33876 
33877   // Just delegate to the generic legality, clear masks aren't special.
33878   return isShuffleMaskLegal(Mask, VT);
33879 }
33880 
areJTsAllowed(const Function * Fn) const33881 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
33882   // If the subtarget is using thunks, we need to not generate jump tables.
33883   if (Subtarget.useIndirectThunkBranches())
33884     return false;
33885 
33886   // Otherwise, fallback on the generic logic.
33887   return TargetLowering::areJTsAllowed(Fn);
33888 }
33889 
getPreferredSwitchConditionType(LLVMContext & Context,EVT ConditionVT) const33890 MVT X86TargetLowering::getPreferredSwitchConditionType(LLVMContext &Context,
33891                                                        EVT ConditionVT) const {
33892   // Avoid 8 and 16 bit types because they increase the chance for unnecessary
33893   // zero-extensions.
33894   if (ConditionVT.getSizeInBits() < 32)
33895     return MVT::i32;
33896   return TargetLoweringBase::getPreferredSwitchConditionType(Context,
33897                                                              ConditionVT);
33898 }
33899 
33900 //===----------------------------------------------------------------------===//
33901 //                           X86 Scheduler Hooks
33902 //===----------------------------------------------------------------------===//
33903 
33904 // Returns true if EFLAG is consumed after this iterator in the rest of the
33905 // basic block or any successors of the basic block.
isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,MachineBasicBlock * BB)33906 static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
33907                               MachineBasicBlock *BB) {
33908   // Scan forward through BB for a use/def of EFLAGS.
33909   for (const MachineInstr &mi : llvm::make_range(std::next(Itr), BB->end())) {
33910     if (mi.readsRegister(X86::EFLAGS))
33911       return true;
33912     // If we found a def, we can stop searching.
33913     if (mi.definesRegister(X86::EFLAGS))
33914       return false;
33915   }
33916 
33917   // If we hit the end of the block, check whether EFLAGS is live into a
33918   // successor.
33919   for (MachineBasicBlock *Succ : BB->successors())
33920     if (Succ->isLiveIn(X86::EFLAGS))
33921       return true;
33922 
33923   return false;
33924 }
33925 
33926 /// Utility function to emit xbegin specifying the start of an RTM region.
emitXBegin(MachineInstr & MI,MachineBasicBlock * MBB,const TargetInstrInfo * TII)33927 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
33928                                      const TargetInstrInfo *TII) {
33929   const MIMetadata MIMD(MI);
33930 
33931   const BasicBlock *BB = MBB->getBasicBlock();
33932   MachineFunction::iterator I = ++MBB->getIterator();
33933 
33934   // For the v = xbegin(), we generate
33935   //
33936   // thisMBB:
33937   //  xbegin sinkMBB
33938   //
33939   // mainMBB:
33940   //  s0 = -1
33941   //
33942   // fallBB:
33943   //  eax = # XABORT_DEF
33944   //  s1 = eax
33945   //
33946   // sinkMBB:
33947   //  v = phi(s0/mainBB, s1/fallBB)
33948 
33949   MachineBasicBlock *thisMBB = MBB;
33950   MachineFunction *MF = MBB->getParent();
33951   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
33952   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
33953   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
33954   MF->insert(I, mainMBB);
33955   MF->insert(I, fallMBB);
33956   MF->insert(I, sinkMBB);
33957 
33958   if (isEFLAGSLiveAfter(MI, MBB)) {
33959     mainMBB->addLiveIn(X86::EFLAGS);
33960     fallMBB->addLiveIn(X86::EFLAGS);
33961     sinkMBB->addLiveIn(X86::EFLAGS);
33962   }
33963 
33964   // Transfer the remainder of BB and its successor edges to sinkMBB.
33965   sinkMBB->splice(sinkMBB->begin(), MBB,
33966                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
33967   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
33968 
33969   MachineRegisterInfo &MRI = MF->getRegInfo();
33970   Register DstReg = MI.getOperand(0).getReg();
33971   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
33972   Register mainDstReg = MRI.createVirtualRegister(RC);
33973   Register fallDstReg = MRI.createVirtualRegister(RC);
33974 
33975   // thisMBB:
33976   //  xbegin fallMBB
33977   //  # fallthrough to mainMBB
33978   //  # abortion to fallMBB
33979   BuildMI(thisMBB, MIMD, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
33980   thisMBB->addSuccessor(mainMBB);
33981   thisMBB->addSuccessor(fallMBB);
33982 
33983   // mainMBB:
33984   //  mainDstReg := -1
33985   BuildMI(mainMBB, MIMD, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
33986   BuildMI(mainMBB, MIMD, TII->get(X86::JMP_1)).addMBB(sinkMBB);
33987   mainMBB->addSuccessor(sinkMBB);
33988 
33989   // fallMBB:
33990   //  ; pseudo instruction to model hardware's definition from XABORT
33991   //  EAX := XABORT_DEF
33992   //  fallDstReg := EAX
33993   BuildMI(fallMBB, MIMD, TII->get(X86::XABORT_DEF));
33994   BuildMI(fallMBB, MIMD, TII->get(TargetOpcode::COPY), fallDstReg)
33995       .addReg(X86::EAX);
33996   fallMBB->addSuccessor(sinkMBB);
33997 
33998   // sinkMBB:
33999   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
34000   BuildMI(*sinkMBB, sinkMBB->begin(), MIMD, TII->get(X86::PHI), DstReg)
34001       .addReg(mainDstReg).addMBB(mainMBB)
34002       .addReg(fallDstReg).addMBB(fallMBB);
34003 
34004   MI.eraseFromParent();
34005   return sinkMBB;
34006 }
34007 
34008 MachineBasicBlock *
EmitVAARGWithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const34009 X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
34010                                                MachineBasicBlock *MBB) const {
34011   // Emit va_arg instruction on X86-64.
34012 
34013   // Operands to this pseudo-instruction:
34014   // 0  ) Output        : destination address (reg)
34015   // 1-5) Input         : va_list address (addr, i64mem)
34016   // 6  ) ArgSize       : Size (in bytes) of vararg type
34017   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
34018   // 8  ) Align         : Alignment of type
34019   // 9  ) EFLAGS (implicit-def)
34020 
34021   assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!");
34022   static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
34023 
34024   Register DestReg = MI.getOperand(0).getReg();
34025   MachineOperand &Base = MI.getOperand(1);
34026   MachineOperand &Scale = MI.getOperand(2);
34027   MachineOperand &Index = MI.getOperand(3);
34028   MachineOperand &Disp = MI.getOperand(4);
34029   MachineOperand &Segment = MI.getOperand(5);
34030   unsigned ArgSize = MI.getOperand(6).getImm();
34031   unsigned ArgMode = MI.getOperand(7).getImm();
34032   Align Alignment = Align(MI.getOperand(8).getImm());
34033 
34034   MachineFunction *MF = MBB->getParent();
34035 
34036   // Memory Reference
34037   assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand");
34038 
34039   MachineMemOperand *OldMMO = MI.memoperands().front();
34040 
34041   // Clone the MMO into two separate MMOs for loading and storing
34042   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
34043       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
34044   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
34045       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
34046 
34047   // Machine Information
34048   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34049   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
34050   const TargetRegisterClass *AddrRegClass =
34051       getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
34052   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
34053   const MIMetadata MIMD(MI);
34054 
34055   // struct va_list {
34056   //   i32   gp_offset
34057   //   i32   fp_offset
34058   //   i64   overflow_area (address)
34059   //   i64   reg_save_area (address)
34060   // }
34061   // sizeof(va_list) = 24
34062   // alignment(va_list) = 8
34063 
34064   unsigned TotalNumIntRegs = 6;
34065   unsigned TotalNumXMMRegs = 8;
34066   bool UseGPOffset = (ArgMode == 1);
34067   bool UseFPOffset = (ArgMode == 2);
34068   unsigned MaxOffset = TotalNumIntRegs * 8 +
34069                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
34070 
34071   /* Align ArgSize to a multiple of 8 */
34072   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
34073   bool NeedsAlign = (Alignment > 8);
34074 
34075   MachineBasicBlock *thisMBB = MBB;
34076   MachineBasicBlock *overflowMBB;
34077   MachineBasicBlock *offsetMBB;
34078   MachineBasicBlock *endMBB;
34079 
34080   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
34081   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
34082   unsigned OffsetReg = 0;
34083 
34084   if (!UseGPOffset && !UseFPOffset) {
34085     // If we only pull from the overflow region, we don't create a branch.
34086     // We don't need to alter control flow.
34087     OffsetDestReg = 0; // unused
34088     OverflowDestReg = DestReg;
34089 
34090     offsetMBB = nullptr;
34091     overflowMBB = thisMBB;
34092     endMBB = thisMBB;
34093   } else {
34094     // First emit code to check if gp_offset (or fp_offset) is below the bound.
34095     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
34096     // If not, pull from overflow_area. (branch to overflowMBB)
34097     //
34098     //       thisMBB
34099     //         |     .
34100     //         |        .
34101     //     offsetMBB   overflowMBB
34102     //         |        .
34103     //         |     .
34104     //        endMBB
34105 
34106     // Registers for the PHI in endMBB
34107     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
34108     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
34109 
34110     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
34111     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34112     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34113     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34114 
34115     MachineFunction::iterator MBBIter = ++MBB->getIterator();
34116 
34117     // Insert the new basic blocks
34118     MF->insert(MBBIter, offsetMBB);
34119     MF->insert(MBBIter, overflowMBB);
34120     MF->insert(MBBIter, endMBB);
34121 
34122     // Transfer the remainder of MBB and its successor edges to endMBB.
34123     endMBB->splice(endMBB->begin(), thisMBB,
34124                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
34125     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
34126 
34127     // Make offsetMBB and overflowMBB successors of thisMBB
34128     thisMBB->addSuccessor(offsetMBB);
34129     thisMBB->addSuccessor(overflowMBB);
34130 
34131     // endMBB is a successor of both offsetMBB and overflowMBB
34132     offsetMBB->addSuccessor(endMBB);
34133     overflowMBB->addSuccessor(endMBB);
34134 
34135     // Load the offset value into a register
34136     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
34137     BuildMI(thisMBB, MIMD, TII->get(X86::MOV32rm), OffsetReg)
34138         .add(Base)
34139         .add(Scale)
34140         .add(Index)
34141         .addDisp(Disp, UseFPOffset ? 4 : 0)
34142         .add(Segment)
34143         .setMemRefs(LoadOnlyMMO);
34144 
34145     // Check if there is enough room left to pull this argument.
34146     BuildMI(thisMBB, MIMD, TII->get(X86::CMP32ri))
34147       .addReg(OffsetReg)
34148       .addImm(MaxOffset + 8 - ArgSizeA8);
34149 
34150     // Branch to "overflowMBB" if offset >= max
34151     // Fall through to "offsetMBB" otherwise
34152     BuildMI(thisMBB, MIMD, TII->get(X86::JCC_1))
34153       .addMBB(overflowMBB).addImm(X86::COND_AE);
34154   }
34155 
34156   // In offsetMBB, emit code to use the reg_save_area.
34157   if (offsetMBB) {
34158     assert(OffsetReg != 0);
34159 
34160     // Read the reg_save_area address.
34161     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
34162     BuildMI(
34163         offsetMBB, MIMD,
34164         TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
34165         RegSaveReg)
34166         .add(Base)
34167         .add(Scale)
34168         .add(Index)
34169         .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
34170         .add(Segment)
34171         .setMemRefs(LoadOnlyMMO);
34172 
34173     if (Subtarget.isTarget64BitLP64()) {
34174       // Zero-extend the offset
34175       Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
34176       BuildMI(offsetMBB, MIMD, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
34177           .addImm(0)
34178           .addReg(OffsetReg)
34179           .addImm(X86::sub_32bit);
34180 
34181       // Add the offset to the reg_save_area to get the final address.
34182       BuildMI(offsetMBB, MIMD, TII->get(X86::ADD64rr), OffsetDestReg)
34183           .addReg(OffsetReg64)
34184           .addReg(RegSaveReg);
34185     } else {
34186       // Add the offset to the reg_save_area to get the final address.
34187       BuildMI(offsetMBB, MIMD, TII->get(X86::ADD32rr), OffsetDestReg)
34188           .addReg(OffsetReg)
34189           .addReg(RegSaveReg);
34190     }
34191 
34192     // Compute the offset for the next argument
34193     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
34194     BuildMI(offsetMBB, MIMD, TII->get(X86::ADD32ri), NextOffsetReg)
34195       .addReg(OffsetReg)
34196       .addImm(UseFPOffset ? 16 : 8);
34197 
34198     // Store it back into the va_list.
34199     BuildMI(offsetMBB, MIMD, TII->get(X86::MOV32mr))
34200         .add(Base)
34201         .add(Scale)
34202         .add(Index)
34203         .addDisp(Disp, UseFPOffset ? 4 : 0)
34204         .add(Segment)
34205         .addReg(NextOffsetReg)
34206         .setMemRefs(StoreOnlyMMO);
34207 
34208     // Jump to endMBB
34209     BuildMI(offsetMBB, MIMD, TII->get(X86::JMP_1))
34210       .addMBB(endMBB);
34211   }
34212 
34213   //
34214   // Emit code to use overflow area
34215   //
34216 
34217   // Load the overflow_area address into a register.
34218   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
34219   BuildMI(overflowMBB, MIMD,
34220           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
34221           OverflowAddrReg)
34222       .add(Base)
34223       .add(Scale)
34224       .add(Index)
34225       .addDisp(Disp, 8)
34226       .add(Segment)
34227       .setMemRefs(LoadOnlyMMO);
34228 
34229   // If we need to align it, do so. Otherwise, just copy the address
34230   // to OverflowDestReg.
34231   if (NeedsAlign) {
34232     // Align the overflow address
34233     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
34234 
34235     // aligned_addr = (addr + (align-1)) & ~(align-1)
34236     BuildMI(
34237         overflowMBB, MIMD,
34238         TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
34239         TmpReg)
34240         .addReg(OverflowAddrReg)
34241         .addImm(Alignment.value() - 1);
34242 
34243     BuildMI(
34244         overflowMBB, MIMD,
34245         TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
34246         OverflowDestReg)
34247         .addReg(TmpReg)
34248         .addImm(~(uint64_t)(Alignment.value() - 1));
34249   } else {
34250     BuildMI(overflowMBB, MIMD, TII->get(TargetOpcode::COPY), OverflowDestReg)
34251       .addReg(OverflowAddrReg);
34252   }
34253 
34254   // Compute the next overflow address after this argument.
34255   // (the overflow address should be kept 8-byte aligned)
34256   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
34257   BuildMI(
34258       overflowMBB, MIMD,
34259       TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
34260       NextAddrReg)
34261       .addReg(OverflowDestReg)
34262       .addImm(ArgSizeA8);
34263 
34264   // Store the new overflow address.
34265   BuildMI(overflowMBB, MIMD,
34266           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
34267       .add(Base)
34268       .add(Scale)
34269       .add(Index)
34270       .addDisp(Disp, 8)
34271       .add(Segment)
34272       .addReg(NextAddrReg)
34273       .setMemRefs(StoreOnlyMMO);
34274 
34275   // If we branched, emit the PHI to the front of endMBB.
34276   if (offsetMBB) {
34277     BuildMI(*endMBB, endMBB->begin(), MIMD,
34278             TII->get(X86::PHI), DestReg)
34279       .addReg(OffsetDestReg).addMBB(offsetMBB)
34280       .addReg(OverflowDestReg).addMBB(overflowMBB);
34281   }
34282 
34283   // Erase the pseudo instruction
34284   MI.eraseFromParent();
34285 
34286   return endMBB;
34287 }
34288 
34289 // The EFLAGS operand of SelectItr might be missing a kill marker
34290 // because there were multiple uses of EFLAGS, and ISel didn't know
34291 // which to mark. Figure out whether SelectItr should have had a
34292 // kill marker, and set it if it should. Returns the correct kill
34293 // marker value.
checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,MachineBasicBlock * BB,const TargetRegisterInfo * TRI)34294 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
34295                                      MachineBasicBlock* BB,
34296                                      const TargetRegisterInfo* TRI) {
34297   if (isEFLAGSLiveAfter(SelectItr, BB))
34298     return false;
34299 
34300   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
34301   // out. SelectMI should have a kill flag on EFLAGS.
34302   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
34303   return true;
34304 }
34305 
34306 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
34307 // together with other CMOV pseudo-opcodes into a single basic-block with
34308 // conditional jump around it.
isCMOVPseudo(MachineInstr & MI)34309 static bool isCMOVPseudo(MachineInstr &MI) {
34310   switch (MI.getOpcode()) {
34311   case X86::CMOV_FR16:
34312   case X86::CMOV_FR16X:
34313   case X86::CMOV_FR32:
34314   case X86::CMOV_FR32X:
34315   case X86::CMOV_FR64:
34316   case X86::CMOV_FR64X:
34317   case X86::CMOV_GR8:
34318   case X86::CMOV_GR16:
34319   case X86::CMOV_GR32:
34320   case X86::CMOV_RFP32:
34321   case X86::CMOV_RFP64:
34322   case X86::CMOV_RFP80:
34323   case X86::CMOV_VR64:
34324   case X86::CMOV_VR128:
34325   case X86::CMOV_VR128X:
34326   case X86::CMOV_VR256:
34327   case X86::CMOV_VR256X:
34328   case X86::CMOV_VR512:
34329   case X86::CMOV_VK1:
34330   case X86::CMOV_VK2:
34331   case X86::CMOV_VK4:
34332   case X86::CMOV_VK8:
34333   case X86::CMOV_VK16:
34334   case X86::CMOV_VK32:
34335   case X86::CMOV_VK64:
34336     return true;
34337 
34338   default:
34339     return false;
34340   }
34341 }
34342 
34343 // Helper function, which inserts PHI functions into SinkMBB:
34344 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
34345 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
34346 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
34347 // the last PHI function inserted.
createPHIsForCMOVsInSinkBB(MachineBasicBlock::iterator MIItBegin,MachineBasicBlock::iterator MIItEnd,MachineBasicBlock * TrueMBB,MachineBasicBlock * FalseMBB,MachineBasicBlock * SinkMBB)34348 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
34349     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
34350     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
34351     MachineBasicBlock *SinkMBB) {
34352   MachineFunction *MF = TrueMBB->getParent();
34353   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
34354   const MIMetadata MIMD(*MIItBegin);
34355 
34356   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
34357   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
34358 
34359   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
34360 
34361   // As we are creating the PHIs, we have to be careful if there is more than
34362   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
34363   // PHIs have to reference the individual true/false inputs from earlier PHIs.
34364   // That also means that PHI construction must work forward from earlier to
34365   // later, and that the code must maintain a mapping from earlier PHI's
34366   // destination registers, and the registers that went into the PHI.
34367   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
34368   MachineInstrBuilder MIB;
34369 
34370   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
34371     Register DestReg = MIIt->getOperand(0).getReg();
34372     Register Op1Reg = MIIt->getOperand(1).getReg();
34373     Register Op2Reg = MIIt->getOperand(2).getReg();
34374 
34375     // If this CMOV we are generating is the opposite condition from
34376     // the jump we generated, then we have to swap the operands for the
34377     // PHI that is going to be generated.
34378     if (MIIt->getOperand(3).getImm() == OppCC)
34379       std::swap(Op1Reg, Op2Reg);
34380 
34381     if (RegRewriteTable.contains(Op1Reg))
34382       Op1Reg = RegRewriteTable[Op1Reg].first;
34383 
34384     if (RegRewriteTable.contains(Op2Reg))
34385       Op2Reg = RegRewriteTable[Op2Reg].second;
34386 
34387     MIB =
34388         BuildMI(*SinkMBB, SinkInsertionPoint, MIMD, TII->get(X86::PHI), DestReg)
34389             .addReg(Op1Reg)
34390             .addMBB(FalseMBB)
34391             .addReg(Op2Reg)
34392             .addMBB(TrueMBB);
34393 
34394     // Add this PHI to the rewrite table.
34395     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
34396   }
34397 
34398   return MIB;
34399 }
34400 
34401 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
34402 MachineBasicBlock *
EmitLoweredCascadedSelect(MachineInstr & FirstCMOV,MachineInstr & SecondCascadedCMOV,MachineBasicBlock * ThisMBB) const34403 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
34404                                              MachineInstr &SecondCascadedCMOV,
34405                                              MachineBasicBlock *ThisMBB) const {
34406   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34407   const MIMetadata MIMD(FirstCMOV);
34408 
34409   // We lower cascaded CMOVs such as
34410   //
34411   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
34412   //
34413   // to two successive branches.
34414   //
34415   // Without this, we would add a PHI between the two jumps, which ends up
34416   // creating a few copies all around. For instance, for
34417   //
34418   //    (sitofp (zext (fcmp une)))
34419   //
34420   // we would generate:
34421   //
34422   //         ucomiss %xmm1, %xmm0
34423   //         movss  <1.0f>, %xmm0
34424   //         movaps  %xmm0, %xmm1
34425   //         jne     .LBB5_2
34426   //         xorps   %xmm1, %xmm1
34427   // .LBB5_2:
34428   //         jp      .LBB5_4
34429   //         movaps  %xmm1, %xmm0
34430   // .LBB5_4:
34431   //         retq
34432   //
34433   // because this custom-inserter would have generated:
34434   //
34435   //   A
34436   //   | \
34437   //   |  B
34438   //   | /
34439   //   C
34440   //   | \
34441   //   |  D
34442   //   | /
34443   //   E
34444   //
34445   // A: X = ...; Y = ...
34446   // B: empty
34447   // C: Z = PHI [X, A], [Y, B]
34448   // D: empty
34449   // E: PHI [X, C], [Z, D]
34450   //
34451   // If we lower both CMOVs in a single step, we can instead generate:
34452   //
34453   //   A
34454   //   | \
34455   //   |  C
34456   //   | /|
34457   //   |/ |
34458   //   |  |
34459   //   |  D
34460   //   | /
34461   //   E
34462   //
34463   // A: X = ...; Y = ...
34464   // D: empty
34465   // E: PHI [X, A], [X, C], [Y, D]
34466   //
34467   // Which, in our sitofp/fcmp example, gives us something like:
34468   //
34469   //         ucomiss %xmm1, %xmm0
34470   //         movss  <1.0f>, %xmm0
34471   //         jne     .LBB5_4
34472   //         jp      .LBB5_4
34473   //         xorps   %xmm0, %xmm0
34474   // .LBB5_4:
34475   //         retq
34476   //
34477 
34478   // We lower cascaded CMOV into two successive branches to the same block.
34479   // EFLAGS is used by both, so mark it as live in the second.
34480   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
34481   MachineFunction *F = ThisMBB->getParent();
34482   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
34483   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
34484   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
34485 
34486   MachineFunction::iterator It = ++ThisMBB->getIterator();
34487   F->insert(It, FirstInsertedMBB);
34488   F->insert(It, SecondInsertedMBB);
34489   F->insert(It, SinkMBB);
34490 
34491   // For a cascaded CMOV, we lower it to two successive branches to
34492   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
34493   // the FirstInsertedMBB.
34494   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
34495 
34496   // If the EFLAGS register isn't dead in the terminator, then claim that it's
34497   // live into the sink and copy blocks.
34498   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
34499   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
34500       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
34501     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
34502     SinkMBB->addLiveIn(X86::EFLAGS);
34503   }
34504 
34505   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
34506   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
34507                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
34508                   ThisMBB->end());
34509   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
34510 
34511   // Fallthrough block for ThisMBB.
34512   ThisMBB->addSuccessor(FirstInsertedMBB);
34513   // The true block target of the first branch is always SinkMBB.
34514   ThisMBB->addSuccessor(SinkMBB);
34515   // Fallthrough block for FirstInsertedMBB.
34516   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
34517   // The true block for the branch of FirstInsertedMBB.
34518   FirstInsertedMBB->addSuccessor(SinkMBB);
34519   // This is fallthrough.
34520   SecondInsertedMBB->addSuccessor(SinkMBB);
34521 
34522   // Create the conditional branch instructions.
34523   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
34524   BuildMI(ThisMBB, MIMD, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
34525 
34526   X86::CondCode SecondCC =
34527       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
34528   BuildMI(FirstInsertedMBB, MIMD, TII->get(X86::JCC_1))
34529       .addMBB(SinkMBB)
34530       .addImm(SecondCC);
34531 
34532   //  SinkMBB:
34533   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
34534   Register DestReg = SecondCascadedCMOV.getOperand(0).getReg();
34535   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
34536   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
34537   MachineInstrBuilder MIB =
34538       BuildMI(*SinkMBB, SinkMBB->begin(), MIMD, TII->get(X86::PHI), DestReg)
34539           .addReg(Op1Reg)
34540           .addMBB(SecondInsertedMBB)
34541           .addReg(Op2Reg)
34542           .addMBB(ThisMBB);
34543 
34544   // The second SecondInsertedMBB provides the same incoming value as the
34545   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
34546   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
34547 
34548   // Now remove the CMOVs.
34549   FirstCMOV.eraseFromParent();
34550   SecondCascadedCMOV.eraseFromParent();
34551 
34552   return SinkMBB;
34553 }
34554 
34555 MachineBasicBlock *
EmitLoweredSelect(MachineInstr & MI,MachineBasicBlock * ThisMBB) const34556 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
34557                                      MachineBasicBlock *ThisMBB) const {
34558   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34559   const MIMetadata MIMD(MI);
34560 
34561   // To "insert" a SELECT_CC instruction, we actually have to insert the
34562   // diamond control-flow pattern.  The incoming instruction knows the
34563   // destination vreg to set, the condition code register to branch on, the
34564   // true/false values to select between and a branch opcode to use.
34565 
34566   //  ThisMBB:
34567   //  ...
34568   //   TrueVal = ...
34569   //   cmpTY ccX, r1, r2
34570   //   bCC copy1MBB
34571   //   fallthrough --> FalseMBB
34572 
34573   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
34574   // as described above, by inserting a BB, and then making a PHI at the join
34575   // point to select the true and false operands of the CMOV in the PHI.
34576   //
34577   // The code also handles two different cases of multiple CMOV opcodes
34578   // in a row.
34579   //
34580   // Case 1:
34581   // In this case, there are multiple CMOVs in a row, all which are based on
34582   // the same condition setting (or the exact opposite condition setting).
34583   // In this case we can lower all the CMOVs using a single inserted BB, and
34584   // then make a number of PHIs at the join point to model the CMOVs. The only
34585   // trickiness here, is that in a case like:
34586   //
34587   // t2 = CMOV cond1 t1, f1
34588   // t3 = CMOV cond1 t2, f2
34589   //
34590   // when rewriting this into PHIs, we have to perform some renaming on the
34591   // temps since you cannot have a PHI operand refer to a PHI result earlier
34592   // in the same block.  The "simple" but wrong lowering would be:
34593   //
34594   // t2 = PHI t1(BB1), f1(BB2)
34595   // t3 = PHI t2(BB1), f2(BB2)
34596   //
34597   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
34598   // renaming is to note that on the path through BB1, t2 is really just a
34599   // copy of t1, and do that renaming, properly generating:
34600   //
34601   // t2 = PHI t1(BB1), f1(BB2)
34602   // t3 = PHI t1(BB1), f2(BB2)
34603   //
34604   // Case 2:
34605   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
34606   // function - EmitLoweredCascadedSelect.
34607 
34608   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
34609   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
34610   MachineInstr *LastCMOV = &MI;
34611   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
34612 
34613   // Check for case 1, where there are multiple CMOVs with the same condition
34614   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
34615   // number of jumps the most.
34616 
34617   if (isCMOVPseudo(MI)) {
34618     // See if we have a string of CMOVS with the same condition. Skip over
34619     // intervening debug insts.
34620     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
34621            (NextMIIt->getOperand(3).getImm() == CC ||
34622             NextMIIt->getOperand(3).getImm() == OppCC)) {
34623       LastCMOV = &*NextMIIt;
34624       NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
34625     }
34626   }
34627 
34628   // This checks for case 2, but only do this if we didn't already find
34629   // case 1, as indicated by LastCMOV == MI.
34630   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
34631       NextMIIt->getOpcode() == MI.getOpcode() &&
34632       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
34633       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
34634       NextMIIt->getOperand(1).isKill()) {
34635     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
34636   }
34637 
34638   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
34639   MachineFunction *F = ThisMBB->getParent();
34640   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
34641   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
34642 
34643   MachineFunction::iterator It = ++ThisMBB->getIterator();
34644   F->insert(It, FalseMBB);
34645   F->insert(It, SinkMBB);
34646 
34647   // Set the call frame size on entry to the new basic blocks.
34648   unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
34649   FalseMBB->setCallFrameSize(CallFrameSize);
34650   SinkMBB->setCallFrameSize(CallFrameSize);
34651 
34652   // If the EFLAGS register isn't dead in the terminator, then claim that it's
34653   // live into the sink and copy blocks.
34654   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
34655   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
34656       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
34657     FalseMBB->addLiveIn(X86::EFLAGS);
34658     SinkMBB->addLiveIn(X86::EFLAGS);
34659   }
34660 
34661   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
34662   auto DbgRange = llvm::make_range(MachineBasicBlock::iterator(MI),
34663                                    MachineBasicBlock::iterator(LastCMOV));
34664   for (MachineInstr &MI : llvm::make_early_inc_range(DbgRange))
34665     if (MI.isDebugInstr())
34666       SinkMBB->push_back(MI.removeFromParent());
34667 
34668   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
34669   SinkMBB->splice(SinkMBB->end(), ThisMBB,
34670                   std::next(MachineBasicBlock::iterator(LastCMOV)),
34671                   ThisMBB->end());
34672   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
34673 
34674   // Fallthrough block for ThisMBB.
34675   ThisMBB->addSuccessor(FalseMBB);
34676   // The true block target of the first (or only) branch is always a SinkMBB.
34677   ThisMBB->addSuccessor(SinkMBB);
34678   // Fallthrough block for FalseMBB.
34679   FalseMBB->addSuccessor(SinkMBB);
34680 
34681   // Create the conditional branch instruction.
34682   BuildMI(ThisMBB, MIMD, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
34683 
34684   //  SinkMBB:
34685   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
34686   //  ...
34687   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
34688   MachineBasicBlock::iterator MIItEnd =
34689       std::next(MachineBasicBlock::iterator(LastCMOV));
34690   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
34691 
34692   // Now remove the CMOV(s).
34693   ThisMBB->erase(MIItBegin, MIItEnd);
34694 
34695   return SinkMBB;
34696 }
34697 
getSUBriOpcode(bool IsLP64)34698 static unsigned getSUBriOpcode(bool IsLP64) {
34699   if (IsLP64)
34700     return X86::SUB64ri32;
34701   else
34702     return X86::SUB32ri;
34703 }
34704 
34705 MachineBasicBlock *
EmitLoweredProbedAlloca(MachineInstr & MI,MachineBasicBlock * MBB) const34706 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
34707                                            MachineBasicBlock *MBB) const {
34708   MachineFunction *MF = MBB->getParent();
34709   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34710   const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
34711   const MIMetadata MIMD(MI);
34712   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
34713 
34714   const unsigned ProbeSize = getStackProbeSize(*MF);
34715 
34716   MachineRegisterInfo &MRI = MF->getRegInfo();
34717   MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34718   MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34719   MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34720 
34721   MachineFunction::iterator MBBIter = ++MBB->getIterator();
34722   MF->insert(MBBIter, testMBB);
34723   MF->insert(MBBIter, blockMBB);
34724   MF->insert(MBBIter, tailMBB);
34725 
34726   Register sizeVReg = MI.getOperand(1).getReg();
34727 
34728   Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
34729 
34730   Register TmpStackPtr = MRI.createVirtualRegister(
34731       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
34732   Register FinalStackPtr = MRI.createVirtualRegister(
34733       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
34734 
34735   BuildMI(*MBB, {MI}, MIMD, TII->get(TargetOpcode::COPY), TmpStackPtr)
34736       .addReg(physSPReg);
34737   {
34738     const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
34739     BuildMI(*MBB, {MI}, MIMD, TII->get(Opc), FinalStackPtr)
34740         .addReg(TmpStackPtr)
34741         .addReg(sizeVReg);
34742   }
34743 
34744   // test rsp size
34745 
34746   BuildMI(testMBB, MIMD,
34747           TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
34748       .addReg(FinalStackPtr)
34749       .addReg(physSPReg);
34750 
34751   BuildMI(testMBB, MIMD, TII->get(X86::JCC_1))
34752       .addMBB(tailMBB)
34753       .addImm(X86::COND_GE);
34754   testMBB->addSuccessor(blockMBB);
34755   testMBB->addSuccessor(tailMBB);
34756 
34757   // Touch the block then extend it. This is done on the opposite side of
34758   // static probe where we allocate then touch, to avoid the need of probing the
34759   // tail of the static alloca. Possible scenarios are:
34760   //
34761   //       + ---- <- ------------ <- ------------- <- ------------ +
34762   //       |                                                       |
34763   // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
34764   //                                                               |                                                               |
34765   //                                                               + <- ----------- <- ------------ <- ----------- <- ------------ +
34766   //
34767   // The property we want to enforce is to never have more than [page alloc] between two probes.
34768 
34769   const unsigned XORMIOpc =
34770       TFI.Uses64BitFramePtr ? X86::XOR64mi32 : X86::XOR32mi;
34771   addRegOffset(BuildMI(blockMBB, MIMD, TII->get(XORMIOpc)), physSPReg, false, 0)
34772       .addImm(0);
34773 
34774   BuildMI(blockMBB, MIMD, TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr)),
34775           physSPReg)
34776       .addReg(physSPReg)
34777       .addImm(ProbeSize);
34778 
34779   BuildMI(blockMBB, MIMD, TII->get(X86::JMP_1)).addMBB(testMBB);
34780   blockMBB->addSuccessor(testMBB);
34781 
34782   // Replace original instruction by the expected stack ptr
34783   BuildMI(tailMBB, MIMD, TII->get(TargetOpcode::COPY),
34784           MI.getOperand(0).getReg())
34785       .addReg(FinalStackPtr);
34786 
34787   tailMBB->splice(tailMBB->end(), MBB,
34788                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
34789   tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
34790   MBB->addSuccessor(testMBB);
34791 
34792   // Delete the original pseudo instruction.
34793   MI.eraseFromParent();
34794 
34795   // And we're done.
34796   return tailMBB;
34797 }
34798 
34799 MachineBasicBlock *
EmitLoweredSegAlloca(MachineInstr & MI,MachineBasicBlock * BB) const34800 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
34801                                         MachineBasicBlock *BB) const {
34802   MachineFunction *MF = BB->getParent();
34803   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
34804   const MIMetadata MIMD(MI);
34805   const BasicBlock *LLVM_BB = BB->getBasicBlock();
34806 
34807   assert(MF->shouldSplitStack());
34808 
34809   const bool Is64Bit = Subtarget.is64Bit();
34810   const bool IsLP64 = Subtarget.isTarget64BitLP64();
34811 
34812   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
34813   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
34814 
34815   // BB:
34816   //  ... [Till the alloca]
34817   // If stacklet is not large enough, jump to mallocMBB
34818   //
34819   // bumpMBB:
34820   //  Allocate by subtracting from RSP
34821   //  Jump to continueMBB
34822   //
34823   // mallocMBB:
34824   //  Allocate by call to runtime
34825   //
34826   // continueMBB:
34827   //  ...
34828   //  [rest of original BB]
34829   //
34830 
34831   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34832   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34833   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
34834 
34835   MachineRegisterInfo &MRI = MF->getRegInfo();
34836   const TargetRegisterClass *AddrRegClass =
34837       getRegClassFor(getPointerTy(MF->getDataLayout()));
34838 
34839   Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
34840            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
34841            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
34842            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
34843            sizeVReg = MI.getOperand(1).getReg(),
34844            physSPReg =
34845                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
34846 
34847   MachineFunction::iterator MBBIter = ++BB->getIterator();
34848 
34849   MF->insert(MBBIter, bumpMBB);
34850   MF->insert(MBBIter, mallocMBB);
34851   MF->insert(MBBIter, continueMBB);
34852 
34853   continueMBB->splice(continueMBB->begin(), BB,
34854                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
34855   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
34856 
34857   // Add code to the main basic block to check if the stack limit has been hit,
34858   // and if so, jump to mallocMBB otherwise to bumpMBB.
34859   BuildMI(BB, MIMD, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
34860   BuildMI(BB, MIMD, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
34861     .addReg(tmpSPVReg).addReg(sizeVReg);
34862   BuildMI(BB, MIMD, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
34863     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
34864     .addReg(SPLimitVReg);
34865   BuildMI(BB, MIMD, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
34866 
34867   // bumpMBB simply decreases the stack pointer, since we know the current
34868   // stacklet has enough space.
34869   BuildMI(bumpMBB, MIMD, TII->get(TargetOpcode::COPY), physSPReg)
34870     .addReg(SPLimitVReg);
34871   BuildMI(bumpMBB, MIMD, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
34872     .addReg(SPLimitVReg);
34873   BuildMI(bumpMBB, MIMD, TII->get(X86::JMP_1)).addMBB(continueMBB);
34874 
34875   // Calls into a routine in libgcc to allocate more space from the heap.
34876   const uint32_t *RegMask =
34877       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
34878   if (IsLP64) {
34879     BuildMI(mallocMBB, MIMD, TII->get(X86::MOV64rr), X86::RDI)
34880       .addReg(sizeVReg);
34881     BuildMI(mallocMBB, MIMD, TII->get(X86::CALL64pcrel32))
34882       .addExternalSymbol("__morestack_allocate_stack_space")
34883       .addRegMask(RegMask)
34884       .addReg(X86::RDI, RegState::Implicit)
34885       .addReg(X86::RAX, RegState::ImplicitDefine);
34886   } else if (Is64Bit) {
34887     BuildMI(mallocMBB, MIMD, TII->get(X86::MOV32rr), X86::EDI)
34888       .addReg(sizeVReg);
34889     BuildMI(mallocMBB, MIMD, TII->get(X86::CALL64pcrel32))
34890       .addExternalSymbol("__morestack_allocate_stack_space")
34891       .addRegMask(RegMask)
34892       .addReg(X86::EDI, RegState::Implicit)
34893       .addReg(X86::EAX, RegState::ImplicitDefine);
34894   } else {
34895     BuildMI(mallocMBB, MIMD, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
34896       .addImm(12);
34897     BuildMI(mallocMBB, MIMD, TII->get(X86::PUSH32r)).addReg(sizeVReg);
34898     BuildMI(mallocMBB, MIMD, TII->get(X86::CALLpcrel32))
34899       .addExternalSymbol("__morestack_allocate_stack_space")
34900       .addRegMask(RegMask)
34901       .addReg(X86::EAX, RegState::ImplicitDefine);
34902   }
34903 
34904   if (!Is64Bit)
34905     BuildMI(mallocMBB, MIMD, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
34906       .addImm(16);
34907 
34908   BuildMI(mallocMBB, MIMD, TII->get(TargetOpcode::COPY), mallocPtrVReg)
34909     .addReg(IsLP64 ? X86::RAX : X86::EAX);
34910   BuildMI(mallocMBB, MIMD, TII->get(X86::JMP_1)).addMBB(continueMBB);
34911 
34912   // Set up the CFG correctly.
34913   BB->addSuccessor(bumpMBB);
34914   BB->addSuccessor(mallocMBB);
34915   mallocMBB->addSuccessor(continueMBB);
34916   bumpMBB->addSuccessor(continueMBB);
34917 
34918   // Take care of the PHI nodes.
34919   BuildMI(*continueMBB, continueMBB->begin(), MIMD, TII->get(X86::PHI),
34920           MI.getOperand(0).getReg())
34921       .addReg(mallocPtrVReg)
34922       .addMBB(mallocMBB)
34923       .addReg(bumpSPPtrVReg)
34924       .addMBB(bumpMBB);
34925 
34926   // Delete the original pseudo instruction.
34927   MI.eraseFromParent();
34928 
34929   // And we're done.
34930   return continueMBB;
34931 }
34932 
34933 MachineBasicBlock *
EmitLoweredCatchRet(MachineInstr & MI,MachineBasicBlock * BB) const34934 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
34935                                        MachineBasicBlock *BB) const {
34936   MachineFunction *MF = BB->getParent();
34937   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
34938   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
34939   const MIMetadata MIMD(MI);
34940 
34941   assert(!isAsynchronousEHPersonality(
34942              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
34943          "SEH does not use catchret!");
34944 
34945   // Only 32-bit EH needs to worry about manually restoring stack pointers.
34946   if (!Subtarget.is32Bit())
34947     return BB;
34948 
34949   // C++ EH creates a new target block to hold the restore code, and wires up
34950   // the new block to the return destination with a normal JMP_4.
34951   MachineBasicBlock *RestoreMBB =
34952       MF->CreateMachineBasicBlock(BB->getBasicBlock());
34953   assert(BB->succ_size() == 1);
34954   MF->insert(std::next(BB->getIterator()), RestoreMBB);
34955   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
34956   BB->addSuccessor(RestoreMBB);
34957   MI.getOperand(0).setMBB(RestoreMBB);
34958 
34959   // Marking this as an EH pad but not a funclet entry block causes PEI to
34960   // restore stack pointers in the block.
34961   RestoreMBB->setIsEHPad(true);
34962 
34963   auto RestoreMBBI = RestoreMBB->begin();
34964   BuildMI(*RestoreMBB, RestoreMBBI, MIMD, TII.get(X86::JMP_4)).addMBB(TargetMBB);
34965   return BB;
34966 }
34967 
34968 MachineBasicBlock *
EmitLoweredTLSAddr(MachineInstr & MI,MachineBasicBlock * BB) const34969 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
34970                                       MachineBasicBlock *BB) const {
34971   // So, here we replace TLSADDR with the sequence:
34972   // adjust_stackdown -> TLSADDR -> adjust_stackup.
34973   // We need this because TLSADDR is lowered into calls
34974   // inside MC, therefore without the two markers shrink-wrapping
34975   // may push the prologue/epilogue pass them.
34976   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
34977   const MIMetadata MIMD(MI);
34978   MachineFunction &MF = *BB->getParent();
34979 
34980   // Emit CALLSEQ_START right before the instruction.
34981   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
34982   MachineInstrBuilder CallseqStart =
34983       BuildMI(MF, MIMD, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
34984   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
34985 
34986   // Emit CALLSEQ_END right after the instruction.
34987   // We don't call erase from parent because we want to keep the
34988   // original instruction around.
34989   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
34990   MachineInstrBuilder CallseqEnd =
34991       BuildMI(MF, MIMD, TII.get(AdjStackUp)).addImm(0).addImm(0);
34992   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
34993 
34994   return BB;
34995 }
34996 
34997 MachineBasicBlock *
EmitLoweredTLSCall(MachineInstr & MI,MachineBasicBlock * BB) const34998 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
34999                                       MachineBasicBlock *BB) const {
35000   // This is pretty easy.  We're taking the value that we received from
35001   // our load from the relocation, sticking it in either RDI (x86-64)
35002   // or EAX and doing an indirect call.  The return value will then
35003   // be in the normal return register.
35004   MachineFunction *F = BB->getParent();
35005   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35006   const MIMetadata MIMD(MI);
35007 
35008   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
35009   assert(MI.getOperand(3).isGlobal() && "This should be a global");
35010 
35011   // Get a register mask for the lowered call.
35012   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
35013   // proper register mask.
35014   const uint32_t *RegMask =
35015       Subtarget.is64Bit() ?
35016       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
35017       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
35018   if (Subtarget.is64Bit()) {
35019     MachineInstrBuilder MIB =
35020         BuildMI(*BB, MI, MIMD, TII->get(X86::MOV64rm), X86::RDI)
35021             .addReg(X86::RIP)
35022             .addImm(0)
35023             .addReg(0)
35024             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
35025                               MI.getOperand(3).getTargetFlags())
35026             .addReg(0);
35027     MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL64m));
35028     addDirectMem(MIB, X86::RDI);
35029     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
35030   } else if (!isPositionIndependent()) {
35031     MachineInstrBuilder MIB =
35032         BuildMI(*BB, MI, MIMD, TII->get(X86::MOV32rm), X86::EAX)
35033             .addReg(0)
35034             .addImm(0)
35035             .addReg(0)
35036             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
35037                               MI.getOperand(3).getTargetFlags())
35038             .addReg(0);
35039     MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL32m));
35040     addDirectMem(MIB, X86::EAX);
35041     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
35042   } else {
35043     MachineInstrBuilder MIB =
35044         BuildMI(*BB, MI, MIMD, TII->get(X86::MOV32rm), X86::EAX)
35045             .addReg(TII->getGlobalBaseReg(F))
35046             .addImm(0)
35047             .addReg(0)
35048             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
35049                               MI.getOperand(3).getTargetFlags())
35050             .addReg(0);
35051     MIB = BuildMI(*BB, MI, MIMD, TII->get(X86::CALL32m));
35052     addDirectMem(MIB, X86::EAX);
35053     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
35054   }
35055 
35056   MI.eraseFromParent(); // The pseudo instruction is gone now.
35057   return BB;
35058 }
35059 
getOpcodeForIndirectThunk(unsigned RPOpc)35060 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
35061   switch (RPOpc) {
35062   case X86::INDIRECT_THUNK_CALL32:
35063     return X86::CALLpcrel32;
35064   case X86::INDIRECT_THUNK_CALL64:
35065     return X86::CALL64pcrel32;
35066   case X86::INDIRECT_THUNK_TCRETURN32:
35067     return X86::TCRETURNdi;
35068   case X86::INDIRECT_THUNK_TCRETURN64:
35069     return X86::TCRETURNdi64;
35070   }
35071   llvm_unreachable("not indirect thunk opcode");
35072 }
35073 
getIndirectThunkSymbol(const X86Subtarget & Subtarget,unsigned Reg)35074 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
35075                                           unsigned Reg) {
35076   if (Subtarget.useRetpolineExternalThunk()) {
35077     // When using an external thunk for retpolines, we pick names that match the
35078     // names GCC happens to use as well. This helps simplify the implementation
35079     // of the thunks for kernels where they have no easy ability to create
35080     // aliases and are doing non-trivial configuration of the thunk's body. For
35081     // example, the Linux kernel will do boot-time hot patching of the thunk
35082     // bodies and cannot easily export aliases of these to loaded modules.
35083     //
35084     // Note that at any point in the future, we may need to change the semantics
35085     // of how we implement retpolines and at that time will likely change the
35086     // name of the called thunk. Essentially, there is no hard guarantee that
35087     // LLVM will generate calls to specific thunks, we merely make a best-effort
35088     // attempt to help out kernels and other systems where duplicating the
35089     // thunks is costly.
35090     switch (Reg) {
35091     case X86::EAX:
35092       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35093       return "__x86_indirect_thunk_eax";
35094     case X86::ECX:
35095       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35096       return "__x86_indirect_thunk_ecx";
35097     case X86::EDX:
35098       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35099       return "__x86_indirect_thunk_edx";
35100     case X86::EDI:
35101       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35102       return "__x86_indirect_thunk_edi";
35103     case X86::R11:
35104       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
35105       return "__x86_indirect_thunk_r11";
35106     }
35107     llvm_unreachable("unexpected reg for external indirect thunk");
35108   }
35109 
35110   if (Subtarget.useRetpolineIndirectCalls() ||
35111       Subtarget.useRetpolineIndirectBranches()) {
35112     // When targeting an internal COMDAT thunk use an LLVM-specific name.
35113     switch (Reg) {
35114     case X86::EAX:
35115       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35116       return "__llvm_retpoline_eax";
35117     case X86::ECX:
35118       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35119       return "__llvm_retpoline_ecx";
35120     case X86::EDX:
35121       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35122       return "__llvm_retpoline_edx";
35123     case X86::EDI:
35124       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
35125       return "__llvm_retpoline_edi";
35126     case X86::R11:
35127       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
35128       return "__llvm_retpoline_r11";
35129     }
35130     llvm_unreachable("unexpected reg for retpoline");
35131   }
35132 
35133   if (Subtarget.useLVIControlFlowIntegrity()) {
35134     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
35135     return "__llvm_lvi_thunk_r11";
35136   }
35137   llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
35138 }
35139 
35140 MachineBasicBlock *
EmitLoweredIndirectThunk(MachineInstr & MI,MachineBasicBlock * BB) const35141 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
35142                                             MachineBasicBlock *BB) const {
35143   // Copy the virtual register into the R11 physical register and
35144   // call the retpoline thunk.
35145   const MIMetadata MIMD(MI);
35146   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35147   Register CalleeVReg = MI.getOperand(0).getReg();
35148   unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
35149 
35150   // Find an available scratch register to hold the callee. On 64-bit, we can
35151   // just use R11, but we scan for uses anyway to ensure we don't generate
35152   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
35153   // already a register use operand to the call to hold the callee. If none
35154   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
35155   // register and ESI is the base pointer to realigned stack frames with VLAs.
35156   SmallVector<unsigned, 3> AvailableRegs;
35157   if (Subtarget.is64Bit())
35158     AvailableRegs.push_back(X86::R11);
35159   else
35160     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
35161 
35162   // Zero out any registers that are already used.
35163   for (const auto &MO : MI.operands()) {
35164     if (MO.isReg() && MO.isUse())
35165       for (unsigned &Reg : AvailableRegs)
35166         if (Reg == MO.getReg())
35167           Reg = 0;
35168   }
35169 
35170   // Choose the first remaining non-zero available register.
35171   unsigned AvailableReg = 0;
35172   for (unsigned MaybeReg : AvailableRegs) {
35173     if (MaybeReg) {
35174       AvailableReg = MaybeReg;
35175       break;
35176     }
35177   }
35178   if (!AvailableReg)
35179     report_fatal_error("calling convention incompatible with retpoline, no "
35180                        "available registers");
35181 
35182   const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
35183 
35184   BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), AvailableReg)
35185       .addReg(CalleeVReg);
35186   MI.getOperand(0).ChangeToES(Symbol);
35187   MI.setDesc(TII->get(Opc));
35188   MachineInstrBuilder(*BB->getParent(), &MI)
35189       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
35190   return BB;
35191 }
35192 
35193 /// SetJmp implies future control flow change upon calling the corresponding
35194 /// LongJmp.
35195 /// Instead of using the 'return' instruction, the long jump fixes the stack and
35196 /// performs an indirect branch. To do so it uses the registers that were stored
35197 /// in the jump buffer (when calling SetJmp).
35198 /// In case the shadow stack is enabled we need to fix it as well, because some
35199 /// return addresses will be skipped.
35200 /// The function will save the SSP for future fixing in the function
35201 /// emitLongJmpShadowStackFix.
35202 /// \sa emitLongJmpShadowStackFix
35203 /// \param [in] MI The temporary Machine Instruction for the builtin.
35204 /// \param [in] MBB The Machine Basic Block that will be modified.
emitSetJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const35205 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
35206                                                  MachineBasicBlock *MBB) const {
35207   const MIMetadata MIMD(MI);
35208   MachineFunction *MF = MBB->getParent();
35209   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35210   MachineRegisterInfo &MRI = MF->getRegInfo();
35211   MachineInstrBuilder MIB;
35212 
35213   // Memory Reference.
35214   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35215                                            MI.memoperands_end());
35216 
35217   // Initialize a register with zero.
35218   MVT PVT = getPointerTy(MF->getDataLayout());
35219   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
35220   Register ZReg = MRI.createVirtualRegister(PtrRC);
35221   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
35222   BuildMI(*MBB, MI, MIMD, TII->get(XorRROpc))
35223       .addDef(ZReg)
35224       .addReg(ZReg, RegState::Undef)
35225       .addReg(ZReg, RegState::Undef);
35226 
35227   // Read the current SSP Register value to the zeroed register.
35228   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
35229   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
35230   BuildMI(*MBB, MI, MIMD, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
35231 
35232   // Write the SSP register value to offset 3 in input memory buffer.
35233   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35234   MIB = BuildMI(*MBB, MI, MIMD, TII->get(PtrStoreOpc));
35235   const int64_t SSPOffset = 3 * PVT.getStoreSize();
35236   const unsigned MemOpndSlot = 1;
35237   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35238     if (i == X86::AddrDisp)
35239       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
35240     else
35241       MIB.add(MI.getOperand(MemOpndSlot + i));
35242   }
35243   MIB.addReg(SSPCopyReg);
35244   MIB.setMemRefs(MMOs);
35245 }
35246 
35247 MachineBasicBlock *
emitEHSjLjSetJmp(MachineInstr & MI,MachineBasicBlock * MBB) const35248 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
35249                                     MachineBasicBlock *MBB) const {
35250   const MIMetadata MIMD(MI);
35251   MachineFunction *MF = MBB->getParent();
35252   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35253   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
35254   MachineRegisterInfo &MRI = MF->getRegInfo();
35255 
35256   const BasicBlock *BB = MBB->getBasicBlock();
35257   MachineFunction::iterator I = ++MBB->getIterator();
35258 
35259   // Memory Reference
35260   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35261                                            MI.memoperands_end());
35262 
35263   unsigned DstReg;
35264   unsigned MemOpndSlot = 0;
35265 
35266   unsigned CurOp = 0;
35267 
35268   DstReg = MI.getOperand(CurOp++).getReg();
35269   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
35270   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
35271   (void)TRI;
35272   Register mainDstReg = MRI.createVirtualRegister(RC);
35273   Register restoreDstReg = MRI.createVirtualRegister(RC);
35274 
35275   MemOpndSlot = CurOp;
35276 
35277   MVT PVT = getPointerTy(MF->getDataLayout());
35278   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
35279          "Invalid Pointer Size!");
35280 
35281   // For v = setjmp(buf), we generate
35282   //
35283   // thisMBB:
35284   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
35285   //  SjLjSetup restoreMBB
35286   //
35287   // mainMBB:
35288   //  v_main = 0
35289   //
35290   // sinkMBB:
35291   //  v = phi(main, restore)
35292   //
35293   // restoreMBB:
35294   //  if base pointer being used, load it from frame
35295   //  v_restore = 1
35296 
35297   MachineBasicBlock *thisMBB = MBB;
35298   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
35299   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
35300   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
35301   MF->insert(I, mainMBB);
35302   MF->insert(I, sinkMBB);
35303   MF->push_back(restoreMBB);
35304   restoreMBB->setMachineBlockAddressTaken();
35305 
35306   MachineInstrBuilder MIB;
35307 
35308   // Transfer the remainder of BB and its successor edges to sinkMBB.
35309   sinkMBB->splice(sinkMBB->begin(), MBB,
35310                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
35311   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
35312 
35313   // thisMBB:
35314   unsigned PtrStoreOpc = 0;
35315   unsigned LabelReg = 0;
35316   const int64_t LabelOffset = 1 * PVT.getStoreSize();
35317   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
35318                      !isPositionIndependent();
35319 
35320   // Prepare IP either in reg or imm.
35321   if (!UseImmLabel) {
35322     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35323     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
35324     LabelReg = MRI.createVirtualRegister(PtrRC);
35325     if (Subtarget.is64Bit()) {
35326       MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::LEA64r), LabelReg)
35327               .addReg(X86::RIP)
35328               .addImm(0)
35329               .addReg(0)
35330               .addMBB(restoreMBB)
35331               .addReg(0);
35332     } else {
35333       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
35334       MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::LEA32r), LabelReg)
35335               .addReg(XII->getGlobalBaseReg(MF))
35336               .addImm(0)
35337               .addReg(0)
35338               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
35339               .addReg(0);
35340     }
35341   } else
35342     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
35343   // Store IP
35344   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrStoreOpc));
35345   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35346     if (i == X86::AddrDisp)
35347       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
35348     else
35349       MIB.add(MI.getOperand(MemOpndSlot + i));
35350   }
35351   if (!UseImmLabel)
35352     MIB.addReg(LabelReg);
35353   else
35354     MIB.addMBB(restoreMBB);
35355   MIB.setMemRefs(MMOs);
35356 
35357   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
35358     emitSetJmpShadowStackFix(MI, thisMBB);
35359   }
35360 
35361   // Setup
35362   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(X86::EH_SjLj_Setup))
35363           .addMBB(restoreMBB);
35364 
35365   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
35366   MIB.addRegMask(RegInfo->getNoPreservedMask());
35367   thisMBB->addSuccessor(mainMBB);
35368   thisMBB->addSuccessor(restoreMBB);
35369 
35370   // mainMBB:
35371   //  EAX = 0
35372   BuildMI(mainMBB, MIMD, TII->get(X86::MOV32r0), mainDstReg);
35373   mainMBB->addSuccessor(sinkMBB);
35374 
35375   // sinkMBB:
35376   BuildMI(*sinkMBB, sinkMBB->begin(), MIMD, TII->get(X86::PHI), DstReg)
35377       .addReg(mainDstReg)
35378       .addMBB(mainMBB)
35379       .addReg(restoreDstReg)
35380       .addMBB(restoreMBB);
35381 
35382   // restoreMBB:
35383   if (RegInfo->hasBasePointer(*MF)) {
35384     const bool Uses64BitFramePtr =
35385         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
35386     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
35387     X86FI->setRestoreBasePointer(MF);
35388     Register FramePtr = RegInfo->getFrameRegister(*MF);
35389     Register BasePtr = RegInfo->getBaseRegister();
35390     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
35391     addRegOffset(BuildMI(restoreMBB, MIMD, TII->get(Opm), BasePtr),
35392                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
35393       .setMIFlag(MachineInstr::FrameSetup);
35394   }
35395   BuildMI(restoreMBB, MIMD, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
35396   BuildMI(restoreMBB, MIMD, TII->get(X86::JMP_1)).addMBB(sinkMBB);
35397   restoreMBB->addSuccessor(sinkMBB);
35398 
35399   MI.eraseFromParent();
35400   return sinkMBB;
35401 }
35402 
35403 /// Fix the shadow stack using the previously saved SSP pointer.
35404 /// \sa emitSetJmpShadowStackFix
35405 /// \param [in] MI The temporary Machine Instruction for the builtin.
35406 /// \param [in] MBB The Machine Basic Block that will be modified.
35407 /// \return The sink MBB that will perform the future indirect branch.
35408 MachineBasicBlock *
emitLongJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const35409 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
35410                                              MachineBasicBlock *MBB) const {
35411   const MIMetadata MIMD(MI);
35412   MachineFunction *MF = MBB->getParent();
35413   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35414   MachineRegisterInfo &MRI = MF->getRegInfo();
35415 
35416   // Memory Reference
35417   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35418                                            MI.memoperands_end());
35419 
35420   MVT PVT = getPointerTy(MF->getDataLayout());
35421   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
35422 
35423   // checkSspMBB:
35424   //         xor vreg1, vreg1
35425   //         rdssp vreg1
35426   //         test vreg1, vreg1
35427   //         je sinkMBB   # Jump if Shadow Stack is not supported
35428   // fallMBB:
35429   //         mov buf+24/12(%rip), vreg2
35430   //         sub vreg1, vreg2
35431   //         jbe sinkMBB  # No need to fix the Shadow Stack
35432   // fixShadowMBB:
35433   //         shr 3/2, vreg2
35434   //         incssp vreg2  # fix the SSP according to the lower 8 bits
35435   //         shr 8, vreg2
35436   //         je sinkMBB
35437   // fixShadowLoopPrepareMBB:
35438   //         shl vreg2
35439   //         mov 128, vreg3
35440   // fixShadowLoopMBB:
35441   //         incssp vreg3
35442   //         dec vreg2
35443   //         jne fixShadowLoopMBB # Iterate until you finish fixing
35444   //                              # the Shadow Stack
35445   // sinkMBB:
35446 
35447   MachineFunction::iterator I = ++MBB->getIterator();
35448   const BasicBlock *BB = MBB->getBasicBlock();
35449 
35450   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
35451   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
35452   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
35453   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
35454   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
35455   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
35456   MF->insert(I, checkSspMBB);
35457   MF->insert(I, fallMBB);
35458   MF->insert(I, fixShadowMBB);
35459   MF->insert(I, fixShadowLoopPrepareMBB);
35460   MF->insert(I, fixShadowLoopMBB);
35461   MF->insert(I, sinkMBB);
35462 
35463   // Transfer the remainder of BB and its successor edges to sinkMBB.
35464   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
35465                   MBB->end());
35466   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
35467 
35468   MBB->addSuccessor(checkSspMBB);
35469 
35470   // Initialize a register with zero.
35471   Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
35472   BuildMI(checkSspMBB, MIMD, TII->get(X86::MOV32r0), ZReg);
35473 
35474   if (PVT == MVT::i64) {
35475     Register TmpZReg = MRI.createVirtualRegister(PtrRC);
35476     BuildMI(checkSspMBB, MIMD, TII->get(X86::SUBREG_TO_REG), TmpZReg)
35477       .addImm(0)
35478       .addReg(ZReg)
35479       .addImm(X86::sub_32bit);
35480     ZReg = TmpZReg;
35481   }
35482 
35483   // Read the current SSP Register value to the zeroed register.
35484   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
35485   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
35486   BuildMI(checkSspMBB, MIMD, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
35487 
35488   // Check whether the result of the SSP register is zero and jump directly
35489   // to the sink.
35490   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
35491   BuildMI(checkSspMBB, MIMD, TII->get(TestRROpc))
35492       .addReg(SSPCopyReg)
35493       .addReg(SSPCopyReg);
35494   BuildMI(checkSspMBB, MIMD, TII->get(X86::JCC_1))
35495       .addMBB(sinkMBB)
35496       .addImm(X86::COND_E);
35497   checkSspMBB->addSuccessor(sinkMBB);
35498   checkSspMBB->addSuccessor(fallMBB);
35499 
35500   // Reload the previously saved SSP register value.
35501   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
35502   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
35503   const int64_t SPPOffset = 3 * PVT.getStoreSize();
35504   MachineInstrBuilder MIB =
35505       BuildMI(fallMBB, MIMD, TII->get(PtrLoadOpc), PrevSSPReg);
35506   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35507     const MachineOperand &MO = MI.getOperand(i);
35508     if (i == X86::AddrDisp)
35509       MIB.addDisp(MO, SPPOffset);
35510     else if (MO.isReg()) // Don't add the whole operand, we don't want to
35511                          // preserve kill flags.
35512       MIB.addReg(MO.getReg());
35513     else
35514       MIB.add(MO);
35515   }
35516   MIB.setMemRefs(MMOs);
35517 
35518   // Subtract the current SSP from the previous SSP.
35519   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
35520   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
35521   BuildMI(fallMBB, MIMD, TII->get(SubRROpc), SspSubReg)
35522       .addReg(PrevSSPReg)
35523       .addReg(SSPCopyReg);
35524 
35525   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
35526   BuildMI(fallMBB, MIMD, TII->get(X86::JCC_1))
35527       .addMBB(sinkMBB)
35528       .addImm(X86::COND_BE);
35529   fallMBB->addSuccessor(sinkMBB);
35530   fallMBB->addSuccessor(fixShadowMBB);
35531 
35532   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
35533   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
35534   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
35535   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
35536   BuildMI(fixShadowMBB, MIMD, TII->get(ShrRIOpc), SspFirstShrReg)
35537       .addReg(SspSubReg)
35538       .addImm(Offset);
35539 
35540   // Increase SSP when looking only on the lower 8 bits of the delta.
35541   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
35542   BuildMI(fixShadowMBB, MIMD, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
35543 
35544   // Reset the lower 8 bits.
35545   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
35546   BuildMI(fixShadowMBB, MIMD, TII->get(ShrRIOpc), SspSecondShrReg)
35547       .addReg(SspFirstShrReg)
35548       .addImm(8);
35549 
35550   // Jump if the result of the shift is zero.
35551   BuildMI(fixShadowMBB, MIMD, TII->get(X86::JCC_1))
35552       .addMBB(sinkMBB)
35553       .addImm(X86::COND_E);
35554   fixShadowMBB->addSuccessor(sinkMBB);
35555   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
35556 
35557   // Do a single shift left.
35558   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64ri : X86::SHL32ri;
35559   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
35560   BuildMI(fixShadowLoopPrepareMBB, MIMD, TII->get(ShlR1Opc), SspAfterShlReg)
35561       .addReg(SspSecondShrReg)
35562       .addImm(1);
35563 
35564   // Save the value 128 to a register (will be used next with incssp).
35565   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
35566   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
35567   BuildMI(fixShadowLoopPrepareMBB, MIMD, TII->get(MovRIOpc), Value128InReg)
35568       .addImm(128);
35569   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
35570 
35571   // Since incssp only looks at the lower 8 bits, we might need to do several
35572   // iterations of incssp until we finish fixing the shadow stack.
35573   Register DecReg = MRI.createVirtualRegister(PtrRC);
35574   Register CounterReg = MRI.createVirtualRegister(PtrRC);
35575   BuildMI(fixShadowLoopMBB, MIMD, TII->get(X86::PHI), CounterReg)
35576       .addReg(SspAfterShlReg)
35577       .addMBB(fixShadowLoopPrepareMBB)
35578       .addReg(DecReg)
35579       .addMBB(fixShadowLoopMBB);
35580 
35581   // Every iteration we increase the SSP by 128.
35582   BuildMI(fixShadowLoopMBB, MIMD, TII->get(IncsspOpc)).addReg(Value128InReg);
35583 
35584   // Every iteration we decrement the counter by 1.
35585   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
35586   BuildMI(fixShadowLoopMBB, MIMD, TII->get(DecROpc), DecReg).addReg(CounterReg);
35587 
35588   // Jump if the counter is not zero yet.
35589   BuildMI(fixShadowLoopMBB, MIMD, TII->get(X86::JCC_1))
35590       .addMBB(fixShadowLoopMBB)
35591       .addImm(X86::COND_NE);
35592   fixShadowLoopMBB->addSuccessor(sinkMBB);
35593   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
35594 
35595   return sinkMBB;
35596 }
35597 
35598 MachineBasicBlock *
emitEHSjLjLongJmp(MachineInstr & MI,MachineBasicBlock * MBB) const35599 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
35600                                      MachineBasicBlock *MBB) const {
35601   const MIMetadata MIMD(MI);
35602   MachineFunction *MF = MBB->getParent();
35603   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35604   MachineRegisterInfo &MRI = MF->getRegInfo();
35605 
35606   // Memory Reference
35607   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
35608                                            MI.memoperands_end());
35609 
35610   MVT PVT = getPointerTy(MF->getDataLayout());
35611   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
35612          "Invalid Pointer Size!");
35613 
35614   const TargetRegisterClass *RC =
35615     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
35616   Register Tmp = MRI.createVirtualRegister(RC);
35617   // Since FP is only updated here but NOT referenced, it's treated as GPR.
35618   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
35619   Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
35620   Register SP = RegInfo->getStackRegister();
35621 
35622   MachineInstrBuilder MIB;
35623 
35624   const int64_t LabelOffset = 1 * PVT.getStoreSize();
35625   const int64_t SPOffset = 2 * PVT.getStoreSize();
35626 
35627   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
35628   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
35629 
35630   MachineBasicBlock *thisMBB = MBB;
35631 
35632   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
35633   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
35634     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
35635   }
35636 
35637   // Reload FP
35638   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), FP);
35639   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35640     const MachineOperand &MO = MI.getOperand(i);
35641     if (MO.isReg()) // Don't add the whole operand, we don't want to
35642                     // preserve kill flags.
35643       MIB.addReg(MO.getReg());
35644     else
35645       MIB.add(MO);
35646   }
35647   MIB.setMemRefs(MMOs);
35648 
35649   // Reload IP
35650   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), Tmp);
35651   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35652     const MachineOperand &MO = MI.getOperand(i);
35653     if (i == X86::AddrDisp)
35654       MIB.addDisp(MO, LabelOffset);
35655     else if (MO.isReg()) // Don't add the whole operand, we don't want to
35656                          // preserve kill flags.
35657       MIB.addReg(MO.getReg());
35658     else
35659       MIB.add(MO);
35660   }
35661   MIB.setMemRefs(MMOs);
35662 
35663   // Reload SP
35664   MIB = BuildMI(*thisMBB, MI, MIMD, TII->get(PtrLoadOpc), SP);
35665   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
35666     if (i == X86::AddrDisp)
35667       MIB.addDisp(MI.getOperand(i), SPOffset);
35668     else
35669       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
35670                                  // the last instruction of the expansion.
35671   }
35672   MIB.setMemRefs(MMOs);
35673 
35674   // Jump
35675   BuildMI(*thisMBB, MI, MIMD, TII->get(IJmpOpc)).addReg(Tmp);
35676 
35677   MI.eraseFromParent();
35678   return thisMBB;
35679 }
35680 
SetupEntryBlockForSjLj(MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const35681 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
35682                                                MachineBasicBlock *MBB,
35683                                                MachineBasicBlock *DispatchBB,
35684                                                int FI) const {
35685   const MIMetadata MIMD(MI);
35686   MachineFunction *MF = MBB->getParent();
35687   MachineRegisterInfo *MRI = &MF->getRegInfo();
35688   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35689 
35690   MVT PVT = getPointerTy(MF->getDataLayout());
35691   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
35692 
35693   unsigned Op = 0;
35694   unsigned VR = 0;
35695 
35696   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
35697                      !isPositionIndependent();
35698 
35699   if (UseImmLabel) {
35700     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
35701   } else {
35702     const TargetRegisterClass *TRC =
35703         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
35704     VR = MRI->createVirtualRegister(TRC);
35705     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
35706 
35707     if (Subtarget.is64Bit())
35708       BuildMI(*MBB, MI, MIMD, TII->get(X86::LEA64r), VR)
35709           .addReg(X86::RIP)
35710           .addImm(1)
35711           .addReg(0)
35712           .addMBB(DispatchBB)
35713           .addReg(0);
35714     else
35715       BuildMI(*MBB, MI, MIMD, TII->get(X86::LEA32r), VR)
35716           .addReg(0) /* TII->getGlobalBaseReg(MF) */
35717           .addImm(1)
35718           .addReg(0)
35719           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
35720           .addReg(0);
35721   }
35722 
35723   MachineInstrBuilder MIB = BuildMI(*MBB, MI, MIMD, TII->get(Op));
35724   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
35725   if (UseImmLabel)
35726     MIB.addMBB(DispatchBB);
35727   else
35728     MIB.addReg(VR);
35729 }
35730 
35731 MachineBasicBlock *
EmitSjLjDispatchBlock(MachineInstr & MI,MachineBasicBlock * BB) const35732 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
35733                                          MachineBasicBlock *BB) const {
35734   const MIMetadata MIMD(MI);
35735   MachineFunction *MF = BB->getParent();
35736   MachineRegisterInfo *MRI = &MF->getRegInfo();
35737   const X86InstrInfo *TII = Subtarget.getInstrInfo();
35738   int FI = MF->getFrameInfo().getFunctionContextIndex();
35739 
35740   // Get a mapping of the call site numbers to all of the landing pads they're
35741   // associated with.
35742   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
35743   unsigned MaxCSNum = 0;
35744   for (auto &MBB : *MF) {
35745     if (!MBB.isEHPad())
35746       continue;
35747 
35748     MCSymbol *Sym = nullptr;
35749     for (const auto &MI : MBB) {
35750       if (MI.isDebugInstr())
35751         continue;
35752 
35753       assert(MI.isEHLabel() && "expected EH_LABEL");
35754       Sym = MI.getOperand(0).getMCSymbol();
35755       break;
35756     }
35757 
35758     if (!MF->hasCallSiteLandingPad(Sym))
35759       continue;
35760 
35761     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
35762       CallSiteNumToLPad[CSI].push_back(&MBB);
35763       MaxCSNum = std::max(MaxCSNum, CSI);
35764     }
35765   }
35766 
35767   // Get an ordered list of the machine basic blocks for the jump table.
35768   std::vector<MachineBasicBlock *> LPadList;
35769   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
35770   LPadList.reserve(CallSiteNumToLPad.size());
35771 
35772   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
35773     for (auto &LP : CallSiteNumToLPad[CSI]) {
35774       LPadList.push_back(LP);
35775       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
35776     }
35777   }
35778 
35779   assert(!LPadList.empty() &&
35780          "No landing pad destinations for the dispatch jump table!");
35781 
35782   // Create the MBBs for the dispatch code.
35783 
35784   // Shove the dispatch's address into the return slot in the function context.
35785   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
35786   DispatchBB->setIsEHPad(true);
35787 
35788   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
35789   BuildMI(TrapBB, MIMD, TII->get(X86::TRAP));
35790   DispatchBB->addSuccessor(TrapBB);
35791 
35792   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
35793   DispatchBB->addSuccessor(DispContBB);
35794 
35795   // Insert MBBs.
35796   MF->push_back(DispatchBB);
35797   MF->push_back(DispContBB);
35798   MF->push_back(TrapBB);
35799 
35800   // Insert code into the entry block that creates and registers the function
35801   // context.
35802   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
35803 
35804   // Create the jump table and associated information
35805   unsigned JTE = getJumpTableEncoding();
35806   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
35807   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
35808 
35809   const X86RegisterInfo &RI = TII->getRegisterInfo();
35810   // Add a register mask with no preserved registers.  This results in all
35811   // registers being marked as clobbered.
35812   if (RI.hasBasePointer(*MF)) {
35813     const bool FPIs64Bit =
35814         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
35815     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
35816     MFI->setRestoreBasePointer(MF);
35817 
35818     Register FP = RI.getFrameRegister(*MF);
35819     Register BP = RI.getBaseRegister();
35820     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
35821     addRegOffset(BuildMI(DispatchBB, MIMD, TII->get(Op), BP), FP, true,
35822                  MFI->getRestoreBasePointerOffset())
35823         .addRegMask(RI.getNoPreservedMask());
35824   } else {
35825     BuildMI(DispatchBB, MIMD, TII->get(X86::NOOP))
35826         .addRegMask(RI.getNoPreservedMask());
35827   }
35828 
35829   // IReg is used as an index in a memory operand and therefore can't be SP
35830   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
35831   addFrameReference(BuildMI(DispatchBB, MIMD, TII->get(X86::MOV32rm), IReg), FI,
35832                     Subtarget.is64Bit() ? 8 : 4);
35833   BuildMI(DispatchBB, MIMD, TII->get(X86::CMP32ri))
35834       .addReg(IReg)
35835       .addImm(LPadList.size());
35836   BuildMI(DispatchBB, MIMD, TII->get(X86::JCC_1))
35837       .addMBB(TrapBB)
35838       .addImm(X86::COND_AE);
35839 
35840   if (Subtarget.is64Bit()) {
35841     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
35842     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
35843 
35844     // leaq .LJTI0_0(%rip), BReg
35845     BuildMI(DispContBB, MIMD, TII->get(X86::LEA64r), BReg)
35846         .addReg(X86::RIP)
35847         .addImm(1)
35848         .addReg(0)
35849         .addJumpTableIndex(MJTI)
35850         .addReg(0);
35851     // movzx IReg64, IReg
35852     BuildMI(DispContBB, MIMD, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
35853         .addImm(0)
35854         .addReg(IReg)
35855         .addImm(X86::sub_32bit);
35856 
35857     switch (JTE) {
35858     case MachineJumpTableInfo::EK_BlockAddress:
35859       // jmpq *(BReg,IReg64,8)
35860       BuildMI(DispContBB, MIMD, TII->get(X86::JMP64m))
35861           .addReg(BReg)
35862           .addImm(8)
35863           .addReg(IReg64)
35864           .addImm(0)
35865           .addReg(0);
35866       break;
35867     case MachineJumpTableInfo::EK_LabelDifference32: {
35868       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
35869       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
35870       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
35871 
35872       // movl (BReg,IReg64,4), OReg
35873       BuildMI(DispContBB, MIMD, TII->get(X86::MOV32rm), OReg)
35874           .addReg(BReg)
35875           .addImm(4)
35876           .addReg(IReg64)
35877           .addImm(0)
35878           .addReg(0);
35879       // movsx OReg64, OReg
35880       BuildMI(DispContBB, MIMD, TII->get(X86::MOVSX64rr32), OReg64)
35881           .addReg(OReg);
35882       // addq BReg, OReg64, TReg
35883       BuildMI(DispContBB, MIMD, TII->get(X86::ADD64rr), TReg)
35884           .addReg(OReg64)
35885           .addReg(BReg);
35886       // jmpq *TReg
35887       BuildMI(DispContBB, MIMD, TII->get(X86::JMP64r)).addReg(TReg);
35888       break;
35889     }
35890     default:
35891       llvm_unreachable("Unexpected jump table encoding");
35892     }
35893   } else {
35894     // jmpl *.LJTI0_0(,IReg,4)
35895     BuildMI(DispContBB, MIMD, TII->get(X86::JMP32m))
35896         .addReg(0)
35897         .addImm(4)
35898         .addReg(IReg)
35899         .addJumpTableIndex(MJTI)
35900         .addReg(0);
35901   }
35902 
35903   // Add the jump table entries as successors to the MBB.
35904   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
35905   for (auto &LP : LPadList)
35906     if (SeenMBBs.insert(LP).second)
35907       DispContBB->addSuccessor(LP);
35908 
35909   // N.B. the order the invoke BBs are processed in doesn't matter here.
35910   SmallVector<MachineBasicBlock *, 64> MBBLPads;
35911   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
35912   for (MachineBasicBlock *MBB : InvokeBBs) {
35913     // Remove the landing pad successor from the invoke block and replace it
35914     // with the new dispatch block.
35915     // Keep a copy of Successors since it's modified inside the loop.
35916     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
35917                                                    MBB->succ_rend());
35918     // FIXME: Avoid quadratic complexity.
35919     for (auto *MBBS : Successors) {
35920       if (MBBS->isEHPad()) {
35921         MBB->removeSuccessor(MBBS);
35922         MBBLPads.push_back(MBBS);
35923       }
35924     }
35925 
35926     MBB->addSuccessor(DispatchBB);
35927 
35928     // Find the invoke call and mark all of the callee-saved registers as
35929     // 'implicit defined' so that they're spilled.  This prevents code from
35930     // moving instructions to before the EH block, where they will never be
35931     // executed.
35932     for (auto &II : reverse(*MBB)) {
35933       if (!II.isCall())
35934         continue;
35935 
35936       DenseMap<unsigned, bool> DefRegs;
35937       for (auto &MOp : II.operands())
35938         if (MOp.isReg())
35939           DefRegs[MOp.getReg()] = true;
35940 
35941       MachineInstrBuilder MIB(*MF, &II);
35942       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
35943         unsigned Reg = SavedRegs[RegIdx];
35944         if (!DefRegs[Reg])
35945           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
35946       }
35947 
35948       break;
35949     }
35950   }
35951 
35952   // Mark all former landing pads as non-landing pads.  The dispatch is the only
35953   // landing pad now.
35954   for (auto &LP : MBBLPads)
35955     LP->setIsEHPad(false);
35956 
35957   // The instruction is gone now.
35958   MI.eraseFromParent();
35959   return BB;
35960 }
35961 
35962 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const35963 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
35964                                                MachineBasicBlock *BB) const {
35965   MachineFunction *MF = BB->getParent();
35966   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
35967   const MIMetadata MIMD(MI);
35968 
35969   auto TMMImmToTMMReg = [](unsigned Imm) {
35970     assert (Imm < 8 && "Illegal tmm index");
35971     return X86::TMM0 + Imm;
35972   };
35973   switch (MI.getOpcode()) {
35974   default: llvm_unreachable("Unexpected instr type to insert");
35975   case X86::TLS_addr32:
35976   case X86::TLS_addr64:
35977   case X86::TLS_addrX32:
35978   case X86::TLS_base_addr32:
35979   case X86::TLS_base_addr64:
35980   case X86::TLS_base_addrX32:
35981     return EmitLoweredTLSAddr(MI, BB);
35982   case X86::INDIRECT_THUNK_CALL32:
35983   case X86::INDIRECT_THUNK_CALL64:
35984   case X86::INDIRECT_THUNK_TCRETURN32:
35985   case X86::INDIRECT_THUNK_TCRETURN64:
35986     return EmitLoweredIndirectThunk(MI, BB);
35987   case X86::CATCHRET:
35988     return EmitLoweredCatchRet(MI, BB);
35989   case X86::SEG_ALLOCA_32:
35990   case X86::SEG_ALLOCA_64:
35991     return EmitLoweredSegAlloca(MI, BB);
35992   case X86::PROBED_ALLOCA_32:
35993   case X86::PROBED_ALLOCA_64:
35994     return EmitLoweredProbedAlloca(MI, BB);
35995   case X86::TLSCall_32:
35996   case X86::TLSCall_64:
35997     return EmitLoweredTLSCall(MI, BB);
35998   case X86::CMOV_FR16:
35999   case X86::CMOV_FR16X:
36000   case X86::CMOV_FR32:
36001   case X86::CMOV_FR32X:
36002   case X86::CMOV_FR64:
36003   case X86::CMOV_FR64X:
36004   case X86::CMOV_GR8:
36005   case X86::CMOV_GR16:
36006   case X86::CMOV_GR32:
36007   case X86::CMOV_RFP32:
36008   case X86::CMOV_RFP64:
36009   case X86::CMOV_RFP80:
36010   case X86::CMOV_VR64:
36011   case X86::CMOV_VR128:
36012   case X86::CMOV_VR128X:
36013   case X86::CMOV_VR256:
36014   case X86::CMOV_VR256X:
36015   case X86::CMOV_VR512:
36016   case X86::CMOV_VK1:
36017   case X86::CMOV_VK2:
36018   case X86::CMOV_VK4:
36019   case X86::CMOV_VK8:
36020   case X86::CMOV_VK16:
36021   case X86::CMOV_VK32:
36022   case X86::CMOV_VK64:
36023     return EmitLoweredSelect(MI, BB);
36024 
36025   case X86::FP80_ADDr:
36026   case X86::FP80_ADDm32: {
36027     // Change the floating point control register to use double extended
36028     // precision when performing the addition.
36029     int OrigCWFrameIdx =
36030         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
36031     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FNSTCW16m)),
36032                       OrigCWFrameIdx);
36033 
36034     // Load the old value of the control word...
36035     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
36036     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOVZX32rm16), OldCW),
36037                       OrigCWFrameIdx);
36038 
36039     // OR 0b11 into bit 8 and 9. 0b11 is the encoding for double extended
36040     // precision.
36041     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
36042     BuildMI(*BB, MI, MIMD, TII->get(X86::OR32ri), NewCW)
36043         .addReg(OldCW, RegState::Kill)
36044         .addImm(0x300);
36045 
36046     // Extract to 16 bits.
36047     Register NewCW16 =
36048         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
36049     BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), NewCW16)
36050         .addReg(NewCW, RegState::Kill, X86::sub_16bit);
36051 
36052     // Prepare memory for FLDCW.
36053     int NewCWFrameIdx =
36054         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
36055     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOV16mr)),
36056                       NewCWFrameIdx)
36057         .addReg(NewCW16, RegState::Kill);
36058 
36059     // Reload the modified control word now...
36060     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
36061                       NewCWFrameIdx);
36062 
36063     // Do the addition.
36064     if (MI.getOpcode() == X86::FP80_ADDr) {
36065       BuildMI(*BB, MI, MIMD, TII->get(X86::ADD_Fp80))
36066           .add(MI.getOperand(0))
36067           .add(MI.getOperand(1))
36068           .add(MI.getOperand(2));
36069     } else {
36070       BuildMI(*BB, MI, MIMD, TII->get(X86::ADD_Fp80m32))
36071           .add(MI.getOperand(0))
36072           .add(MI.getOperand(1))
36073           .add(MI.getOperand(2))
36074           .add(MI.getOperand(3))
36075           .add(MI.getOperand(4))
36076           .add(MI.getOperand(5))
36077           .add(MI.getOperand(6));
36078     }
36079 
36080     // Reload the original control word now.
36081     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
36082                       OrigCWFrameIdx);
36083 
36084     MI.eraseFromParent(); // The pseudo instruction is gone now.
36085     return BB;
36086   }
36087 
36088   case X86::FP32_TO_INT16_IN_MEM:
36089   case X86::FP32_TO_INT32_IN_MEM:
36090   case X86::FP32_TO_INT64_IN_MEM:
36091   case X86::FP64_TO_INT16_IN_MEM:
36092   case X86::FP64_TO_INT32_IN_MEM:
36093   case X86::FP64_TO_INT64_IN_MEM:
36094   case X86::FP80_TO_INT16_IN_MEM:
36095   case X86::FP80_TO_INT32_IN_MEM:
36096   case X86::FP80_TO_INT64_IN_MEM: {
36097     // Change the floating point control register to use "round towards zero"
36098     // mode when truncating to an integer value.
36099     int OrigCWFrameIdx =
36100         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
36101     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FNSTCW16m)),
36102                       OrigCWFrameIdx);
36103 
36104     // Load the old value of the control word...
36105     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
36106     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOVZX32rm16), OldCW),
36107                       OrigCWFrameIdx);
36108 
36109     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
36110     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
36111     BuildMI(*BB, MI, MIMD, TII->get(X86::OR32ri), NewCW)
36112       .addReg(OldCW, RegState::Kill).addImm(0xC00);
36113 
36114     // Extract to 16 bits.
36115     Register NewCW16 =
36116         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
36117     BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), NewCW16)
36118       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
36119 
36120     // Prepare memory for FLDCW.
36121     int NewCWFrameIdx =
36122         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
36123     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::MOV16mr)),
36124                       NewCWFrameIdx)
36125       .addReg(NewCW16, RegState::Kill);
36126 
36127     // Reload the modified control word now...
36128     addFrameReference(BuildMI(*BB, MI, MIMD,
36129                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
36130 
36131     // Get the X86 opcode to use.
36132     unsigned Opc;
36133     switch (MI.getOpcode()) {
36134     default: llvm_unreachable("illegal opcode!");
36135     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
36136     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
36137     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
36138     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
36139     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
36140     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
36141     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
36142     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
36143     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
36144     }
36145 
36146     X86AddressMode AM = getAddressFromInstr(&MI, 0);
36147     addFullAddress(BuildMI(*BB, MI, MIMD, TII->get(Opc)), AM)
36148         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
36149 
36150     // Reload the original control word now.
36151     addFrameReference(BuildMI(*BB, MI, MIMD, TII->get(X86::FLDCW16m)),
36152                       OrigCWFrameIdx);
36153 
36154     MI.eraseFromParent(); // The pseudo instruction is gone now.
36155     return BB;
36156   }
36157 
36158   // xbegin
36159   case X86::XBEGIN:
36160     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
36161 
36162   case X86::VAARG_64:
36163   case X86::VAARG_X32:
36164     return EmitVAARGWithCustomInserter(MI, BB);
36165 
36166   case X86::EH_SjLj_SetJmp32:
36167   case X86::EH_SjLj_SetJmp64:
36168     return emitEHSjLjSetJmp(MI, BB);
36169 
36170   case X86::EH_SjLj_LongJmp32:
36171   case X86::EH_SjLj_LongJmp64:
36172     return emitEHSjLjLongJmp(MI, BB);
36173 
36174   case X86::Int_eh_sjlj_setup_dispatch:
36175     return EmitSjLjDispatchBlock(MI, BB);
36176 
36177   case TargetOpcode::STATEPOINT:
36178     // As an implementation detail, STATEPOINT shares the STACKMAP format at
36179     // this point in the process.  We diverge later.
36180     return emitPatchPoint(MI, BB);
36181 
36182   case TargetOpcode::STACKMAP:
36183   case TargetOpcode::PATCHPOINT:
36184     return emitPatchPoint(MI, BB);
36185 
36186   case TargetOpcode::PATCHABLE_EVENT_CALL:
36187   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
36188     return BB;
36189 
36190   case X86::LCMPXCHG8B: {
36191     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
36192     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
36193     // requires a memory operand. If it happens that current architecture is
36194     // i686 and for current function we need a base pointer
36195     // - which is ESI for i686 - register allocator would not be able to
36196     // allocate registers for an address in form of X(%reg, %reg, Y)
36197     // - there never would be enough unreserved registers during regalloc
36198     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
36199     // We are giving a hand to register allocator by precomputing the address in
36200     // a new vreg using LEA.
36201 
36202     // If it is not i686 or there is no base pointer - nothing to do here.
36203     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
36204       return BB;
36205 
36206     // Even though this code does not necessarily needs the base pointer to
36207     // be ESI, we check for that. The reason: if this assert fails, there are
36208     // some changes happened in the compiler base pointer handling, which most
36209     // probably have to be addressed somehow here.
36210     assert(TRI->getBaseRegister() == X86::ESI &&
36211            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
36212            "base pointer in mind");
36213 
36214     MachineRegisterInfo &MRI = MF->getRegInfo();
36215     MVT SPTy = getPointerTy(MF->getDataLayout());
36216     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
36217     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
36218 
36219     X86AddressMode AM = getAddressFromInstr(&MI, 0);
36220     // Regalloc does not need any help when the memory operand of CMPXCHG8B
36221     // does not use index register.
36222     if (AM.IndexReg == X86::NoRegister)
36223       return BB;
36224 
36225     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
36226     // four operand definitions that are E[ABCD] registers. We skip them and
36227     // then insert the LEA.
36228     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
36229     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
36230                                    RMBBI->definesRegister(X86::EBX) ||
36231                                    RMBBI->definesRegister(X86::ECX) ||
36232                                    RMBBI->definesRegister(X86::EDX))) {
36233       ++RMBBI;
36234     }
36235     MachineBasicBlock::iterator MBBI(RMBBI);
36236     addFullAddress(
36237         BuildMI(*BB, *MBBI, MIMD, TII->get(X86::LEA32r), computedAddrVReg), AM);
36238 
36239     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
36240 
36241     return BB;
36242   }
36243   case X86::LCMPXCHG16B_NO_RBX: {
36244     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
36245     Register BasePtr = TRI->getBaseRegister();
36246     if (TRI->hasBasePointer(*MF) &&
36247         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
36248       if (!BB->isLiveIn(BasePtr))
36249         BB->addLiveIn(BasePtr);
36250       // Save RBX into a virtual register.
36251       Register SaveRBX =
36252           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36253       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), SaveRBX)
36254           .addReg(X86::RBX);
36255       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36256       MachineInstrBuilder MIB =
36257           BuildMI(*BB, MI, MIMD, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
36258       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
36259         MIB.add(MI.getOperand(Idx));
36260       MIB.add(MI.getOperand(X86::AddrNumOperands));
36261       MIB.addReg(SaveRBX);
36262     } else {
36263       // Simple case, just copy the virtual register to RBX.
36264       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::RBX)
36265           .add(MI.getOperand(X86::AddrNumOperands));
36266       MachineInstrBuilder MIB =
36267           BuildMI(*BB, MI, MIMD, TII->get(X86::LCMPXCHG16B));
36268       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
36269         MIB.add(MI.getOperand(Idx));
36270     }
36271     MI.eraseFromParent();
36272     return BB;
36273   }
36274   case X86::MWAITX: {
36275     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
36276     Register BasePtr = TRI->getBaseRegister();
36277     bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
36278     // If no need to save the base pointer, we generate MWAITXrrr,
36279     // else we generate pseudo MWAITX_SAVE_RBX.
36280     if (!IsRBX || !TRI->hasBasePointer(*MF)) {
36281       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::ECX)
36282           .addReg(MI.getOperand(0).getReg());
36283       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EAX)
36284           .addReg(MI.getOperand(1).getReg());
36285       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EBX)
36286           .addReg(MI.getOperand(2).getReg());
36287       BuildMI(*BB, MI, MIMD, TII->get(X86::MWAITXrrr));
36288       MI.eraseFromParent();
36289     } else {
36290       if (!BB->isLiveIn(BasePtr)) {
36291         BB->addLiveIn(BasePtr);
36292       }
36293       // Parameters can be copied into ECX and EAX but not EBX yet.
36294       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::ECX)
36295           .addReg(MI.getOperand(0).getReg());
36296       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), X86::EAX)
36297           .addReg(MI.getOperand(1).getReg());
36298       assert(Subtarget.is64Bit() && "Expected 64-bit mode!");
36299       // Save RBX into a virtual register.
36300       Register SaveRBX =
36301           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36302       BuildMI(*BB, MI, MIMD, TII->get(TargetOpcode::COPY), SaveRBX)
36303           .addReg(X86::RBX);
36304       // Generate mwaitx pseudo.
36305       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
36306       BuildMI(*BB, MI, MIMD, TII->get(X86::MWAITX_SAVE_RBX))
36307           .addDef(Dst) // Destination tied in with SaveRBX.
36308           .addReg(MI.getOperand(2).getReg()) // input value of EBX.
36309           .addUse(SaveRBX);                  // Save of base pointer.
36310       MI.eraseFromParent();
36311     }
36312     return BB;
36313   }
36314   case TargetOpcode::PREALLOCATED_SETUP: {
36315     assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
36316     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
36317     MFI->setHasPreallocatedCall(true);
36318     int64_t PreallocatedId = MI.getOperand(0).getImm();
36319     size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
36320     assert(StackAdjustment != 0 && "0 stack adjustment");
36321     LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
36322                       << StackAdjustment << "\n");
36323     BuildMI(*BB, MI, MIMD, TII->get(X86::SUB32ri), X86::ESP)
36324         .addReg(X86::ESP)
36325         .addImm(StackAdjustment);
36326     MI.eraseFromParent();
36327     return BB;
36328   }
36329   case TargetOpcode::PREALLOCATED_ARG: {
36330     assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
36331     int64_t PreallocatedId = MI.getOperand(1).getImm();
36332     int64_t ArgIdx = MI.getOperand(2).getImm();
36333     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
36334     size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
36335     LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
36336                       << ", arg offset " << ArgOffset << "\n");
36337     // stack pointer + offset
36338     addRegOffset(BuildMI(*BB, MI, MIMD, TII->get(X86::LEA32r),
36339                          MI.getOperand(0).getReg()),
36340                  X86::ESP, false, ArgOffset);
36341     MI.eraseFromParent();
36342     return BB;
36343   }
36344   case X86::PTDPBSSD:
36345   case X86::PTDPBSUD:
36346   case X86::PTDPBUSD:
36347   case X86::PTDPBUUD:
36348   case X86::PTDPBF16PS:
36349   case X86::PTDPFP16PS: {
36350     unsigned Opc;
36351     switch (MI.getOpcode()) {
36352     default: llvm_unreachable("illegal opcode!");
36353     case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
36354     case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
36355     case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
36356     case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
36357     case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
36358     case X86::PTDPFP16PS: Opc = X86::TDPFP16PS; break;
36359     }
36360 
36361     MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
36362     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
36363     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
36364     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
36365     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
36366 
36367     MI.eraseFromParent(); // The pseudo is gone now.
36368     return BB;
36369   }
36370   case X86::PTILEZERO: {
36371     unsigned Imm = MI.getOperand(0).getImm();
36372     BuildMI(*BB, MI, MIMD, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
36373     MI.eraseFromParent(); // The pseudo is gone now.
36374     return BB;
36375   }
36376   case X86::PTILELOADD:
36377   case X86::PTILELOADDT1:
36378   case X86::PTILESTORED: {
36379     unsigned Opc;
36380     switch (MI.getOpcode()) {
36381     default: llvm_unreachable("illegal opcode!");
36382 #define GET_EGPR_IF_ENABLED(OPC) (Subtarget.hasEGPR() ? OPC##_EVEX : OPC)
36383     case X86::PTILELOADD:
36384       Opc = GET_EGPR_IF_ENABLED(X86::TILELOADD);
36385       break;
36386     case X86::PTILELOADDT1:
36387       Opc = GET_EGPR_IF_ENABLED(X86::TILELOADDT1);
36388       break;
36389     case X86::PTILESTORED:
36390       Opc = GET_EGPR_IF_ENABLED(X86::TILESTORED);
36391       break;
36392 #undef GET_EGPR_IF_ENABLED
36393     }
36394 
36395     MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
36396     unsigned CurOp = 0;
36397     if (Opc != X86::TILESTORED && Opc != X86::TILESTORED_EVEX)
36398       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
36399                  RegState::Define);
36400 
36401     MIB.add(MI.getOperand(CurOp++)); // base
36402     MIB.add(MI.getOperand(CurOp++)); // scale
36403     MIB.add(MI.getOperand(CurOp++)); // index -- stride
36404     MIB.add(MI.getOperand(CurOp++)); // displacement
36405     MIB.add(MI.getOperand(CurOp++)); // segment
36406 
36407     if (Opc == X86::TILESTORED || Opc == X86::TILESTORED_EVEX)
36408       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
36409                  RegState::Undef);
36410 
36411     MI.eraseFromParent(); // The pseudo is gone now.
36412     return BB;
36413   }
36414   case X86::PTCMMIMFP16PS:
36415   case X86::PTCMMRLFP16PS: {
36416     const MIMetadata MIMD(MI);
36417     unsigned Opc;
36418     switch (MI.getOpcode()) {
36419     default: llvm_unreachable("Unexpected instruction!");
36420     case X86::PTCMMIMFP16PS:     Opc = X86::TCMMIMFP16PS;     break;
36421     case X86::PTCMMRLFP16PS:     Opc = X86::TCMMRLFP16PS;     break;
36422     }
36423     MachineInstrBuilder MIB = BuildMI(*BB, MI, MIMD, TII->get(Opc));
36424     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
36425     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
36426     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
36427     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
36428     MI.eraseFromParent(); // The pseudo is gone now.
36429     return BB;
36430   }
36431   }
36432 }
36433 
36434 //===----------------------------------------------------------------------===//
36435 //                           X86 Optimization Hooks
36436 //===----------------------------------------------------------------------===//
36437 
36438 bool
targetShrinkDemandedConstant(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,TargetLoweringOpt & TLO) const36439 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
36440                                                 const APInt &DemandedBits,
36441                                                 const APInt &DemandedElts,
36442                                                 TargetLoweringOpt &TLO) const {
36443   EVT VT = Op.getValueType();
36444   unsigned Opcode = Op.getOpcode();
36445   unsigned EltSize = VT.getScalarSizeInBits();
36446 
36447   if (VT.isVector()) {
36448     // If the constant is only all signbits in the active bits, then we should
36449     // extend it to the entire constant to allow it act as a boolean constant
36450     // vector.
36451     auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
36452       if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
36453         return false;
36454       for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
36455         if (!DemandedElts[i] || V.getOperand(i).isUndef())
36456           continue;
36457         const APInt &Val = V.getConstantOperandAPInt(i);
36458         if (Val.getBitWidth() > Val.getNumSignBits() &&
36459             Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
36460           return true;
36461       }
36462       return false;
36463     };
36464     // For vectors - if we have a constant, then try to sign extend.
36465     // TODO: Handle AND cases.
36466     unsigned ActiveBits = DemandedBits.getActiveBits();
36467     if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
36468         (Opcode == ISD::OR || Opcode == ISD::XOR || Opcode == X86ISD::ANDNP) &&
36469         NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
36470       EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
36471       EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
36472                                    VT.getVectorNumElements());
36473       SDValue NewC =
36474           TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
36475                           Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
36476       SDValue NewOp =
36477           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
36478       return TLO.CombineTo(Op, NewOp);
36479     }
36480     return false;
36481   }
36482 
36483   // Only optimize Ands to prevent shrinking a constant that could be
36484   // matched by movzx.
36485   if (Opcode != ISD::AND)
36486     return false;
36487 
36488   // Make sure the RHS really is a constant.
36489   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
36490   if (!C)
36491     return false;
36492 
36493   const APInt &Mask = C->getAPIntValue();
36494 
36495   // Clear all non-demanded bits initially.
36496   APInt ShrunkMask = Mask & DemandedBits;
36497 
36498   // Find the width of the shrunk mask.
36499   unsigned Width = ShrunkMask.getActiveBits();
36500 
36501   // If the mask is all 0s there's nothing to do here.
36502   if (Width == 0)
36503     return false;
36504 
36505   // Find the next power of 2 width, rounding up to a byte.
36506   Width = llvm::bit_ceil(std::max(Width, 8U));
36507   // Truncate the width to size to handle illegal types.
36508   Width = std::min(Width, EltSize);
36509 
36510   // Calculate a possible zero extend mask for this constant.
36511   APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
36512 
36513   // If we aren't changing the mask, just return true to keep it and prevent
36514   // the caller from optimizing.
36515   if (ZeroExtendMask == Mask)
36516     return true;
36517 
36518   // Make sure the new mask can be represented by a combination of mask bits
36519   // and non-demanded bits.
36520   if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
36521     return false;
36522 
36523   // Replace the constant with the zero extend mask.
36524   SDLoc DL(Op);
36525   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
36526   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
36527   return TLO.CombineTo(Op, NewOp);
36528 }
36529 
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const36530 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
36531                                                       KnownBits &Known,
36532                                                       const APInt &DemandedElts,
36533                                                       const SelectionDAG &DAG,
36534                                                       unsigned Depth) const {
36535   unsigned BitWidth = Known.getBitWidth();
36536   unsigned NumElts = DemandedElts.getBitWidth();
36537   unsigned Opc = Op.getOpcode();
36538   EVT VT = Op.getValueType();
36539   assert((Opc >= ISD::BUILTIN_OP_END ||
36540           Opc == ISD::INTRINSIC_WO_CHAIN ||
36541           Opc == ISD::INTRINSIC_W_CHAIN ||
36542           Opc == ISD::INTRINSIC_VOID) &&
36543          "Should use MaskedValueIsZero if you don't know whether Op"
36544          " is a target node!");
36545 
36546   Known.resetAll();
36547   switch (Opc) {
36548   default: break;
36549   case X86ISD::MUL_IMM: {
36550     KnownBits Known2;
36551     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36552     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36553     Known = KnownBits::mul(Known, Known2);
36554     break;
36555   }
36556   case X86ISD::SETCC:
36557     Known.Zero.setBitsFrom(1);
36558     break;
36559   case X86ISD::MOVMSK: {
36560     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
36561     Known.Zero.setBitsFrom(NumLoBits);
36562     break;
36563   }
36564   case X86ISD::PEXTRB:
36565   case X86ISD::PEXTRW: {
36566     SDValue Src = Op.getOperand(0);
36567     EVT SrcVT = Src.getValueType();
36568     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
36569                                             Op.getConstantOperandVal(1));
36570     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
36571     Known = Known.anyextOrTrunc(BitWidth);
36572     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
36573     break;
36574   }
36575   case X86ISD::VSRAI:
36576   case X86ISD::VSHLI:
36577   case X86ISD::VSRLI: {
36578     unsigned ShAmt = Op.getConstantOperandVal(1);
36579     if (ShAmt >= VT.getScalarSizeInBits()) {
36580       // Out of range logical bit shifts are guaranteed to be zero.
36581       // Out of range arithmetic bit shifts splat the sign bit.
36582       if (Opc != X86ISD::VSRAI) {
36583         Known.setAllZero();
36584         break;
36585       }
36586 
36587       ShAmt = VT.getScalarSizeInBits() - 1;
36588     }
36589 
36590     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36591     if (Opc == X86ISD::VSHLI) {
36592       Known.Zero <<= ShAmt;
36593       Known.One <<= ShAmt;
36594       // Low bits are known zero.
36595       Known.Zero.setLowBits(ShAmt);
36596     } else if (Opc == X86ISD::VSRLI) {
36597       Known.Zero.lshrInPlace(ShAmt);
36598       Known.One.lshrInPlace(ShAmt);
36599       // High bits are known zero.
36600       Known.Zero.setHighBits(ShAmt);
36601     } else {
36602       Known.Zero.ashrInPlace(ShAmt);
36603       Known.One.ashrInPlace(ShAmt);
36604     }
36605     break;
36606   }
36607   case X86ISD::PACKUS: {
36608     // PACKUS is just a truncation if the upper half is zero.
36609     APInt DemandedLHS, DemandedRHS;
36610     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
36611 
36612     Known.One = APInt::getAllOnes(BitWidth * 2);
36613     Known.Zero = APInt::getAllOnes(BitWidth * 2);
36614 
36615     KnownBits Known2;
36616     if (!!DemandedLHS) {
36617       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
36618       Known = Known.intersectWith(Known2);
36619     }
36620     if (!!DemandedRHS) {
36621       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
36622       Known = Known.intersectWith(Known2);
36623     }
36624 
36625     if (Known.countMinLeadingZeros() < BitWidth)
36626       Known.resetAll();
36627     Known = Known.trunc(BitWidth);
36628     break;
36629   }
36630   case X86ISD::VBROADCAST: {
36631     SDValue Src = Op.getOperand(0);
36632     if (!Src.getSimpleValueType().isVector()) {
36633       Known = DAG.computeKnownBits(Src, Depth + 1);
36634       return;
36635     }
36636     break;
36637   }
36638   case X86ISD::AND: {
36639     if (Op.getResNo() == 0) {
36640       KnownBits Known2;
36641       Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36642       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36643       Known &= Known2;
36644     }
36645     break;
36646   }
36647   case X86ISD::ANDNP: {
36648     KnownBits Known2;
36649     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36650     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36651 
36652     // ANDNP = (~X & Y);
36653     Known.One &= Known2.Zero;
36654     Known.Zero |= Known2.One;
36655     break;
36656   }
36657   case X86ISD::FOR: {
36658     KnownBits Known2;
36659     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36660     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36661 
36662     Known |= Known2;
36663     break;
36664   }
36665   case X86ISD::PSADBW: {
36666     assert(VT.getScalarType() == MVT::i64 &&
36667            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
36668            "Unexpected PSADBW types");
36669 
36670     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
36671     Known.Zero.setBitsFrom(16);
36672     break;
36673   }
36674   case X86ISD::PCMPGT:
36675   case X86ISD::PCMPEQ: {
36676     KnownBits KnownLhs =
36677         DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36678     KnownBits KnownRhs =
36679         DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36680     std::optional<bool> Res = Opc == X86ISD::PCMPEQ
36681                                   ? KnownBits::eq(KnownLhs, KnownRhs)
36682                                   : KnownBits::sgt(KnownLhs, KnownRhs);
36683     if (Res) {
36684       if (*Res)
36685         Known.setAllOnes();
36686       else
36687         Known.setAllZero();
36688     }
36689     break;
36690   }
36691   case X86ISD::PMULUDQ: {
36692     KnownBits Known2;
36693     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36694     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36695 
36696     Known = Known.trunc(BitWidth / 2).zext(BitWidth);
36697     Known2 = Known2.trunc(BitWidth / 2).zext(BitWidth);
36698     Known = KnownBits::mul(Known, Known2);
36699     break;
36700   }
36701   case X86ISD::CMOV: {
36702     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
36703     // If we don't know any bits, early out.
36704     if (Known.isUnknown())
36705       break;
36706     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
36707 
36708     // Only known if known in both the LHS and RHS.
36709     Known = Known.intersectWith(Known2);
36710     break;
36711   }
36712   case X86ISD::BEXTR:
36713   case X86ISD::BEXTRI: {
36714     SDValue Op0 = Op.getOperand(0);
36715     SDValue Op1 = Op.getOperand(1);
36716 
36717     if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
36718       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
36719       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
36720 
36721       // If the length is 0, the result is 0.
36722       if (Length == 0) {
36723         Known.setAllZero();
36724         break;
36725       }
36726 
36727       if ((Shift + Length) <= BitWidth) {
36728         Known = DAG.computeKnownBits(Op0, Depth + 1);
36729         Known = Known.extractBits(Length, Shift);
36730         Known = Known.zextOrTrunc(BitWidth);
36731       }
36732     }
36733     break;
36734   }
36735   case X86ISD::PDEP: {
36736     KnownBits Known2;
36737     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36738     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
36739     // Zeros are retained from the mask operand. But not ones.
36740     Known.One.clearAllBits();
36741     // The result will have at least as many trailing zeros as the non-mask
36742     // operand since bits can only map to the same or higher bit position.
36743     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
36744     break;
36745   }
36746   case X86ISD::PEXT: {
36747     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
36748     // The result has as many leading zeros as the number of zeroes in the mask.
36749     unsigned Count = Known.Zero.popcount();
36750     Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
36751     Known.One.clearAllBits();
36752     break;
36753   }
36754   case X86ISD::VTRUNC:
36755   case X86ISD::VTRUNCS:
36756   case X86ISD::VTRUNCUS:
36757   case X86ISD::CVTSI2P:
36758   case X86ISD::CVTUI2P:
36759   case X86ISD::CVTP2SI:
36760   case X86ISD::CVTP2UI:
36761   case X86ISD::MCVTP2SI:
36762   case X86ISD::MCVTP2UI:
36763   case X86ISD::CVTTP2SI:
36764   case X86ISD::CVTTP2UI:
36765   case X86ISD::MCVTTP2SI:
36766   case X86ISD::MCVTTP2UI:
36767   case X86ISD::MCVTSI2P:
36768   case X86ISD::MCVTUI2P:
36769   case X86ISD::VFPROUND:
36770   case X86ISD::VMFPROUND:
36771   case X86ISD::CVTPS2PH:
36772   case X86ISD::MCVTPS2PH: {
36773     // Truncations/Conversions - upper elements are known zero.
36774     EVT SrcVT = Op.getOperand(0).getValueType();
36775     if (SrcVT.isVector()) {
36776       unsigned NumSrcElts = SrcVT.getVectorNumElements();
36777       if (NumElts > NumSrcElts && DemandedElts.countr_zero() >= NumSrcElts)
36778         Known.setAllZero();
36779     }
36780     break;
36781   }
36782   case X86ISD::STRICT_CVTTP2SI:
36783   case X86ISD::STRICT_CVTTP2UI:
36784   case X86ISD::STRICT_CVTSI2P:
36785   case X86ISD::STRICT_CVTUI2P:
36786   case X86ISD::STRICT_VFPROUND:
36787   case X86ISD::STRICT_CVTPS2PH: {
36788     // Strict Conversions - upper elements are known zero.
36789     EVT SrcVT = Op.getOperand(1).getValueType();
36790     if (SrcVT.isVector()) {
36791       unsigned NumSrcElts = SrcVT.getVectorNumElements();
36792       if (NumElts > NumSrcElts && DemandedElts.countr_zero() >= NumSrcElts)
36793         Known.setAllZero();
36794     }
36795     break;
36796   }
36797   case X86ISD::MOVQ2DQ: {
36798     // Move from MMX to XMM. Upper half of XMM should be 0.
36799     if (DemandedElts.countr_zero() >= (NumElts / 2))
36800       Known.setAllZero();
36801     break;
36802   }
36803   case X86ISD::VBROADCAST_LOAD: {
36804     APInt UndefElts;
36805     SmallVector<APInt, 16> EltBits;
36806     if (getTargetConstantBitsFromNode(Op, BitWidth, UndefElts, EltBits,
36807                                       /*AllowWholeUndefs*/ false,
36808                                       /*AllowPartialUndefs*/ false)) {
36809       Known.Zero.setAllBits();
36810       Known.One.setAllBits();
36811       for (unsigned I = 0; I != NumElts; ++I) {
36812         if (!DemandedElts[I])
36813           continue;
36814         if (UndefElts[I]) {
36815           Known.resetAll();
36816           break;
36817         }
36818         KnownBits Known2 = KnownBits::makeConstant(EltBits[I]);
36819         Known = Known.intersectWith(Known2);
36820       }
36821       return;
36822     }
36823     break;
36824   }
36825   }
36826 
36827   // Handle target shuffles.
36828   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
36829   if (isTargetShuffle(Opc)) {
36830     SmallVector<int, 64> Mask;
36831     SmallVector<SDValue, 2> Ops;
36832     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
36833       unsigned NumOps = Ops.size();
36834       unsigned NumElts = VT.getVectorNumElements();
36835       if (Mask.size() == NumElts) {
36836         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
36837         Known.Zero.setAllBits(); Known.One.setAllBits();
36838         for (unsigned i = 0; i != NumElts; ++i) {
36839           if (!DemandedElts[i])
36840             continue;
36841           int M = Mask[i];
36842           if (M == SM_SentinelUndef) {
36843             // For UNDEF elements, we don't know anything about the common state
36844             // of the shuffle result.
36845             Known.resetAll();
36846             break;
36847           }
36848           if (M == SM_SentinelZero) {
36849             Known.One.clearAllBits();
36850             continue;
36851           }
36852           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
36853                  "Shuffle index out of range");
36854 
36855           unsigned OpIdx = (unsigned)M / NumElts;
36856           unsigned EltIdx = (unsigned)M % NumElts;
36857           if (Ops[OpIdx].getValueType() != VT) {
36858             // TODO - handle target shuffle ops with different value types.
36859             Known.resetAll();
36860             break;
36861           }
36862           DemandedOps[OpIdx].setBit(EltIdx);
36863         }
36864         // Known bits are the values that are shared by every demanded element.
36865         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
36866           if (!DemandedOps[i])
36867             continue;
36868           KnownBits Known2 =
36869               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
36870           Known = Known.intersectWith(Known2);
36871         }
36872       }
36873     }
36874   }
36875 }
36876 
ComputeNumSignBitsForTargetNode(SDValue Op,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const36877 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
36878     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
36879     unsigned Depth) const {
36880   EVT VT = Op.getValueType();
36881   unsigned VTBits = VT.getScalarSizeInBits();
36882   unsigned Opcode = Op.getOpcode();
36883   switch (Opcode) {
36884   case X86ISD::SETCC_CARRY:
36885     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
36886     return VTBits;
36887 
36888   case X86ISD::VTRUNC: {
36889     SDValue Src = Op.getOperand(0);
36890     MVT SrcVT = Src.getSimpleValueType();
36891     unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
36892     assert(VTBits < NumSrcBits && "Illegal truncation input type");
36893     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
36894     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
36895     if (Tmp > (NumSrcBits - VTBits))
36896       return Tmp - (NumSrcBits - VTBits);
36897     return 1;
36898   }
36899 
36900   case X86ISD::PACKSS: {
36901     // PACKSS is just a truncation if the sign bits extend to the packed size.
36902     APInt DemandedLHS, DemandedRHS;
36903     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
36904                         DemandedRHS);
36905 
36906     // Helper to detect PACKSSDW(BITCAST(PACKSSDW(X)),BITCAST(PACKSSDW(Y)))
36907     // patterns often used to compact vXi64 allsignbit patterns.
36908     auto NumSignBitsPACKSS = [&](SDValue V, const APInt &Elts) -> unsigned {
36909       SDValue BC = peekThroughBitcasts(V);
36910       if (BC.getOpcode() == X86ISD::PACKSS &&
36911           BC.getScalarValueSizeInBits() == 16 &&
36912           V.getScalarValueSizeInBits() == 32) {
36913         SDValue BC0 = peekThroughBitcasts(BC.getOperand(0));
36914         SDValue BC1 = peekThroughBitcasts(BC.getOperand(1));
36915         if (BC0.getScalarValueSizeInBits() == 64 &&
36916             BC1.getScalarValueSizeInBits() == 64 &&
36917             DAG.ComputeNumSignBits(BC0, Depth + 1) == 64 &&
36918             DAG.ComputeNumSignBits(BC1, Depth + 1) == 64)
36919           return 32;
36920       }
36921       return DAG.ComputeNumSignBits(V, Elts, Depth + 1);
36922     };
36923 
36924     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
36925     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
36926     if (!!DemandedLHS)
36927       Tmp0 = NumSignBitsPACKSS(Op.getOperand(0), DemandedLHS);
36928     if (!!DemandedRHS)
36929       Tmp1 = NumSignBitsPACKSS(Op.getOperand(1), DemandedRHS);
36930     unsigned Tmp = std::min(Tmp0, Tmp1);
36931     if (Tmp > (SrcBits - VTBits))
36932       return Tmp - (SrcBits - VTBits);
36933     return 1;
36934   }
36935 
36936   case X86ISD::VBROADCAST: {
36937     SDValue Src = Op.getOperand(0);
36938     if (!Src.getSimpleValueType().isVector())
36939       return DAG.ComputeNumSignBits(Src, Depth + 1);
36940     break;
36941   }
36942 
36943   case X86ISD::VSHLI: {
36944     SDValue Src = Op.getOperand(0);
36945     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
36946     if (ShiftVal.uge(VTBits))
36947       return VTBits; // Shifted all bits out --> zero.
36948     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
36949     if (ShiftVal.uge(Tmp))
36950       return 1; // Shifted all sign bits out --> unknown.
36951     return Tmp - ShiftVal.getZExtValue();
36952   }
36953 
36954   case X86ISD::VSRAI: {
36955     SDValue Src = Op.getOperand(0);
36956     APInt ShiftVal = Op.getConstantOperandAPInt(1);
36957     if (ShiftVal.uge(VTBits - 1))
36958       return VTBits; // Sign splat.
36959     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
36960     ShiftVal += Tmp;
36961     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
36962   }
36963 
36964   case X86ISD::FSETCC:
36965     // cmpss/cmpsd return zero/all-bits result values in the bottom element.
36966     if (VT == MVT::f32 || VT == MVT::f64 ||
36967         ((VT == MVT::v4f32 || VT == MVT::v2f64) && DemandedElts == 1))
36968       return VTBits;
36969     break;
36970 
36971   case X86ISD::PCMPGT:
36972   case X86ISD::PCMPEQ:
36973   case X86ISD::CMPP:
36974   case X86ISD::VPCOM:
36975   case X86ISD::VPCOMU:
36976     // Vector compares return zero/all-bits result values.
36977     return VTBits;
36978 
36979   case X86ISD::ANDNP: {
36980     unsigned Tmp0 =
36981         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
36982     if (Tmp0 == 1) return 1; // Early out.
36983     unsigned Tmp1 =
36984         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
36985     return std::min(Tmp0, Tmp1);
36986   }
36987 
36988   case X86ISD::CMOV: {
36989     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
36990     if (Tmp0 == 1) return 1;  // Early out.
36991     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
36992     return std::min(Tmp0, Tmp1);
36993   }
36994   }
36995 
36996   // Handle target shuffles.
36997   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
36998   if (isTargetShuffle(Opcode)) {
36999     SmallVector<int, 64> Mask;
37000     SmallVector<SDValue, 2> Ops;
37001     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask)) {
37002       unsigned NumOps = Ops.size();
37003       unsigned NumElts = VT.getVectorNumElements();
37004       if (Mask.size() == NumElts) {
37005         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
37006         for (unsigned i = 0; i != NumElts; ++i) {
37007           if (!DemandedElts[i])
37008             continue;
37009           int M = Mask[i];
37010           if (M == SM_SentinelUndef) {
37011             // For UNDEF elements, we don't know anything about the common state
37012             // of the shuffle result.
37013             return 1;
37014           } else if (M == SM_SentinelZero) {
37015             // Zero = all sign bits.
37016             continue;
37017           }
37018           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
37019                  "Shuffle index out of range");
37020 
37021           unsigned OpIdx = (unsigned)M / NumElts;
37022           unsigned EltIdx = (unsigned)M % NumElts;
37023           if (Ops[OpIdx].getValueType() != VT) {
37024             // TODO - handle target shuffle ops with different value types.
37025             return 1;
37026           }
37027           DemandedOps[OpIdx].setBit(EltIdx);
37028         }
37029         unsigned Tmp0 = VTBits;
37030         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
37031           if (!DemandedOps[i])
37032             continue;
37033           unsigned Tmp1 =
37034               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
37035           Tmp0 = std::min(Tmp0, Tmp1);
37036         }
37037         return Tmp0;
37038       }
37039     }
37040   }
37041 
37042   // Fallback case.
37043   return 1;
37044 }
37045 
unwrapAddress(SDValue N) const37046 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
37047   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
37048     return N->getOperand(0);
37049   return N;
37050 }
37051 
37052 // Helper to look for a normal load that can be narrowed into a vzload with the
37053 // specified VT and memory VT. Returns SDValue() on failure.
narrowLoadToVZLoad(LoadSDNode * LN,MVT MemVT,MVT VT,SelectionDAG & DAG)37054 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
37055                                   SelectionDAG &DAG) {
37056   // Can't if the load is volatile or atomic.
37057   if (!LN->isSimple())
37058     return SDValue();
37059 
37060   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37061   SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
37062   return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
37063                                  LN->getPointerInfo(), LN->getOriginalAlign(),
37064                                  LN->getMemOperand()->getFlags());
37065 }
37066 
37067 // Attempt to match a combined shuffle mask against supported unary shuffle
37068 // instructions.
37069 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue V1,const SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT)37070 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
37071                               bool AllowFloatDomain, bool AllowIntDomain,
37072                               SDValue V1, const SelectionDAG &DAG,
37073                               const X86Subtarget &Subtarget, unsigned &Shuffle,
37074                               MVT &SrcVT, MVT &DstVT) {
37075   unsigned NumMaskElts = Mask.size();
37076   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
37077 
37078   // Match against a VZEXT_MOVL vXi32 and vXi16 zero-extending instruction.
37079   if (Mask[0] == 0 &&
37080       (MaskEltSize == 32 || (MaskEltSize == 16 && Subtarget.hasFP16()))) {
37081     if ((isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) ||
37082         (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37083          isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1))) {
37084       Shuffle = X86ISD::VZEXT_MOVL;
37085       if (MaskEltSize == 16)
37086         SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
37087       else
37088         SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
37089       return true;
37090     }
37091   }
37092 
37093   // Match against a ANY/SIGN/ZERO_EXTEND_VECTOR_INREG instruction.
37094   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
37095   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
37096                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
37097     unsigned MaxScale = 64 / MaskEltSize;
37098     bool UseSign = V1.getScalarValueSizeInBits() == MaskEltSize &&
37099                    DAG.ComputeNumSignBits(V1) == MaskEltSize;
37100     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
37101       bool MatchAny = true;
37102       bool MatchZero = true;
37103       bool MatchSign = UseSign;
37104       unsigned NumDstElts = NumMaskElts / Scale;
37105       for (unsigned i = 0;
37106            i != NumDstElts && (MatchAny || MatchSign || MatchZero); ++i) {
37107         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
37108           MatchAny = MatchSign = MatchZero = false;
37109           break;
37110         }
37111         unsigned Pos = (i * Scale) + 1;
37112         unsigned Len = Scale - 1;
37113         MatchAny &= isUndefInRange(Mask, Pos, Len);
37114         MatchZero &= isUndefOrZeroInRange(Mask, Pos, Len);
37115         MatchSign &= isUndefOrEqualInRange(Mask, (int)i, Pos, Len);
37116       }
37117       if (MatchAny || MatchSign || MatchZero) {
37118         assert((MatchSign || MatchZero) &&
37119                "Failed to match sext/zext but matched aext?");
37120         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
37121         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType()
37122                                           : MVT::getIntegerVT(MaskEltSize);
37123         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
37124 
37125         Shuffle = unsigned(
37126             MatchAny ? ISD::ANY_EXTEND
37127                      : (MatchSign ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND));
37128         if (SrcVT.getVectorNumElements() != NumDstElts)
37129           Shuffle = DAG.getOpcode_EXTEND_VECTOR_INREG(Shuffle);
37130 
37131         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
37132         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
37133         return true;
37134       }
37135     }
37136   }
37137 
37138   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
37139   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2()) ||
37140        (MaskEltSize == 16 && Subtarget.hasFP16())) &&
37141       isUndefOrEqual(Mask[0], 0) &&
37142       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
37143     Shuffle = X86ISD::VZEXT_MOVL;
37144     if (MaskEltSize == 16)
37145       SrcVT = DstVT = MaskVT.changeVectorElementType(MVT::f16);
37146     else
37147       SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
37148     return true;
37149   }
37150 
37151   // Check if we have SSE3 which will let us use MOVDDUP etc. The
37152   // instructions are no slower than UNPCKLPD but has the option to
37153   // fold the input operand into even an unaligned memory load.
37154   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
37155     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG, V1)) {
37156       Shuffle = X86ISD::MOVDDUP;
37157       SrcVT = DstVT = MVT::v2f64;
37158       return true;
37159     }
37160     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
37161       Shuffle = X86ISD::MOVSLDUP;
37162       SrcVT = DstVT = MVT::v4f32;
37163       return true;
37164     }
37165     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, DAG, V1)) {
37166       Shuffle = X86ISD::MOVSHDUP;
37167       SrcVT = DstVT = MVT::v4f32;
37168       return true;
37169     }
37170   }
37171 
37172   if (MaskVT.is256BitVector() && AllowFloatDomain) {
37173     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
37174     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, DAG, V1)) {
37175       Shuffle = X86ISD::MOVDDUP;
37176       SrcVT = DstVT = MVT::v4f64;
37177       return true;
37178     }
37179     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
37180                                   V1)) {
37181       Shuffle = X86ISD::MOVSLDUP;
37182       SrcVT = DstVT = MVT::v8f32;
37183       return true;
37184     }
37185     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, DAG,
37186                                   V1)) {
37187       Shuffle = X86ISD::MOVSHDUP;
37188       SrcVT = DstVT = MVT::v8f32;
37189       return true;
37190     }
37191   }
37192 
37193   if (MaskVT.is512BitVector() && AllowFloatDomain) {
37194     assert(Subtarget.hasAVX512() &&
37195            "AVX512 required for 512-bit vector shuffles");
37196     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, DAG,
37197                                   V1)) {
37198       Shuffle = X86ISD::MOVDDUP;
37199       SrcVT = DstVT = MVT::v8f64;
37200       return true;
37201     }
37202     if (isTargetShuffleEquivalent(
37203             MaskVT, Mask,
37204             {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, DAG, V1)) {
37205       Shuffle = X86ISD::MOVSLDUP;
37206       SrcVT = DstVT = MVT::v16f32;
37207       return true;
37208     }
37209     if (isTargetShuffleEquivalent(
37210             MaskVT, Mask,
37211             {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, DAG, V1)) {
37212       Shuffle = X86ISD::MOVSHDUP;
37213       SrcVT = DstVT = MVT::v16f32;
37214       return true;
37215     }
37216   }
37217 
37218   return false;
37219 }
37220 
37221 // Attempt to match a combined shuffle mask against supported unary immediate
37222 // permute instructions.
37223 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryPermuteShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,const SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)37224 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
37225                                      const APInt &Zeroable,
37226                                      bool AllowFloatDomain, bool AllowIntDomain,
37227                                      const SelectionDAG &DAG,
37228                                      const X86Subtarget &Subtarget,
37229                                      unsigned &Shuffle, MVT &ShuffleVT,
37230                                      unsigned &PermuteImm) {
37231   unsigned NumMaskElts = Mask.size();
37232   unsigned InputSizeInBits = MaskVT.getSizeInBits();
37233   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
37234   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
37235   bool ContainsZeros = isAnyZero(Mask);
37236 
37237   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
37238   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
37239     // Check for lane crossing permutes.
37240     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
37241       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
37242       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
37243         Shuffle = X86ISD::VPERMI;
37244         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
37245         PermuteImm = getV4X86ShuffleImm(Mask);
37246         return true;
37247       }
37248       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
37249         SmallVector<int, 4> RepeatedMask;
37250         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
37251           Shuffle = X86ISD::VPERMI;
37252           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
37253           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
37254           return true;
37255         }
37256       }
37257     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
37258       // VPERMILPD can permute with a non-repeating shuffle.
37259       Shuffle = X86ISD::VPERMILPI;
37260       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
37261       PermuteImm = 0;
37262       for (int i = 0, e = Mask.size(); i != e; ++i) {
37263         int M = Mask[i];
37264         if (M == SM_SentinelUndef)
37265           continue;
37266         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
37267         PermuteImm |= (M & 1) << i;
37268       }
37269       return true;
37270     }
37271   }
37272 
37273   // We are checking for shuffle match or shift match. Loop twice so we can
37274   // order which we try and match first depending on target preference.
37275   for (unsigned Order = 0; Order < 2; ++Order) {
37276     if (Subtarget.preferLowerShuffleAsShift() ? (Order == 1) : (Order == 0)) {
37277       // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
37278       // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
37279       // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
37280       if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
37281           !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
37282         SmallVector<int, 4> RepeatedMask;
37283         if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
37284           // Narrow the repeated mask to create 32-bit element permutes.
37285           SmallVector<int, 4> WordMask = RepeatedMask;
37286           if (MaskScalarSizeInBits == 64)
37287             narrowShuffleMaskElts(2, RepeatedMask, WordMask);
37288 
37289           Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
37290           ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
37291           ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
37292           PermuteImm = getV4X86ShuffleImm(WordMask);
37293           return true;
37294         }
37295       }
37296 
37297       // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
37298       if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
37299           ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37300            (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37301            (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
37302         SmallVector<int, 4> RepeatedMask;
37303         if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
37304           ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
37305           ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
37306 
37307           // PSHUFLW: permute lower 4 elements only.
37308           if (isUndefOrInRange(LoMask, 0, 4) &&
37309               isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
37310             Shuffle = X86ISD::PSHUFLW;
37311             ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
37312             PermuteImm = getV4X86ShuffleImm(LoMask);
37313             return true;
37314           }
37315 
37316           // PSHUFHW: permute upper 4 elements only.
37317           if (isUndefOrInRange(HiMask, 4, 8) &&
37318               isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
37319             // Offset the HiMask so that we can create the shuffle immediate.
37320             int OffsetHiMask[4];
37321             for (int i = 0; i != 4; ++i)
37322               OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
37323 
37324             Shuffle = X86ISD::PSHUFHW;
37325             ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
37326             PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
37327             return true;
37328           }
37329         }
37330       }
37331     } else {
37332       // Attempt to match against bit rotates.
37333       if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
37334           ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
37335            Subtarget.hasAVX512())) {
37336         int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
37337                                                 Subtarget, Mask);
37338         if (0 < RotateAmt) {
37339           Shuffle = X86ISD::VROTLI;
37340           PermuteImm = (unsigned)RotateAmt;
37341           return true;
37342         }
37343       }
37344     }
37345     // Attempt to match against byte/bit shifts.
37346     if (AllowIntDomain &&
37347         ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37348          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37349          (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37350       int ShiftAmt =
37351           matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits, Mask, 0,
37352                               Zeroable, Subtarget);
37353       if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
37354                            32 <= ShuffleVT.getScalarSizeInBits())) {
37355         // Byte shifts can be slower so only match them on second attempt.
37356         if (Order == 0 &&
37357             (Shuffle == X86ISD::VSHLDQ || Shuffle == X86ISD::VSRLDQ))
37358           continue;
37359 
37360         PermuteImm = (unsigned)ShiftAmt;
37361         return true;
37362       }
37363 
37364     }
37365   }
37366 
37367   return false;
37368 }
37369 
37370 // Attempt to match a combined unary shuffle mask against supported binary
37371 // shuffle instructions.
37372 // TODO: Investigate sharing more of this with shuffle lowering.
matchBinaryShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,SDValue & V2,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT,bool IsUnary)37373 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
37374                                bool AllowFloatDomain, bool AllowIntDomain,
37375                                SDValue &V1, SDValue &V2, const SDLoc &DL,
37376                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
37377                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
37378                                bool IsUnary) {
37379   unsigned NumMaskElts = Mask.size();
37380   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
37381   unsigned SizeInBits = MaskVT.getSizeInBits();
37382 
37383   if (MaskVT.is128BitVector()) {
37384     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, DAG) &&
37385         AllowFloatDomain) {
37386       V2 = V1;
37387       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
37388       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
37389       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
37390       return true;
37391     }
37392     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}, DAG) &&
37393         AllowFloatDomain) {
37394       V2 = V1;
37395       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
37396       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
37397       return true;
37398     }
37399     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}, DAG) &&
37400         Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
37401       std::swap(V1, V2);
37402       Shuffle = X86ISD::MOVSD;
37403       SrcVT = DstVT = MVT::v2f64;
37404       return true;
37405     }
37406     if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG) &&
37407         (AllowFloatDomain || !Subtarget.hasSSE41())) {
37408       Shuffle = X86ISD::MOVSS;
37409       SrcVT = DstVT = MVT::v4f32;
37410       return true;
37411     }
37412     if (isTargetShuffleEquivalent(MaskVT, Mask, {8, 1, 2, 3, 4, 5, 6, 7},
37413                                   DAG) &&
37414         Subtarget.hasFP16()) {
37415       Shuffle = X86ISD::MOVSH;
37416       SrcVT = DstVT = MVT::v8f16;
37417       return true;
37418     }
37419   }
37420 
37421   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
37422   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
37423       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
37424       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
37425     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
37426                              Subtarget)) {
37427       DstVT = MaskVT;
37428       return true;
37429     }
37430   }
37431   // TODO: Can we handle this inside matchShuffleWithPACK?
37432   if (MaskVT == MVT::v4i32 && Subtarget.hasSSE2() &&
37433       isTargetShuffleEquivalent(MaskVT, Mask, {0, 2, 4, 6}, DAG) &&
37434       V1.getScalarValueSizeInBits() == 64 &&
37435       V2.getScalarValueSizeInBits() == 64) {
37436     // Use (SSE41) PACKUSWD if the leading zerobits goto the lowest 16-bits.
37437     unsigned MinLZV1 = DAG.computeKnownBits(V1).countMinLeadingZeros();
37438     unsigned MinLZV2 = DAG.computeKnownBits(V2).countMinLeadingZeros();
37439     if (Subtarget.hasSSE41() && MinLZV1 >= 48 && MinLZV2 >= 48) {
37440       SrcVT = MVT::v4i32;
37441       DstVT = MVT::v8i16;
37442       Shuffle = X86ISD::PACKUS;
37443       return true;
37444     }
37445     // Use PACKUSBW if the leading zerobits goto the lowest 8-bits.
37446     if (MinLZV1 >= 56 && MinLZV2 >= 56) {
37447       SrcVT = MVT::v8i16;
37448       DstVT = MVT::v16i8;
37449       Shuffle = X86ISD::PACKUS;
37450       return true;
37451     }
37452     // Use PACKSSWD if the signbits extend to the lowest 16-bits.
37453     if (DAG.ComputeNumSignBits(V1) > 48 && DAG.ComputeNumSignBits(V2) > 48) {
37454       SrcVT = MVT::v4i32;
37455       DstVT = MVT::v8i16;
37456       Shuffle = X86ISD::PACKSS;
37457       return true;
37458     }
37459   }
37460 
37461   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
37462   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
37463       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37464       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
37465       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37466       (MaskVT.is512BitVector() && Subtarget.hasAVX512() &&
37467        (32 <= EltSizeInBits || Subtarget.hasBWI()))) {
37468     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
37469                               Subtarget)) {
37470       SrcVT = DstVT = MaskVT;
37471       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
37472         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
37473       return true;
37474     }
37475   }
37476 
37477   // Attempt to match against a OR if we're performing a blend shuffle and the
37478   // non-blended source element is zero in each case.
37479   // TODO: Handle cases where V1/V2 sizes doesn't match SizeInBits.
37480   if (SizeInBits == V1.getValueSizeInBits() &&
37481       SizeInBits == V2.getValueSizeInBits() &&
37482       (EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
37483       (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
37484     bool IsBlend = true;
37485     unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
37486     unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
37487     unsigned Scale1 = NumV1Elts / NumMaskElts;
37488     unsigned Scale2 = NumV2Elts / NumMaskElts;
37489     APInt DemandedZeroV1 = APInt::getZero(NumV1Elts);
37490     APInt DemandedZeroV2 = APInt::getZero(NumV2Elts);
37491     for (unsigned i = 0; i != NumMaskElts; ++i) {
37492       int M = Mask[i];
37493       if (M == SM_SentinelUndef)
37494         continue;
37495       if (M == SM_SentinelZero) {
37496         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
37497         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
37498         continue;
37499       }
37500       if (M == (int)i) {
37501         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
37502         continue;
37503       }
37504       if (M == (int)(i + NumMaskElts)) {
37505         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
37506         continue;
37507       }
37508       IsBlend = false;
37509       break;
37510     }
37511     if (IsBlend) {
37512       if (DAG.MaskedVectorIsZero(V1, DemandedZeroV1) &&
37513           DAG.MaskedVectorIsZero(V2, DemandedZeroV2)) {
37514         Shuffle = ISD::OR;
37515         SrcVT = DstVT = MaskVT.changeTypeToInteger();
37516         return true;
37517       }
37518       if (NumV1Elts == NumV2Elts && NumV1Elts == NumMaskElts) {
37519         // FIXME: handle mismatched sizes?
37520         // TODO: investigate if `ISD::OR` handling in
37521         // `TargetLowering::SimplifyDemandedVectorElts` can be improved instead.
37522         auto computeKnownBitsElementWise = [&DAG](SDValue V) {
37523           unsigned NumElts = V.getValueType().getVectorNumElements();
37524           KnownBits Known(NumElts);
37525           for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
37526             APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
37527             KnownBits PeepholeKnown = DAG.computeKnownBits(V, Mask);
37528             if (PeepholeKnown.isZero())
37529               Known.Zero.setBit(EltIdx);
37530             if (PeepholeKnown.isAllOnes())
37531               Known.One.setBit(EltIdx);
37532           }
37533           return Known;
37534         };
37535 
37536         KnownBits V1Known = computeKnownBitsElementWise(V1);
37537         KnownBits V2Known = computeKnownBitsElementWise(V2);
37538 
37539         for (unsigned i = 0; i != NumMaskElts && IsBlend; ++i) {
37540           int M = Mask[i];
37541           if (M == SM_SentinelUndef)
37542             continue;
37543           if (M == SM_SentinelZero) {
37544             IsBlend &= V1Known.Zero[i] && V2Known.Zero[i];
37545             continue;
37546           }
37547           if (M == (int)i) {
37548             IsBlend &= V2Known.Zero[i] || V1Known.One[i];
37549             continue;
37550           }
37551           if (M == (int)(i + NumMaskElts)) {
37552             IsBlend &= V1Known.Zero[i] || V2Known.One[i];
37553             continue;
37554           }
37555           llvm_unreachable("will not get here.");
37556         }
37557         if (IsBlend) {
37558           Shuffle = ISD::OR;
37559           SrcVT = DstVT = MaskVT.changeTypeToInteger();
37560           return true;
37561         }
37562       }
37563     }
37564   }
37565 
37566   return false;
37567 }
37568 
matchBinaryPermuteShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,SDValue & V2,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)37569 static bool matchBinaryPermuteShuffle(
37570     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
37571     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
37572     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
37573     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
37574   unsigned NumMaskElts = Mask.size();
37575   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
37576 
37577   // Attempt to match against VALIGND/VALIGNQ rotate.
37578   if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
37579       ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
37580        (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
37581        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37582     if (!isAnyZero(Mask)) {
37583       int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
37584       if (0 < Rotation) {
37585         Shuffle = X86ISD::VALIGN;
37586         if (EltSizeInBits == 64)
37587           ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
37588         else
37589           ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
37590         PermuteImm = Rotation;
37591         return true;
37592       }
37593     }
37594   }
37595 
37596   // Attempt to match against PALIGNR byte rotate.
37597   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
37598                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
37599                          (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
37600     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
37601     if (0 < ByteRotation) {
37602       Shuffle = X86ISD::PALIGNR;
37603       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
37604       PermuteImm = ByteRotation;
37605       return true;
37606     }
37607   }
37608 
37609   // Attempt to combine to X86ISD::BLENDI.
37610   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
37611                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
37612       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
37613     uint64_t BlendMask = 0;
37614     bool ForceV1Zero = false, ForceV2Zero = false;
37615     SmallVector<int, 8> TargetMask(Mask);
37616     if (matchShuffleAsBlend(MaskVT, V1, V2, TargetMask, Zeroable, ForceV1Zero,
37617                             ForceV2Zero, BlendMask)) {
37618       if (MaskVT == MVT::v16i16) {
37619         // We can only use v16i16 PBLENDW if the lanes are repeated.
37620         SmallVector<int, 8> RepeatedMask;
37621         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
37622                                         RepeatedMask)) {
37623           assert(RepeatedMask.size() == 8 &&
37624                  "Repeated mask size doesn't match!");
37625           PermuteImm = 0;
37626           for (int i = 0; i < 8; ++i)
37627             if (RepeatedMask[i] >= 8)
37628               PermuteImm |= 1 << i;
37629           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
37630           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
37631           Shuffle = X86ISD::BLENDI;
37632           ShuffleVT = MaskVT;
37633           return true;
37634         }
37635       } else {
37636         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
37637         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
37638         PermuteImm = (unsigned)BlendMask;
37639         Shuffle = X86ISD::BLENDI;
37640         ShuffleVT = MaskVT;
37641         return true;
37642       }
37643     }
37644   }
37645 
37646   // Attempt to combine to INSERTPS, but only if it has elements that need to
37647   // be set to zero.
37648   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
37649       MaskVT.is128BitVector() && isAnyZero(Mask) &&
37650       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
37651     Shuffle = X86ISD::INSERTPS;
37652     ShuffleVT = MVT::v4f32;
37653     return true;
37654   }
37655 
37656   // Attempt to combine to SHUFPD.
37657   if (AllowFloatDomain && EltSizeInBits == 64 &&
37658       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
37659        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
37660        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37661     bool ForceV1Zero = false, ForceV2Zero = false;
37662     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
37663                                PermuteImm, Mask, Zeroable)) {
37664       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
37665       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
37666       Shuffle = X86ISD::SHUFP;
37667       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
37668       return true;
37669     }
37670   }
37671 
37672   // Attempt to combine to SHUFPS.
37673   if (AllowFloatDomain && EltSizeInBits == 32 &&
37674       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
37675        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
37676        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
37677     SmallVector<int, 4> RepeatedMask;
37678     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
37679       // Match each half of the repeated mask, to determine if its just
37680       // referencing one of the vectors, is zeroable or entirely undef.
37681       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
37682         int M0 = RepeatedMask[Offset];
37683         int M1 = RepeatedMask[Offset + 1];
37684 
37685         if (isUndefInRange(RepeatedMask, Offset, 2)) {
37686           return DAG.getUNDEF(MaskVT);
37687         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
37688           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
37689           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
37690           return getZeroVector(MaskVT, Subtarget, DAG, DL);
37691         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
37692           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
37693           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
37694           return V1;
37695         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
37696           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
37697           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
37698           return V2;
37699         }
37700 
37701         return SDValue();
37702       };
37703 
37704       int ShufMask[4] = {-1, -1, -1, -1};
37705       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
37706       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
37707 
37708       if (Lo && Hi) {
37709         V1 = Lo;
37710         V2 = Hi;
37711         Shuffle = X86ISD::SHUFP;
37712         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
37713         PermuteImm = getV4X86ShuffleImm(ShufMask);
37714         return true;
37715       }
37716     }
37717   }
37718 
37719   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
37720   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
37721       MaskVT.is128BitVector() &&
37722       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
37723     Shuffle = X86ISD::INSERTPS;
37724     ShuffleVT = MVT::v4f32;
37725     return true;
37726   }
37727 
37728   return false;
37729 }
37730 
37731 static SDValue combineX86ShuffleChainWithExtract(
37732     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
37733     bool HasVariableMask, bool AllowVariableCrossLaneMask,
37734     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
37735     const X86Subtarget &Subtarget);
37736 
37737 /// Combine an arbitrary chain of shuffles into a single instruction if
37738 /// possible.
37739 ///
37740 /// This is the leaf of the recursive combine below. When we have found some
37741 /// chain of single-use x86 shuffle instructions and accumulated the combined
37742 /// shuffle mask represented by them, this will try to pattern match that mask
37743 /// into either a single instruction if there is a special purpose instruction
37744 /// for this operation, or into a PSHUFB instruction which is a fully general
37745 /// instruction but should only be used to replace chains over a certain depth.
combineX86ShuffleChain(ArrayRef<SDValue> Inputs,SDValue Root,ArrayRef<int> BaseMask,int Depth,bool HasVariableMask,bool AllowVariableCrossLaneMask,bool AllowVariablePerLaneMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)37746 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
37747                                       ArrayRef<int> BaseMask, int Depth,
37748                                       bool HasVariableMask,
37749                                       bool AllowVariableCrossLaneMask,
37750                                       bool AllowVariablePerLaneMask,
37751                                       SelectionDAG &DAG,
37752                                       const X86Subtarget &Subtarget) {
37753   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
37754   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
37755          "Unexpected number of shuffle inputs!");
37756 
37757   SDLoc DL(Root);
37758   MVT RootVT = Root.getSimpleValueType();
37759   unsigned RootSizeInBits = RootVT.getSizeInBits();
37760   unsigned NumRootElts = RootVT.getVectorNumElements();
37761 
37762   // Canonicalize shuffle input op to the requested type.
37763   auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
37764     if (VT.getSizeInBits() > Op.getValueSizeInBits())
37765       Op = widenSubVector(Op, false, Subtarget, DAG, DL, VT.getSizeInBits());
37766     else if (VT.getSizeInBits() < Op.getValueSizeInBits())
37767       Op = extractSubVector(Op, 0, DAG, DL, VT.getSizeInBits());
37768     return DAG.getBitcast(VT, Op);
37769   };
37770 
37771   // Find the inputs that enter the chain. Note that multiple uses are OK
37772   // here, we're not going to remove the operands we find.
37773   bool UnaryShuffle = (Inputs.size() == 1);
37774   SDValue V1 = peekThroughBitcasts(Inputs[0]);
37775   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
37776                              : peekThroughBitcasts(Inputs[1]));
37777 
37778   MVT VT1 = V1.getSimpleValueType();
37779   MVT VT2 = V2.getSimpleValueType();
37780   assert((RootSizeInBits % VT1.getSizeInBits()) == 0 &&
37781          (RootSizeInBits % VT2.getSizeInBits()) == 0 && "Vector size mismatch");
37782 
37783   SDValue Res;
37784 
37785   unsigned NumBaseMaskElts = BaseMask.size();
37786   if (NumBaseMaskElts == 1) {
37787     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
37788     return CanonicalizeShuffleInput(RootVT, V1);
37789   }
37790 
37791   bool OptForSize = DAG.shouldOptForSize();
37792   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
37793   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
37794                      (RootVT.isFloatingPoint() && Depth >= 1) ||
37795                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
37796 
37797   // Don't combine if we are a AVX512/EVEX target and the mask element size
37798   // is different from the root element size - this would prevent writemasks
37799   // from being reused.
37800   bool IsMaskedShuffle = false;
37801   if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
37802     if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
37803         Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
37804       IsMaskedShuffle = true;
37805     }
37806   }
37807 
37808   // If we are shuffling a splat (and not introducing zeros) then we can just
37809   // use it directly. This works for smaller elements as well as they already
37810   // repeat across each mask element.
37811   if (UnaryShuffle && !isAnyZero(BaseMask) &&
37812       V1.getValueSizeInBits() >= RootSizeInBits &&
37813       (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
37814       DAG.isSplatValue(V1, /*AllowUndefs*/ false)) {
37815     return CanonicalizeShuffleInput(RootVT, V1);
37816   }
37817 
37818   SmallVector<int, 64> Mask(BaseMask);
37819 
37820   // See if the shuffle is a hidden identity shuffle - repeated args in HOPs
37821   // etc. can be simplified.
37822   if (VT1 == VT2 && VT1.getSizeInBits() == RootSizeInBits && VT1.isVector()) {
37823     SmallVector<int> ScaledMask, IdentityMask;
37824     unsigned NumElts = VT1.getVectorNumElements();
37825     if (Mask.size() <= NumElts &&
37826         scaleShuffleElements(Mask, NumElts, ScaledMask)) {
37827       for (unsigned i = 0; i != NumElts; ++i)
37828         IdentityMask.push_back(i);
37829       if (isTargetShuffleEquivalent(RootVT, ScaledMask, IdentityMask, DAG, V1,
37830                                     V2))
37831         return CanonicalizeShuffleInput(RootVT, V1);
37832     }
37833   }
37834 
37835   // Handle 128/256-bit lane shuffles of 512-bit vectors.
37836   if (RootVT.is512BitVector() &&
37837       (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
37838     // If the upper subvectors are zeroable, then an extract+insert is more
37839     // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
37840     // to zero the upper subvectors.
37841     if (isUndefOrZeroInRange(Mask, 1, NumBaseMaskElts - 1)) {
37842       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37843         return SDValue(); // Nothing to do!
37844       assert(isInRange(Mask[0], 0, NumBaseMaskElts) &&
37845              "Unexpected lane shuffle");
37846       Res = CanonicalizeShuffleInput(RootVT, V1);
37847       unsigned SubIdx = Mask[0] * (NumRootElts / NumBaseMaskElts);
37848       bool UseZero = isAnyZero(Mask);
37849       Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
37850       return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
37851     }
37852 
37853     // Narrow shuffle mask to v4x128.
37854     SmallVector<int, 4> ScaledMask;
37855     assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
37856     narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, Mask, ScaledMask);
37857 
37858     // Try to lower to vshuf64x2/vshuf32x4.
37859     auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL,
37860                             ArrayRef<int> ScaledMask, SDValue V1, SDValue V2,
37861                             SelectionDAG &DAG) {
37862       int PermMask[4] = {-1, -1, -1, -1};
37863       // Ensure elements came from the same Op.
37864       SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
37865       for (int i = 0; i < 4; ++i) {
37866         assert(ScaledMask[i] >= -1 && "Illegal shuffle sentinel value");
37867         if (ScaledMask[i] < 0)
37868           continue;
37869 
37870         SDValue Op = ScaledMask[i] >= 4 ? V2 : V1;
37871         unsigned OpIndex = i / 2;
37872         if (Ops[OpIndex].isUndef())
37873           Ops[OpIndex] = Op;
37874         else if (Ops[OpIndex] != Op)
37875           return SDValue();
37876 
37877         PermMask[i] = ScaledMask[i] % 4;
37878       }
37879 
37880       return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
37881                          CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
37882                          CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
37883                          getV4X86ShuffleImm8ForMask(PermMask, DL, DAG));
37884     };
37885 
37886     // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
37887     // doesn't work because our mask is for 128 bits and we don't have an MVT
37888     // to match that.
37889     bool PreferPERMQ = UnaryShuffle && isUndefOrInRange(ScaledMask[0], 0, 2) &&
37890                        isUndefOrInRange(ScaledMask[1], 0, 2) &&
37891                        isUndefOrInRange(ScaledMask[2], 2, 4) &&
37892                        isUndefOrInRange(ScaledMask[3], 2, 4) &&
37893                        (ScaledMask[0] < 0 || ScaledMask[2] < 0 ||
37894                         ScaledMask[0] == (ScaledMask[2] % 2)) &&
37895                        (ScaledMask[1] < 0 || ScaledMask[3] < 0 ||
37896                         ScaledMask[1] == (ScaledMask[3] % 2));
37897 
37898     if (!isAnyZero(ScaledMask) && !PreferPERMQ) {
37899       if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
37900         return SDValue(); // Nothing to do!
37901       MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
37902       if (SDValue V = MatchSHUF128(ShuffleVT, DL, ScaledMask, V1, V2, DAG))
37903         return DAG.getBitcast(RootVT, V);
37904     }
37905   }
37906 
37907   // Handle 128-bit lane shuffles of 256-bit vectors.
37908   if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
37909     // If the upper half is zeroable, then an extract+insert is more optimal
37910     // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
37911     // zero the upper half.
37912     if (isUndefOrZero(Mask[1])) {
37913       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37914         return SDValue(); // Nothing to do!
37915       assert(isInRange(Mask[0], 0, 2) && "Unexpected lane shuffle");
37916       Res = CanonicalizeShuffleInput(RootVT, V1);
37917       Res = extract128BitVector(Res, Mask[0] * (NumRootElts / 2), DAG, DL);
37918       return widenSubVector(Res, Mask[1] == SM_SentinelZero, Subtarget, DAG, DL,
37919                             256);
37920     }
37921 
37922     // If we're inserting the low subvector, an insert-subvector 'concat'
37923     // pattern is quicker than VPERM2X128.
37924     // TODO: Add AVX2 support instead of VPERMQ/VPERMPD.
37925     if (BaseMask[0] == 0 && (BaseMask[1] == 0 || BaseMask[1] == 2) &&
37926         !Subtarget.hasAVX2()) {
37927       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
37928         return SDValue(); // Nothing to do!
37929       SDValue Lo = CanonicalizeShuffleInput(RootVT, V1);
37930       SDValue Hi = CanonicalizeShuffleInput(RootVT, BaseMask[1] == 0 ? V1 : V2);
37931       Hi = extractSubVector(Hi, 0, DAG, DL, 128);
37932       return insertSubVector(Lo, Hi, NumRootElts / 2, DAG, DL, 128);
37933     }
37934 
37935     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
37936       return SDValue(); // Nothing to do!
37937 
37938     // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
37939     // we need to use the zeroing feature.
37940     // Prefer blends for sequential shuffles unless we are optimizing for size.
37941     if (UnaryShuffle &&
37942         !(Subtarget.hasAVX2() && isUndefOrInRange(Mask, 0, 2)) &&
37943         (OptForSize || !isSequentialOrUndefOrZeroInRange(Mask, 0, 2, 0))) {
37944       unsigned PermMask = 0;
37945       PermMask |= ((Mask[0] < 0 ? 0x8 : (Mask[0] & 1)) << 0);
37946       PermMask |= ((Mask[1] < 0 ? 0x8 : (Mask[1] & 1)) << 4);
37947       return DAG.getNode(
37948           X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
37949           DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
37950     }
37951 
37952     if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
37953       return SDValue(); // Nothing to do!
37954 
37955     // TODO - handle AVX512VL cases with X86ISD::SHUF128.
37956     if (!UnaryShuffle && !IsMaskedShuffle) {
37957       assert(llvm::all_of(Mask, [](int M) { return 0 <= M && M < 4; }) &&
37958              "Unexpected shuffle sentinel value");
37959       // Prefer blends to X86ISD::VPERM2X128.
37960       if (!((Mask[0] == 0 && Mask[1] == 3) || (Mask[0] == 2 && Mask[1] == 1))) {
37961         unsigned PermMask = 0;
37962         PermMask |= ((Mask[0] & 3) << 0);
37963         PermMask |= ((Mask[1] & 3) << 4);
37964         SDValue LHS = isInRange(Mask[0], 0, 2) ? V1 : V2;
37965         SDValue RHS = isInRange(Mask[1], 0, 2) ? V1 : V2;
37966         return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
37967                           CanonicalizeShuffleInput(RootVT, LHS),
37968                           CanonicalizeShuffleInput(RootVT, RHS),
37969                           DAG.getTargetConstant(PermMask, DL, MVT::i8));
37970       }
37971     }
37972   }
37973 
37974   // For masks that have been widened to 128-bit elements or more,
37975   // narrow back down to 64-bit elements.
37976   if (BaseMaskEltSizeInBits > 64) {
37977     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
37978     int MaskScale = BaseMaskEltSizeInBits / 64;
37979     SmallVector<int, 64> ScaledMask;
37980     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
37981     Mask = std::move(ScaledMask);
37982   }
37983 
37984   // For masked shuffles, we're trying to match the root width for better
37985   // writemask folding, attempt to scale the mask.
37986   // TODO - variable shuffles might need this to be widened again.
37987   if (IsMaskedShuffle && NumRootElts > Mask.size()) {
37988     assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
37989     int MaskScale = NumRootElts / Mask.size();
37990     SmallVector<int, 64> ScaledMask;
37991     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
37992     Mask = std::move(ScaledMask);
37993   }
37994 
37995   unsigned NumMaskElts = Mask.size();
37996   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
37997 
37998   // Determine the effective mask value type.
37999   FloatDomain &= (32 <= MaskEltSizeInBits);
38000   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
38001                            : MVT::getIntegerVT(MaskEltSizeInBits);
38002   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
38003 
38004   // Only allow legal mask types.
38005   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
38006     return SDValue();
38007 
38008   // Attempt to match the mask against known shuffle patterns.
38009   MVT ShuffleSrcVT, ShuffleVT;
38010   unsigned Shuffle, PermuteImm;
38011 
38012   // Which shuffle domains are permitted?
38013   // Permit domain crossing at higher combine depths.
38014   // TODO: Should we indicate which domain is preferred if both are allowed?
38015   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
38016   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
38017                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
38018 
38019   // Determine zeroable mask elements.
38020   APInt KnownUndef, KnownZero;
38021   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
38022   APInt Zeroable = KnownUndef | KnownZero;
38023 
38024   if (UnaryShuffle) {
38025     // Attempt to match against broadcast-from-vector.
38026     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
38027     if ((Subtarget.hasAVX2() ||
38028          (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
38029         (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
38030       if (isUndefOrEqual(Mask, 0)) {
38031         if (V1.getValueType() == MaskVT &&
38032             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
38033             X86::mayFoldLoad(V1.getOperand(0), Subtarget)) {
38034           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
38035             return SDValue(); // Nothing to do!
38036           Res = V1.getOperand(0);
38037           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
38038           return DAG.getBitcast(RootVT, Res);
38039         }
38040         if (Subtarget.hasAVX2()) {
38041           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
38042             return SDValue(); // Nothing to do!
38043           Res = CanonicalizeShuffleInput(MaskVT, V1);
38044           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
38045           return DAG.getBitcast(RootVT, Res);
38046         }
38047       }
38048     }
38049 
38050     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, V1,
38051                           DAG, Subtarget, Shuffle, ShuffleSrcVT, ShuffleVT) &&
38052         (!IsMaskedShuffle ||
38053          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38054       if (Depth == 0 && Root.getOpcode() == Shuffle)
38055         return SDValue(); // Nothing to do!
38056       Res = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
38057       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
38058       return DAG.getBitcast(RootVT, Res);
38059     }
38060 
38061     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
38062                                  AllowIntDomain, DAG, Subtarget, Shuffle, ShuffleVT,
38063                                  PermuteImm) &&
38064         (!IsMaskedShuffle ||
38065          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38066       if (Depth == 0 && Root.getOpcode() == Shuffle)
38067         return SDValue(); // Nothing to do!
38068       Res = CanonicalizeShuffleInput(ShuffleVT, V1);
38069       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
38070                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38071       return DAG.getBitcast(RootVT, Res);
38072     }
38073   }
38074 
38075   // Attempt to combine to INSERTPS, but only if the inserted element has come
38076   // from a scalar.
38077   // TODO: Handle other insertions here as well?
38078   if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
38079       Subtarget.hasSSE41() &&
38080       !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}, DAG)) {
38081     if (MaskEltSizeInBits == 32) {
38082       SDValue SrcV1 = V1, SrcV2 = V2;
38083       if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
38084                                  DAG) &&
38085           SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
38086         if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
38087           return SDValue(); // Nothing to do!
38088         Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
38089                           CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
38090                           CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
38091                           DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38092         return DAG.getBitcast(RootVT, Res);
38093       }
38094     }
38095     if (MaskEltSizeInBits == 64 &&
38096         isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}, DAG) &&
38097         V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
38098         V2.getScalarValueSizeInBits() <= 32) {
38099       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
38100         return SDValue(); // Nothing to do!
38101       PermuteImm = (/*DstIdx*/ 2 << 4) | (/*SrcIdx*/ 0 << 0);
38102       Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
38103                         CanonicalizeShuffleInput(MVT::v4f32, V1),
38104                         CanonicalizeShuffleInput(MVT::v4f32, V2),
38105                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38106       return DAG.getBitcast(RootVT, Res);
38107     }
38108   }
38109 
38110   SDValue NewV1 = V1; // Save operands in case early exit happens.
38111   SDValue NewV2 = V2;
38112   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
38113                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
38114                          ShuffleVT, UnaryShuffle) &&
38115       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38116     if (Depth == 0 && Root.getOpcode() == Shuffle)
38117       return SDValue(); // Nothing to do!
38118     NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
38119     NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
38120     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
38121     return DAG.getBitcast(RootVT, Res);
38122   }
38123 
38124   NewV1 = V1; // Save operands in case early exit happens.
38125   NewV2 = V2;
38126   if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
38127                                 AllowIntDomain, NewV1, NewV2, DL, DAG,
38128                                 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
38129       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
38130     if (Depth == 0 && Root.getOpcode() == Shuffle)
38131       return SDValue(); // Nothing to do!
38132     NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
38133     NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
38134     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
38135                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
38136     return DAG.getBitcast(RootVT, Res);
38137   }
38138 
38139   // Typically from here on, we need an integer version of MaskVT.
38140   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
38141   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
38142 
38143   // Annoyingly, SSE4A instructions don't map into the above match helpers.
38144   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
38145     uint64_t BitLen, BitIdx;
38146     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
38147                             Zeroable)) {
38148       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
38149         return SDValue(); // Nothing to do!
38150       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
38151       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
38152                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
38153                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
38154       return DAG.getBitcast(RootVT, Res);
38155     }
38156 
38157     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
38158       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
38159         return SDValue(); // Nothing to do!
38160       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
38161       V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
38162       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
38163                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
38164                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
38165       return DAG.getBitcast(RootVT, Res);
38166     }
38167   }
38168 
38169   // Match shuffle against TRUNCATE patterns.
38170   if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
38171     // Match against a VTRUNC instruction, accounting for src/dst sizes.
38172     if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
38173                              Subtarget)) {
38174       bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
38175                         ShuffleSrcVT.getVectorNumElements();
38176       unsigned Opc =
38177           IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
38178       if (Depth == 0 && Root.getOpcode() == Opc)
38179         return SDValue(); // Nothing to do!
38180       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
38181       Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
38182       if (ShuffleVT.getSizeInBits() < RootSizeInBits)
38183         Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
38184       return DAG.getBitcast(RootVT, Res);
38185     }
38186 
38187     // Do we need a more general binary truncation pattern?
38188     if (RootSizeInBits < 512 &&
38189         ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
38190          (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
38191         (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
38192         isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
38193       // Bail if this was already a truncation or PACK node.
38194       // We sometimes fail to match PACK if we demand known undef elements.
38195       if (Depth == 0 && (Root.getOpcode() == ISD::TRUNCATE ||
38196                          Root.getOpcode() == X86ISD::PACKSS ||
38197                          Root.getOpcode() == X86ISD::PACKUS))
38198         return SDValue(); // Nothing to do!
38199       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
38200       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
38201       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
38202       V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
38203       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
38204       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
38205       Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
38206       Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
38207       return DAG.getBitcast(RootVT, Res);
38208     }
38209   }
38210 
38211   // Don't try to re-form single instruction chains under any circumstances now
38212   // that we've done encoding canonicalization for them.
38213   if (Depth < 1)
38214     return SDValue();
38215 
38216   // Depth threshold above which we can efficiently use variable mask shuffles.
38217   int VariableCrossLaneShuffleDepth =
38218       Subtarget.hasFastVariableCrossLaneShuffle() ? 1 : 2;
38219   int VariablePerLaneShuffleDepth =
38220       Subtarget.hasFastVariablePerLaneShuffle() ? 1 : 2;
38221   AllowVariableCrossLaneMask &=
38222       (Depth >= VariableCrossLaneShuffleDepth) || HasVariableMask;
38223   AllowVariablePerLaneMask &=
38224       (Depth >= VariablePerLaneShuffleDepth) || HasVariableMask;
38225   // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
38226   // higher depth before combining them.
38227   bool AllowBWIVPERMV3 =
38228       (Depth >= (VariableCrossLaneShuffleDepth + 2) || HasVariableMask);
38229 
38230   bool MaskContainsZeros = isAnyZero(Mask);
38231 
38232   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
38233     // If we have a single input lane-crossing shuffle then lower to VPERMV.
38234     if (UnaryShuffle && AllowVariableCrossLaneMask && !MaskContainsZeros) {
38235       if (Subtarget.hasAVX2() &&
38236           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
38237         SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
38238         Res = CanonicalizeShuffleInput(MaskVT, V1);
38239         Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
38240         return DAG.getBitcast(RootVT, Res);
38241       }
38242       // AVX512 variants (non-VLX will pad to 512-bit shuffles).
38243       if ((Subtarget.hasAVX512() &&
38244            (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
38245             MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
38246           (Subtarget.hasBWI() &&
38247            (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
38248           (Subtarget.hasVBMI() &&
38249            (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
38250         V1 = CanonicalizeShuffleInput(MaskVT, V1);
38251         V2 = DAG.getUNDEF(MaskVT);
38252         Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38253         return DAG.getBitcast(RootVT, Res);
38254       }
38255     }
38256 
38257     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
38258     // vector as the second source (non-VLX will pad to 512-bit shuffles).
38259     if (UnaryShuffle && AllowVariableCrossLaneMask &&
38260         ((Subtarget.hasAVX512() &&
38261           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
38262            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
38263            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
38264            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
38265          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
38266           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
38267          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
38268           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
38269       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
38270       for (unsigned i = 0; i != NumMaskElts; ++i)
38271         if (Mask[i] == SM_SentinelZero)
38272           Mask[i] = NumMaskElts + i;
38273       V1 = CanonicalizeShuffleInput(MaskVT, V1);
38274       V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
38275       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38276       return DAG.getBitcast(RootVT, Res);
38277     }
38278 
38279     // If that failed and either input is extracted then try to combine as a
38280     // shuffle with the larger type.
38281     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
38282             Inputs, Root, BaseMask, Depth, HasVariableMask,
38283             AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG,
38284             Subtarget))
38285       return WideShuffle;
38286 
38287     // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
38288     // (non-VLX will pad to 512-bit shuffles).
38289     if (AllowVariableCrossLaneMask && !MaskContainsZeros &&
38290         ((Subtarget.hasAVX512() &&
38291           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
38292            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
38293            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
38294            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
38295          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
38296           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
38297          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
38298           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
38299       V1 = CanonicalizeShuffleInput(MaskVT, V1);
38300       V2 = CanonicalizeShuffleInput(MaskVT, V2);
38301       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38302       return DAG.getBitcast(RootVT, Res);
38303     }
38304     return SDValue();
38305   }
38306 
38307   // See if we can combine a single input shuffle with zeros to a bit-mask,
38308   // which is much simpler than any shuffle.
38309   if (UnaryShuffle && MaskContainsZeros && AllowVariablePerLaneMask &&
38310       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
38311       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
38312     APInt Zero = APInt::getZero(MaskEltSizeInBits);
38313     APInt AllOnes = APInt::getAllOnes(MaskEltSizeInBits);
38314     APInt UndefElts(NumMaskElts, 0);
38315     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
38316     for (unsigned i = 0; i != NumMaskElts; ++i) {
38317       int M = Mask[i];
38318       if (M == SM_SentinelUndef) {
38319         UndefElts.setBit(i);
38320         continue;
38321       }
38322       if (M == SM_SentinelZero)
38323         continue;
38324       EltBits[i] = AllOnes;
38325     }
38326     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
38327     Res = CanonicalizeShuffleInput(MaskVT, V1);
38328     unsigned AndOpcode =
38329         MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
38330     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
38331     return DAG.getBitcast(RootVT, Res);
38332   }
38333 
38334   // If we have a single input shuffle with different shuffle patterns in the
38335   // the 128-bit lanes use the variable mask to VPERMILPS.
38336   // TODO Combine other mask types at higher depths.
38337   if (UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
38338       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
38339        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
38340     SmallVector<SDValue, 16> VPermIdx;
38341     for (int M : Mask) {
38342       SDValue Idx =
38343           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
38344       VPermIdx.push_back(Idx);
38345     }
38346     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
38347     Res = CanonicalizeShuffleInput(MaskVT, V1);
38348     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
38349     return DAG.getBitcast(RootVT, Res);
38350   }
38351 
38352   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
38353   // to VPERMIL2PD/VPERMIL2PS.
38354   if (AllowVariablePerLaneMask && Subtarget.hasXOP() &&
38355       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
38356        MaskVT == MVT::v8f32)) {
38357     // VPERMIL2 Operation.
38358     // Bits[3] - Match Bit.
38359     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
38360     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
38361     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
38362     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
38363     SmallVector<int, 8> VPerm2Idx;
38364     unsigned M2ZImm = 0;
38365     for (int M : Mask) {
38366       if (M == SM_SentinelUndef) {
38367         VPerm2Idx.push_back(-1);
38368         continue;
38369       }
38370       if (M == SM_SentinelZero) {
38371         M2ZImm = 2;
38372         VPerm2Idx.push_back(8);
38373         continue;
38374       }
38375       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
38376       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
38377       VPerm2Idx.push_back(Index);
38378     }
38379     V1 = CanonicalizeShuffleInput(MaskVT, V1);
38380     V2 = CanonicalizeShuffleInput(MaskVT, V2);
38381     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
38382     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
38383                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
38384     return DAG.getBitcast(RootVT, Res);
38385   }
38386 
38387   // If we have 3 or more shuffle instructions or a chain involving a variable
38388   // mask, we can replace them with a single PSHUFB instruction profitably.
38389   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
38390   // instructions, but in practice PSHUFB tends to be *very* fast so we're
38391   // more aggressive.
38392   if (UnaryShuffle && AllowVariablePerLaneMask &&
38393       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
38394        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
38395        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
38396     SmallVector<SDValue, 16> PSHUFBMask;
38397     int NumBytes = RootVT.getSizeInBits() / 8;
38398     int Ratio = NumBytes / NumMaskElts;
38399     for (int i = 0; i < NumBytes; ++i) {
38400       int M = Mask[i / Ratio];
38401       if (M == SM_SentinelUndef) {
38402         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
38403         continue;
38404       }
38405       if (M == SM_SentinelZero) {
38406         PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
38407         continue;
38408       }
38409       M = Ratio * M + i % Ratio;
38410       assert((M / 16) == (i / 16) && "Lane crossing detected");
38411       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
38412     }
38413     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
38414     Res = CanonicalizeShuffleInput(ByteVT, V1);
38415     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
38416     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
38417     return DAG.getBitcast(RootVT, Res);
38418   }
38419 
38420   // With XOP, if we have a 128-bit binary input shuffle we can always combine
38421   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
38422   // slower than PSHUFB on targets that support both.
38423   if (AllowVariablePerLaneMask && RootVT.is128BitVector() &&
38424       Subtarget.hasXOP()) {
38425     // VPPERM Mask Operation
38426     // Bits[4:0] - Byte Index (0 - 31)
38427     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
38428     SmallVector<SDValue, 16> VPPERMMask;
38429     int NumBytes = 16;
38430     int Ratio = NumBytes / NumMaskElts;
38431     for (int i = 0; i < NumBytes; ++i) {
38432       int M = Mask[i / Ratio];
38433       if (M == SM_SentinelUndef) {
38434         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
38435         continue;
38436       }
38437       if (M == SM_SentinelZero) {
38438         VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
38439         continue;
38440       }
38441       M = Ratio * M + i % Ratio;
38442       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
38443     }
38444     MVT ByteVT = MVT::v16i8;
38445     V1 = CanonicalizeShuffleInput(ByteVT, V1);
38446     V2 = CanonicalizeShuffleInput(ByteVT, V2);
38447     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
38448     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
38449     return DAG.getBitcast(RootVT, Res);
38450   }
38451 
38452   // If that failed and either input is extracted then try to combine as a
38453   // shuffle with the larger type.
38454   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
38455           Inputs, Root, BaseMask, Depth, HasVariableMask,
38456           AllowVariableCrossLaneMask, AllowVariablePerLaneMask, DAG, Subtarget))
38457     return WideShuffle;
38458 
38459   // If we have a dual input shuffle then lower to VPERMV3,
38460   // (non-VLX will pad to 512-bit shuffles)
38461   if (!UnaryShuffle && AllowVariablePerLaneMask && !MaskContainsZeros &&
38462       ((Subtarget.hasAVX512() &&
38463         (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
38464          MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
38465          MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
38466          MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
38467          MaskVT == MVT::v16i32)) ||
38468        (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
38469         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 ||
38470          MaskVT == MVT::v32i16)) ||
38471        (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
38472         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 ||
38473          MaskVT == MVT::v64i8)))) {
38474     V1 = CanonicalizeShuffleInput(MaskVT, V1);
38475     V2 = CanonicalizeShuffleInput(MaskVT, V2);
38476     Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
38477     return DAG.getBitcast(RootVT, Res);
38478   }
38479 
38480   // Failed to find any combines.
38481   return SDValue();
38482 }
38483 
38484 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
38485 // instruction if possible.
38486 //
38487 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
38488 // type size to attempt to combine:
38489 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
38490 // -->
38491 // extract_subvector(shuffle(x,y,m2),0)
combineX86ShuffleChainWithExtract(ArrayRef<SDValue> Inputs,SDValue Root,ArrayRef<int> BaseMask,int Depth,bool HasVariableMask,bool AllowVariableCrossLaneMask,bool AllowVariablePerLaneMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)38492 static SDValue combineX86ShuffleChainWithExtract(
38493     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
38494     bool HasVariableMask, bool AllowVariableCrossLaneMask,
38495     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
38496     const X86Subtarget &Subtarget) {
38497   unsigned NumMaskElts = BaseMask.size();
38498   unsigned NumInputs = Inputs.size();
38499   if (NumInputs == 0)
38500     return SDValue();
38501 
38502   EVT RootVT = Root.getValueType();
38503   unsigned RootSizeInBits = RootVT.getSizeInBits();
38504   unsigned RootEltSizeInBits = RootSizeInBits / NumMaskElts;
38505   assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask");
38506 
38507   // Peek through extract_subvector to find widest legal vector.
38508   // TODO: Handle ISD::TRUNCATE
38509   unsigned WideSizeInBits = RootSizeInBits;
38510   for (unsigned I = 0; I != NumInputs; ++I) {
38511     SDValue Input = peekThroughBitcasts(Inputs[I]);
38512     while (Input.getOpcode() == ISD::EXTRACT_SUBVECTOR)
38513       Input = peekThroughBitcasts(Input.getOperand(0));
38514     if (DAG.getTargetLoweringInfo().isTypeLegal(Input.getValueType()) &&
38515         WideSizeInBits < Input.getValueSizeInBits())
38516       WideSizeInBits = Input.getValueSizeInBits();
38517   }
38518 
38519   // Bail if we fail to find a source larger than the existing root.
38520   unsigned Scale = WideSizeInBits / RootSizeInBits;
38521   if (WideSizeInBits <= RootSizeInBits ||
38522       (WideSizeInBits % RootSizeInBits) != 0)
38523     return SDValue();
38524 
38525   // Create new mask for larger type.
38526   SmallVector<int, 64> WideMask(BaseMask);
38527   for (int &M : WideMask) {
38528     if (M < 0)
38529       continue;
38530     M = (M % NumMaskElts) + ((M / NumMaskElts) * Scale * NumMaskElts);
38531   }
38532   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
38533 
38534   // Attempt to peek through inputs and adjust mask when we extract from an
38535   // upper subvector.
38536   int AdjustedMasks = 0;
38537   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
38538   for (unsigned I = 0; I != NumInputs; ++I) {
38539     SDValue &Input = WideInputs[I];
38540     Input = peekThroughBitcasts(Input);
38541     while (Input.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
38542            Input.getOperand(0).getValueSizeInBits() <= WideSizeInBits) {
38543       uint64_t Idx = Input.getConstantOperandVal(1);
38544       if (Idx != 0) {
38545         ++AdjustedMasks;
38546         unsigned InputEltSizeInBits = Input.getScalarValueSizeInBits();
38547         Idx = (Idx * InputEltSizeInBits) / RootEltSizeInBits;
38548 
38549         int lo = I * WideMask.size();
38550         int hi = (I + 1) * WideMask.size();
38551         for (int &M : WideMask)
38552           if (lo <= M && M < hi)
38553             M += Idx;
38554       }
38555       Input = peekThroughBitcasts(Input.getOperand(0));
38556     }
38557   }
38558 
38559   // Remove unused/repeated shuffle source ops.
38560   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
38561   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
38562 
38563   // Bail if we're always extracting from the lowest subvectors,
38564   // combineX86ShuffleChain should match this for the current width, or the
38565   // shuffle still references too many inputs.
38566   if (AdjustedMasks == 0 || WideInputs.size() > 2)
38567     return SDValue();
38568 
38569   // Minor canonicalization of the accumulated shuffle mask to make it easier
38570   // to match below. All this does is detect masks with sequential pairs of
38571   // elements, and shrink them to the half-width mask. It does this in a loop
38572   // so it will reduce the size of the mask to the minimal width mask which
38573   // performs an equivalent shuffle.
38574   while (WideMask.size() > 1) {
38575     SmallVector<int, 64> WidenedMask;
38576     if (!canWidenShuffleElements(WideMask, WidenedMask))
38577       break;
38578     WideMask = std::move(WidenedMask);
38579   }
38580 
38581   // Canonicalization of binary shuffle masks to improve pattern matching by
38582   // commuting the inputs.
38583   if (WideInputs.size() == 2 && canonicalizeShuffleMaskWithCommute(WideMask)) {
38584     ShuffleVectorSDNode::commuteMask(WideMask);
38585     std::swap(WideInputs[0], WideInputs[1]);
38586   }
38587 
38588   // Increase depth for every upper subvector we've peeked through.
38589   Depth += AdjustedMasks;
38590 
38591   // Attempt to combine wider chain.
38592   // TODO: Can we use a better Root?
38593   SDValue WideRoot = WideInputs.front().getValueSizeInBits() >
38594                              WideInputs.back().getValueSizeInBits()
38595                          ? WideInputs.front()
38596                          : WideInputs.back();
38597   assert(WideRoot.getValueSizeInBits() == WideSizeInBits &&
38598          "WideRootSize mismatch");
38599 
38600   if (SDValue WideShuffle =
38601           combineX86ShuffleChain(WideInputs, WideRoot, WideMask, Depth,
38602                                  HasVariableMask, AllowVariableCrossLaneMask,
38603                                  AllowVariablePerLaneMask, DAG, Subtarget)) {
38604     WideShuffle =
38605         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
38606     return DAG.getBitcast(RootVT, WideShuffle);
38607   }
38608 
38609   return SDValue();
38610 }
38611 
38612 // Canonicalize the combined shuffle mask chain with horizontal ops.
38613 // NOTE: This may update the Ops and Mask.
canonicalizeShuffleMaskWithHorizOp(MutableArrayRef<SDValue> Ops,MutableArrayRef<int> Mask,unsigned RootSizeInBits,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)38614 static SDValue canonicalizeShuffleMaskWithHorizOp(
38615     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
38616     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
38617     const X86Subtarget &Subtarget) {
38618   if (Mask.empty() || Ops.empty())
38619     return SDValue();
38620 
38621   SmallVector<SDValue> BC;
38622   for (SDValue Op : Ops)
38623     BC.push_back(peekThroughBitcasts(Op));
38624 
38625   // All ops must be the same horizop + type.
38626   SDValue BC0 = BC[0];
38627   EVT VT0 = BC0.getValueType();
38628   unsigned Opcode0 = BC0.getOpcode();
38629   if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
38630         return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
38631       }))
38632     return SDValue();
38633 
38634   bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
38635                   Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
38636   bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
38637   if (!isHoriz && !isPack)
38638     return SDValue();
38639 
38640   // Do all ops have a single use?
38641   bool OneUseOps = llvm::all_of(Ops, [](SDValue Op) {
38642     return Op.hasOneUse() &&
38643            peekThroughBitcasts(Op) == peekThroughOneUseBitcasts(Op);
38644   });
38645 
38646   int NumElts = VT0.getVectorNumElements();
38647   int NumLanes = VT0.getSizeInBits() / 128;
38648   int NumEltsPerLane = NumElts / NumLanes;
38649   int NumHalfEltsPerLane = NumEltsPerLane / 2;
38650   MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
38651   unsigned EltSizeInBits = RootSizeInBits / Mask.size();
38652 
38653   if (NumEltsPerLane >= 4 &&
38654       (isPack || shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget))) {
38655     SmallVector<int> LaneMask, ScaledMask;
38656     if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, LaneMask) &&
38657         scaleShuffleElements(LaneMask, 4, ScaledMask)) {
38658       // See if we can remove the shuffle by resorting the HOP chain so that
38659       // the HOP args are pre-shuffled.
38660       // TODO: Generalize to any sized/depth chain.
38661       // TODO: Add support for PACKSS/PACKUS.
38662       if (isHoriz) {
38663         // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
38664         auto GetHOpSrc = [&](int M) {
38665           if (M == SM_SentinelUndef)
38666             return DAG.getUNDEF(VT0);
38667           if (M == SM_SentinelZero)
38668             return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
38669           SDValue Src0 = BC[M / 4];
38670           SDValue Src1 = Src0.getOperand((M % 4) >= 2);
38671           if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
38672             return Src1.getOperand(M % 2);
38673           return SDValue();
38674         };
38675         SDValue M0 = GetHOpSrc(ScaledMask[0]);
38676         SDValue M1 = GetHOpSrc(ScaledMask[1]);
38677         SDValue M2 = GetHOpSrc(ScaledMask[2]);
38678         SDValue M3 = GetHOpSrc(ScaledMask[3]);
38679         if (M0 && M1 && M2 && M3) {
38680           SDValue LHS = DAG.getNode(Opcode0, DL, SrcVT, M0, M1);
38681           SDValue RHS = DAG.getNode(Opcode0, DL, SrcVT, M2, M3);
38682           return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
38683         }
38684       }
38685       // shuffle(hop(x,y),hop(z,w)) -> permute(hop(x,z)) etc.
38686       if (Ops.size() >= 2) {
38687         SDValue LHS, RHS;
38688         auto GetHOpSrc = [&](int M, int &OutM) {
38689           // TODO: Support SM_SentinelZero
38690           if (M < 0)
38691             return M == SM_SentinelUndef;
38692           SDValue Src = BC[M / 4].getOperand((M % 4) >= 2);
38693           if (!LHS || LHS == Src) {
38694             LHS = Src;
38695             OutM = (M % 2);
38696             return true;
38697           }
38698           if (!RHS || RHS == Src) {
38699             RHS = Src;
38700             OutM = (M % 2) + 2;
38701             return true;
38702           }
38703           return false;
38704         };
38705         int PostMask[4] = {-1, -1, -1, -1};
38706         if (GetHOpSrc(ScaledMask[0], PostMask[0]) &&
38707             GetHOpSrc(ScaledMask[1], PostMask[1]) &&
38708             GetHOpSrc(ScaledMask[2], PostMask[2]) &&
38709             GetHOpSrc(ScaledMask[3], PostMask[3])) {
38710           LHS = DAG.getBitcast(SrcVT, LHS);
38711           RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
38712           SDValue Res = DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
38713           // Use SHUFPS for the permute so this will work on SSE2 targets,
38714           // shuffle combining and domain handling will simplify this later on.
38715           MVT ShuffleVT = MVT::getVectorVT(MVT::f32, RootSizeInBits / 32);
38716           Res = DAG.getBitcast(ShuffleVT, Res);
38717           return DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
38718                              getV4X86ShuffleImm8ForMask(PostMask, DL, DAG));
38719         }
38720       }
38721     }
38722   }
38723 
38724   if (2 < Ops.size())
38725     return SDValue();
38726 
38727   SDValue BC1 = BC[BC.size() - 1];
38728   if (Mask.size() == VT0.getVectorNumElements()) {
38729     // Canonicalize binary shuffles of horizontal ops that use the
38730     // same sources to an unary shuffle.
38731     // TODO: Try to perform this fold even if the shuffle remains.
38732     if (Ops.size() == 2) {
38733       auto ContainsOps = [](SDValue HOp, SDValue Op) {
38734         return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
38735       };
38736       // Commute if all BC0's ops are contained in BC1.
38737       if (ContainsOps(BC1, BC0.getOperand(0)) &&
38738           ContainsOps(BC1, BC0.getOperand(1))) {
38739         ShuffleVectorSDNode::commuteMask(Mask);
38740         std::swap(Ops[0], Ops[1]);
38741         std::swap(BC0, BC1);
38742       }
38743 
38744       // If BC1 can be represented by BC0, then convert to unary shuffle.
38745       if (ContainsOps(BC0, BC1.getOperand(0)) &&
38746           ContainsOps(BC0, BC1.getOperand(1))) {
38747         for (int &M : Mask) {
38748           if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
38749             continue;
38750           int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
38751           M -= NumElts + (SubLane * NumHalfEltsPerLane);
38752           if (BC1.getOperand(SubLane) != BC0.getOperand(0))
38753             M += NumHalfEltsPerLane;
38754         }
38755       }
38756     }
38757 
38758     // Canonicalize unary horizontal ops to only refer to lower halves.
38759     for (int i = 0; i != NumElts; ++i) {
38760       int &M = Mask[i];
38761       if (isUndefOrZero(M))
38762         continue;
38763       if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
38764           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
38765         M -= NumHalfEltsPerLane;
38766       if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
38767           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
38768         M -= NumHalfEltsPerLane;
38769     }
38770   }
38771 
38772   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
38773   // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
38774   // represents the LHS/RHS inputs for the lower/upper halves.
38775   SmallVector<int, 16> TargetMask128, WideMask128;
38776   if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
38777       scaleShuffleElements(TargetMask128, 2, WideMask128)) {
38778     assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle");
38779     bool SingleOp = (Ops.size() == 1);
38780     if (isPack || OneUseOps ||
38781         shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
38782       SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
38783       SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
38784       Lo = Lo.getOperand(WideMask128[0] & 1);
38785       Hi = Hi.getOperand(WideMask128[1] & 1);
38786       if (SingleOp) {
38787         SDValue Undef = DAG.getUNDEF(SrcVT);
38788         SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
38789         Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
38790         Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
38791         Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
38792         Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
38793       }
38794       return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
38795     }
38796   }
38797 
38798   // If we are post-shuffling a 256-bit hop and not requiring the upper
38799   // elements, then try to narrow to a 128-bit hop directly.
38800   SmallVector<int, 16> WideMask64;
38801   if (Ops.size() == 1 && NumLanes == 2 &&
38802       scaleShuffleElements(Mask, 4, WideMask64) &&
38803       isUndefInRange(WideMask64, 2, 2)) {
38804     int M0 = WideMask64[0];
38805     int M1 = WideMask64[1];
38806     if (isInRange(M0, 0, 4) && isInRange(M1, 0, 4)) {
38807       MVT HalfVT = VT0.getSimpleVT().getHalfNumVectorElementsVT();
38808       unsigned Idx0 = (M0 & 2) ? (SrcVT.getVectorNumElements() / 2) : 0;
38809       unsigned Idx1 = (M1 & 2) ? (SrcVT.getVectorNumElements() / 2) : 0;
38810       SDValue V0 = extract128BitVector(BC[0].getOperand(M0 & 1), Idx0, DAG, DL);
38811       SDValue V1 = extract128BitVector(BC[0].getOperand(M1 & 1), Idx1, DAG, DL);
38812       SDValue Res = DAG.getNode(Opcode0, DL, HalfVT, V0, V1);
38813       return widenSubVector(Res, false, Subtarget, DAG, DL, 256);
38814     }
38815   }
38816 
38817   return SDValue();
38818 }
38819 
38820 // Attempt to constant fold all of the constant source ops.
38821 // Returns true if the entire shuffle is folded to a constant.
38822 // TODO: Extend this to merge multiple constant Ops and update the mask.
combineX86ShufflesConstants(ArrayRef<SDValue> Ops,ArrayRef<int> Mask,SDValue Root,bool HasVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)38823 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
38824                                            ArrayRef<int> Mask, SDValue Root,
38825                                            bool HasVariableMask,
38826                                            SelectionDAG &DAG,
38827                                            const X86Subtarget &Subtarget) {
38828   MVT VT = Root.getSimpleValueType();
38829 
38830   unsigned SizeInBits = VT.getSizeInBits();
38831   unsigned NumMaskElts = Mask.size();
38832   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
38833   unsigned NumOps = Ops.size();
38834 
38835   // Extract constant bits from each source op.
38836   SmallVector<APInt, 16> UndefEltsOps(NumOps);
38837   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
38838   for (unsigned I = 0; I != NumOps; ++I)
38839     if (!getTargetConstantBitsFromNode(Ops[I], MaskSizeInBits, UndefEltsOps[I],
38840                                        RawBitsOps[I]))
38841       return SDValue();
38842 
38843   // If we're optimizing for size, only fold if at least one of the constants is
38844   // only used once or the combined shuffle has included a variable mask
38845   // shuffle, this is to avoid constant pool bloat.
38846   bool IsOptimizingSize = DAG.shouldOptForSize();
38847   if (IsOptimizingSize && !HasVariableMask &&
38848       llvm::none_of(Ops, [](SDValue SrcOp) { return SrcOp->hasOneUse(); }))
38849     return SDValue();
38850 
38851   // Shuffle the constant bits according to the mask.
38852   SDLoc DL(Root);
38853   APInt UndefElts(NumMaskElts, 0);
38854   APInt ZeroElts(NumMaskElts, 0);
38855   APInt ConstantElts(NumMaskElts, 0);
38856   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
38857                                         APInt::getZero(MaskSizeInBits));
38858   for (unsigned i = 0; i != NumMaskElts; ++i) {
38859     int M = Mask[i];
38860     if (M == SM_SentinelUndef) {
38861       UndefElts.setBit(i);
38862       continue;
38863     } else if (M == SM_SentinelZero) {
38864       ZeroElts.setBit(i);
38865       continue;
38866     }
38867     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
38868 
38869     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
38870     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
38871 
38872     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
38873     if (SrcUndefElts[SrcMaskIdx]) {
38874       UndefElts.setBit(i);
38875       continue;
38876     }
38877 
38878     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
38879     APInt &Bits = SrcEltBits[SrcMaskIdx];
38880     if (!Bits) {
38881       ZeroElts.setBit(i);
38882       continue;
38883     }
38884 
38885     ConstantElts.setBit(i);
38886     ConstantBitData[i] = Bits;
38887   }
38888   assert((UndefElts | ZeroElts | ConstantElts).isAllOnes());
38889 
38890   // Attempt to create a zero vector.
38891   if ((UndefElts | ZeroElts).isAllOnes())
38892     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
38893 
38894   // Create the constant data.
38895   MVT MaskSVT;
38896   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
38897     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
38898   else
38899     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
38900 
38901   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
38902   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
38903     return SDValue();
38904 
38905   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
38906   return DAG.getBitcast(VT, CstOp);
38907 }
38908 
38909 namespace llvm {
38910   namespace X86 {
38911     enum {
38912       MaxShuffleCombineDepth = 8
38913     };
38914   } // namespace X86
38915 } // namespace llvm
38916 
38917 /// Fully generic combining of x86 shuffle instructions.
38918 ///
38919 /// This should be the last combine run over the x86 shuffle instructions. Once
38920 /// they have been fully optimized, this will recursively consider all chains
38921 /// of single-use shuffle instructions, build a generic model of the cumulative
38922 /// shuffle operation, and check for simpler instructions which implement this
38923 /// operation. We use this primarily for two purposes:
38924 ///
38925 /// 1) Collapse generic shuffles to specialized single instructions when
38926 ///    equivalent. In most cases, this is just an encoding size win, but
38927 ///    sometimes we will collapse multiple generic shuffles into a single
38928 ///    special-purpose shuffle.
38929 /// 2) Look for sequences of shuffle instructions with 3 or more total
38930 ///    instructions, and replace them with the slightly more expensive SSSE3
38931 ///    PSHUFB instruction if available. We do this as the last combining step
38932 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
38933 ///    a suitable short sequence of other instructions. The PSHUFB will either
38934 ///    use a register or have to read from memory and so is slightly (but only
38935 ///    slightly) more expensive than the other shuffle instructions.
38936 ///
38937 /// Because this is inherently a quadratic operation (for each shuffle in
38938 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
38939 /// This should never be an issue in practice as the shuffle lowering doesn't
38940 /// produce sequences of more than 8 instructions.
38941 ///
38942 /// FIXME: We will currently miss some cases where the redundant shuffling
38943 /// would simplify under the threshold for PSHUFB formation because of
38944 /// combine-ordering. To fix this, we should do the redundant instruction
38945 /// combining in this recursive walk.
combineX86ShufflesRecursively(ArrayRef<SDValue> SrcOps,int SrcOpIndex,SDValue Root,ArrayRef<int> RootMask,ArrayRef<const SDNode * > SrcNodes,unsigned Depth,unsigned MaxDepth,bool HasVariableMask,bool AllowVariableCrossLaneMask,bool AllowVariablePerLaneMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)38946 static SDValue combineX86ShufflesRecursively(
38947     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
38948     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
38949     unsigned MaxDepth, bool HasVariableMask, bool AllowVariableCrossLaneMask,
38950     bool AllowVariablePerLaneMask, SelectionDAG &DAG,
38951     const X86Subtarget &Subtarget) {
38952   assert(!RootMask.empty() &&
38953          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
38954          "Illegal shuffle root mask");
38955   MVT RootVT = Root.getSimpleValueType();
38956   assert(RootVT.isVector() && "Shuffles operate on vector types!");
38957   unsigned RootSizeInBits = RootVT.getSizeInBits();
38958 
38959   // Bound the depth of our recursive combine because this is ultimately
38960   // quadratic in nature.
38961   if (Depth >= MaxDepth)
38962     return SDValue();
38963 
38964   // Directly rip through bitcasts to find the underlying operand.
38965   SDValue Op = SrcOps[SrcOpIndex];
38966   Op = peekThroughOneUseBitcasts(Op);
38967 
38968   EVT VT = Op.getValueType();
38969   if (!VT.isVector() || !VT.isSimple())
38970     return SDValue(); // Bail if we hit a non-simple non-vector.
38971 
38972   // FIXME: Just bail on f16 for now.
38973   if (VT.getVectorElementType() == MVT::f16)
38974     return SDValue();
38975 
38976   assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&
38977          "Can only combine shuffles upto size of the root op.");
38978 
38979   // Create a demanded elts mask from the referenced elements of Op.
38980   APInt OpDemandedElts = APInt::getZero(RootMask.size());
38981   for (int M : RootMask) {
38982     int BaseIdx = RootMask.size() * SrcOpIndex;
38983     if (isInRange(M, BaseIdx, BaseIdx + RootMask.size()))
38984       OpDemandedElts.setBit(M - BaseIdx);
38985   }
38986   if (RootSizeInBits != VT.getSizeInBits()) {
38987     // Op is smaller than Root - extract the demanded elts for the subvector.
38988     unsigned Scale = RootSizeInBits / VT.getSizeInBits();
38989     unsigned NumOpMaskElts = RootMask.size() / Scale;
38990     assert((RootMask.size() % Scale) == 0 && "Root mask size mismatch");
38991     assert(OpDemandedElts
38992                .extractBits(RootMask.size() - NumOpMaskElts, NumOpMaskElts)
38993                .isZero() &&
38994            "Out of range elements referenced in root mask");
38995     OpDemandedElts = OpDemandedElts.extractBits(NumOpMaskElts, 0);
38996   }
38997   OpDemandedElts =
38998       APIntOps::ScaleBitMask(OpDemandedElts, VT.getVectorNumElements());
38999 
39000   // Extract target shuffle mask and resolve sentinels and inputs.
39001   SmallVector<int, 64> OpMask;
39002   SmallVector<SDValue, 2> OpInputs;
39003   APInt OpUndef, OpZero;
39004   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
39005   if (getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
39006                              OpZero, DAG, Depth, false)) {
39007     // Shuffle inputs must not be larger than the shuffle result.
39008     // TODO: Relax this for single input faux shuffles (e.g. trunc).
39009     if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
39010           return OpInput.getValueSizeInBits() > VT.getSizeInBits();
39011         }))
39012       return SDValue();
39013   } else if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
39014              (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
39015              !isNullConstant(Op.getOperand(1))) {
39016     SDValue SrcVec = Op.getOperand(0);
39017     int ExtractIdx = Op.getConstantOperandVal(1);
39018     unsigned NumElts = VT.getVectorNumElements();
39019     OpInputs.assign({SrcVec});
39020     OpMask.assign(NumElts, SM_SentinelUndef);
39021     std::iota(OpMask.begin(), OpMask.end(), ExtractIdx);
39022     OpZero = OpUndef = APInt::getZero(NumElts);
39023   } else {
39024     return SDValue();
39025   }
39026 
39027   // If the shuffle result was smaller than the root, we need to adjust the
39028   // mask indices and pad the mask with undefs.
39029   if (RootSizeInBits > VT.getSizeInBits()) {
39030     unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
39031     unsigned OpMaskSize = OpMask.size();
39032     if (OpInputs.size() > 1) {
39033       unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
39034       for (int &M : OpMask) {
39035         if (M < 0)
39036           continue;
39037         int EltIdx = M % OpMaskSize;
39038         int OpIdx = M / OpMaskSize;
39039         M = (PaddedMaskSize * OpIdx) + EltIdx;
39040       }
39041     }
39042     OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
39043     OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
39044     OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
39045   }
39046 
39047   SmallVector<int, 64> Mask;
39048   SmallVector<SDValue, 16> Ops;
39049 
39050   // We don't need to merge masks if the root is empty.
39051   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
39052   if (EmptyRoot) {
39053     // Only resolve zeros if it will remove an input, otherwise we might end
39054     // up in an infinite loop.
39055     bool ResolveKnownZeros = true;
39056     if (!OpZero.isZero()) {
39057       APInt UsedInputs = APInt::getZero(OpInputs.size());
39058       for (int i = 0, e = OpMask.size(); i != e; ++i) {
39059         int M = OpMask[i];
39060         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
39061           continue;
39062         UsedInputs.setBit(M / OpMask.size());
39063         if (UsedInputs.isAllOnes()) {
39064           ResolveKnownZeros = false;
39065           break;
39066         }
39067       }
39068     }
39069     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
39070                                       ResolveKnownZeros);
39071 
39072     Mask = OpMask;
39073     Ops.append(OpInputs.begin(), OpInputs.end());
39074   } else {
39075     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
39076 
39077     // Add the inputs to the Ops list, avoiding duplicates.
39078     Ops.append(SrcOps.begin(), SrcOps.end());
39079 
39080     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
39081       // Attempt to find an existing match.
39082       SDValue InputBC = peekThroughBitcasts(Input);
39083       for (int i = 0, e = Ops.size(); i < e; ++i)
39084         if (InputBC == peekThroughBitcasts(Ops[i]))
39085           return i;
39086       // Match failed - should we replace an existing Op?
39087       if (InsertionPoint >= 0) {
39088         Ops[InsertionPoint] = Input;
39089         return InsertionPoint;
39090       }
39091       // Add to the end of the Ops list.
39092       Ops.push_back(Input);
39093       return Ops.size() - 1;
39094     };
39095 
39096     SmallVector<int, 2> OpInputIdx;
39097     for (SDValue OpInput : OpInputs)
39098       OpInputIdx.push_back(
39099           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
39100 
39101     assert(((RootMask.size() > OpMask.size() &&
39102              RootMask.size() % OpMask.size() == 0) ||
39103             (OpMask.size() > RootMask.size() &&
39104              OpMask.size() % RootMask.size() == 0) ||
39105             OpMask.size() == RootMask.size()) &&
39106            "The smaller number of elements must divide the larger.");
39107 
39108     // This function can be performance-critical, so we rely on the power-of-2
39109     // knowledge that we have about the mask sizes to replace div/rem ops with
39110     // bit-masks and shifts.
39111     assert(llvm::has_single_bit<uint32_t>(RootMask.size()) &&
39112            "Non-power-of-2 shuffle mask sizes");
39113     assert(llvm::has_single_bit<uint32_t>(OpMask.size()) &&
39114            "Non-power-of-2 shuffle mask sizes");
39115     unsigned RootMaskSizeLog2 = llvm::countr_zero(RootMask.size());
39116     unsigned OpMaskSizeLog2 = llvm::countr_zero(OpMask.size());
39117 
39118     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
39119     unsigned RootRatio =
39120         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
39121     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
39122     assert((RootRatio == 1 || OpRatio == 1) &&
39123            "Must not have a ratio for both incoming and op masks!");
39124 
39125     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
39126     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
39127     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
39128     unsigned RootRatioLog2 = llvm::countr_zero(RootRatio);
39129     unsigned OpRatioLog2 = llvm::countr_zero(OpRatio);
39130 
39131     Mask.resize(MaskWidth, SM_SentinelUndef);
39132 
39133     // Merge this shuffle operation's mask into our accumulated mask. Note that
39134     // this shuffle's mask will be the first applied to the input, followed by
39135     // the root mask to get us all the way to the root value arrangement. The
39136     // reason for this order is that we are recursing up the operation chain.
39137     for (unsigned i = 0; i < MaskWidth; ++i) {
39138       unsigned RootIdx = i >> RootRatioLog2;
39139       if (RootMask[RootIdx] < 0) {
39140         // This is a zero or undef lane, we're done.
39141         Mask[i] = RootMask[RootIdx];
39142         continue;
39143       }
39144 
39145       unsigned RootMaskedIdx =
39146           RootRatio == 1
39147               ? RootMask[RootIdx]
39148               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
39149 
39150       // Just insert the scaled root mask value if it references an input other
39151       // than the SrcOp we're currently inserting.
39152       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
39153           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
39154         Mask[i] = RootMaskedIdx;
39155         continue;
39156       }
39157 
39158       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
39159       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
39160       if (OpMask[OpIdx] < 0) {
39161         // The incoming lanes are zero or undef, it doesn't matter which ones we
39162         // are using.
39163         Mask[i] = OpMask[OpIdx];
39164         continue;
39165       }
39166 
39167       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
39168       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
39169                                           : (OpMask[OpIdx] << OpRatioLog2) +
39170                                                 (RootMaskedIdx & (OpRatio - 1));
39171 
39172       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
39173       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
39174       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
39175       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
39176 
39177       Mask[i] = OpMaskedIdx;
39178     }
39179   }
39180 
39181   // Peek through vector widenings and set out of bounds mask indices to undef.
39182   // TODO: Can resolveTargetShuffleInputsAndMask do some of this?
39183   for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
39184     SDValue &Op = Ops[I];
39185     if (Op.getOpcode() == ISD::INSERT_SUBVECTOR && Op.getOperand(0).isUndef() &&
39186         isNullConstant(Op.getOperand(2))) {
39187       Op = Op.getOperand(1);
39188       unsigned Scale = RootSizeInBits / Op.getValueSizeInBits();
39189       int Lo = I * Mask.size();
39190       int Hi = (I + 1) * Mask.size();
39191       int NewHi = Lo + (Mask.size() / Scale);
39192       for (int &M : Mask) {
39193         if (Lo <= M && NewHi <= M && M < Hi)
39194           M = SM_SentinelUndef;
39195       }
39196     }
39197   }
39198 
39199   // Peek through any free extract_subvector nodes back to root size.
39200   for (SDValue &Op : Ops)
39201     while (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
39202            (RootSizeInBits % Op.getOperand(0).getValueSizeInBits()) == 0 &&
39203            isNullConstant(Op.getOperand(1)))
39204       Op = Op.getOperand(0);
39205 
39206   // Remove unused/repeated shuffle source ops.
39207   resolveTargetShuffleInputsAndMask(Ops, Mask);
39208 
39209   // Handle the all undef/zero/ones cases early.
39210   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
39211     return DAG.getUNDEF(RootVT);
39212   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
39213     return getZeroVector(RootVT, Subtarget, DAG, SDLoc(Root));
39214   if (Ops.size() == 1 && ISD::isBuildVectorAllOnes(Ops[0].getNode()) &&
39215       !llvm::is_contained(Mask, SM_SentinelZero))
39216     return getOnesVector(RootVT, DAG, SDLoc(Root));
39217 
39218   assert(!Ops.empty() && "Shuffle with no inputs detected");
39219   HasVariableMask |= IsOpVariableMask;
39220 
39221   // Update the list of shuffle nodes that have been combined so far.
39222   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
39223                                                 SrcNodes.end());
39224   CombinedNodes.push_back(Op.getNode());
39225 
39226   // See if we can recurse into each shuffle source op (if it's a target
39227   // shuffle). The source op should only be generally combined if it either has
39228   // a single use (i.e. current Op) or all its users have already been combined,
39229   // if not then we can still combine but should prevent generation of variable
39230   // shuffles to avoid constant pool bloat.
39231   // Don't recurse if we already have more source ops than we can combine in
39232   // the remaining recursion depth.
39233   if (Ops.size() < (MaxDepth - Depth)) {
39234     for (int i = 0, e = Ops.size(); i < e; ++i) {
39235       // For empty roots, we need to resolve zeroable elements before combining
39236       // them with other shuffles.
39237       SmallVector<int, 64> ResolvedMask = Mask;
39238       if (EmptyRoot)
39239         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
39240       bool AllowCrossLaneVar = false;
39241       bool AllowPerLaneVar = false;
39242       if (Ops[i].getNode()->hasOneUse() ||
39243           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode())) {
39244         AllowCrossLaneVar = AllowVariableCrossLaneMask;
39245         AllowPerLaneVar = AllowVariablePerLaneMask;
39246       }
39247       if (SDValue Res = combineX86ShufflesRecursively(
39248               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
39249               HasVariableMask, AllowCrossLaneVar, AllowPerLaneVar, DAG,
39250               Subtarget))
39251         return Res;
39252     }
39253   }
39254 
39255   // Attempt to constant fold all of the constant source ops.
39256   if (SDValue Cst = combineX86ShufflesConstants(
39257           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
39258     return Cst;
39259 
39260   // If constant fold failed and we only have constants - then we have
39261   // multiple uses by a single non-variable shuffle - just bail.
39262   if (Depth == 0 && llvm::all_of(Ops, [&](SDValue Op) {
39263         APInt UndefElts;
39264         SmallVector<APInt> RawBits;
39265         unsigned EltSizeInBits = RootSizeInBits / Mask.size();
39266         return getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
39267                                              RawBits);
39268       })) {
39269     return SDValue();
39270   }
39271 
39272   // Canonicalize the combined shuffle mask chain with horizontal ops.
39273   // NOTE: This will update the Ops and Mask.
39274   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
39275           Ops, Mask, RootSizeInBits, SDLoc(Root), DAG, Subtarget))
39276     return DAG.getBitcast(RootVT, HOp);
39277 
39278   // Try to refine our inputs given our knowledge of target shuffle mask.
39279   for (auto I : enumerate(Ops)) {
39280     int OpIdx = I.index();
39281     SDValue &Op = I.value();
39282 
39283     // What range of shuffle mask element values results in picking from Op?
39284     int Lo = OpIdx * Mask.size();
39285     int Hi = Lo + Mask.size();
39286 
39287     // Which elements of Op do we demand, given the mask's granularity?
39288     APInt OpDemandedElts(Mask.size(), 0);
39289     for (int MaskElt : Mask) {
39290       if (isInRange(MaskElt, Lo, Hi)) { // Picks from Op?
39291         int OpEltIdx = MaskElt - Lo;
39292         OpDemandedElts.setBit(OpEltIdx);
39293       }
39294     }
39295 
39296     // Is the shuffle result smaller than the root?
39297     if (Op.getValueSizeInBits() < RootSizeInBits) {
39298       // We padded the mask with undefs. But we now need to undo that.
39299       unsigned NumExpectedVectorElts = Mask.size();
39300       unsigned EltSizeInBits = RootSizeInBits / NumExpectedVectorElts;
39301       unsigned NumOpVectorElts = Op.getValueSizeInBits() / EltSizeInBits;
39302       assert(!OpDemandedElts.extractBits(
39303                  NumExpectedVectorElts - NumOpVectorElts, NumOpVectorElts) &&
39304              "Demanding the virtual undef widening padding?");
39305       OpDemandedElts = OpDemandedElts.trunc(NumOpVectorElts); // NUW
39306     }
39307 
39308     // The Op itself may be of different VT, so we need to scale the mask.
39309     unsigned NumOpElts = Op.getValueType().getVectorNumElements();
39310     APInt OpScaledDemandedElts = APIntOps::ScaleBitMask(OpDemandedElts, NumOpElts);
39311 
39312     // Can this operand be simplified any further, given it's demanded elements?
39313     if (SDValue NewOp =
39314             DAG.getTargetLoweringInfo().SimplifyMultipleUseDemandedVectorElts(
39315                 Op, OpScaledDemandedElts, DAG))
39316       Op = NewOp;
39317   }
39318   // FIXME: should we rerun resolveTargetShuffleInputsAndMask() now?
39319 
39320   // Widen any subvector shuffle inputs we've collected.
39321   // TODO: Remove this to avoid generating temporary nodes, we should only
39322   // widen once combineX86ShuffleChain has found a match.
39323   if (any_of(Ops, [RootSizeInBits](SDValue Op) {
39324         return Op.getValueSizeInBits() < RootSizeInBits;
39325       })) {
39326     for (SDValue &Op : Ops)
39327       if (Op.getValueSizeInBits() < RootSizeInBits)
39328         Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
39329                             RootSizeInBits);
39330     // Reresolve - we might have repeated subvector sources.
39331     resolveTargetShuffleInputsAndMask(Ops, Mask);
39332   }
39333 
39334   // We can only combine unary and binary shuffle mask cases.
39335   if (Ops.size() <= 2) {
39336     // Minor canonicalization of the accumulated shuffle mask to make it easier
39337     // to match below. All this does is detect masks with sequential pairs of
39338     // elements, and shrink them to the half-width mask. It does this in a loop
39339     // so it will reduce the size of the mask to the minimal width mask which
39340     // performs an equivalent shuffle.
39341     while (Mask.size() > 1) {
39342       SmallVector<int, 64> WidenedMask;
39343       if (!canWidenShuffleElements(Mask, WidenedMask))
39344         break;
39345       Mask = std::move(WidenedMask);
39346     }
39347 
39348     // Canonicalization of binary shuffle masks to improve pattern matching by
39349     // commuting the inputs.
39350     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
39351       ShuffleVectorSDNode::commuteMask(Mask);
39352       std::swap(Ops[0], Ops[1]);
39353     }
39354 
39355     // Try to combine into a single shuffle instruction.
39356     if (SDValue Shuffle = combineX86ShuffleChain(
39357             Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
39358             AllowVariablePerLaneMask, DAG, Subtarget))
39359       return Shuffle;
39360 
39361     // If all the operands come from the same larger vector, fallthrough and try
39362     // to use combineX86ShuffleChainWithExtract.
39363     SDValue LHS = peekThroughBitcasts(Ops.front());
39364     SDValue RHS = peekThroughBitcasts(Ops.back());
39365     if (Ops.size() != 2 || !Subtarget.hasAVX2() || RootSizeInBits != 128 ||
39366         (RootSizeInBits / Mask.size()) != 64 ||
39367         LHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
39368         RHS.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
39369         LHS.getOperand(0) != RHS.getOperand(0))
39370       return SDValue();
39371   }
39372 
39373   // If that failed and any input is extracted then try to combine as a
39374   // shuffle with the larger type.
39375   return combineX86ShuffleChainWithExtract(
39376       Ops, Root, Mask, Depth, HasVariableMask, AllowVariableCrossLaneMask,
39377       AllowVariablePerLaneMask, DAG, Subtarget);
39378 }
39379 
39380 /// Helper entry wrapper to combineX86ShufflesRecursively.
combineX86ShufflesRecursively(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)39381 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
39382                                              const X86Subtarget &Subtarget) {
39383   return combineX86ShufflesRecursively(
39384       {Op}, 0, Op, {0}, {}, /*Depth*/ 0, X86::MaxShuffleCombineDepth,
39385       /*HasVarMask*/ false,
39386       /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, DAG,
39387       Subtarget);
39388 }
39389 
39390 /// Get the PSHUF-style mask from PSHUF node.
39391 ///
39392 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
39393 /// PSHUF-style masks that can be reused with such instructions.
getPSHUFShuffleMask(SDValue N)39394 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
39395   MVT VT = N.getSimpleValueType();
39396   SmallVector<int, 4> Mask;
39397   SmallVector<SDValue, 2> Ops;
39398   bool HaveMask =
39399       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask);
39400   (void)HaveMask;
39401   assert(HaveMask);
39402 
39403   // If we have more than 128-bits, only the low 128-bits of shuffle mask
39404   // matter. Check that the upper masks are repeats and remove them.
39405   if (VT.getSizeInBits() > 128) {
39406     int LaneElts = 128 / VT.getScalarSizeInBits();
39407 #ifndef NDEBUG
39408     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
39409       for (int j = 0; j < LaneElts; ++j)
39410         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
39411                "Mask doesn't repeat in high 128-bit lanes!");
39412 #endif
39413     Mask.resize(LaneElts);
39414   }
39415 
39416   switch (N.getOpcode()) {
39417   case X86ISD::PSHUFD:
39418     return Mask;
39419   case X86ISD::PSHUFLW:
39420     Mask.resize(4);
39421     return Mask;
39422   case X86ISD::PSHUFHW:
39423     Mask.erase(Mask.begin(), Mask.begin() + 4);
39424     for (int &M : Mask)
39425       M -= 4;
39426     return Mask;
39427   default:
39428     llvm_unreachable("No valid shuffle instruction found!");
39429   }
39430 }
39431 
39432 /// Search for a combinable shuffle across a chain ending in pshufd.
39433 ///
39434 /// We walk up the chain and look for a combinable shuffle, skipping over
39435 /// shuffles that we could hoist this shuffle's transformation past without
39436 /// altering anything.
39437 static SDValue
combineRedundantDWordShuffle(SDValue N,MutableArrayRef<int> Mask,SelectionDAG & DAG)39438 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
39439                              SelectionDAG &DAG) {
39440   assert(N.getOpcode() == X86ISD::PSHUFD &&
39441          "Called with something other than an x86 128-bit half shuffle!");
39442   SDLoc DL(N);
39443 
39444   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
39445   // of the shuffles in the chain so that we can form a fresh chain to replace
39446   // this one.
39447   SmallVector<SDValue, 8> Chain;
39448   SDValue V = N.getOperand(0);
39449   for (; V.hasOneUse(); V = V.getOperand(0)) {
39450     switch (V.getOpcode()) {
39451     default:
39452       return SDValue(); // Nothing combined!
39453 
39454     case ISD::BITCAST:
39455       // Skip bitcasts as we always know the type for the target specific
39456       // instructions.
39457       continue;
39458 
39459     case X86ISD::PSHUFD:
39460       // Found another dword shuffle.
39461       break;
39462 
39463     case X86ISD::PSHUFLW:
39464       // Check that the low words (being shuffled) are the identity in the
39465       // dword shuffle, and the high words are self-contained.
39466       if (Mask[0] != 0 || Mask[1] != 1 ||
39467           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
39468         return SDValue();
39469 
39470       Chain.push_back(V);
39471       continue;
39472 
39473     case X86ISD::PSHUFHW:
39474       // Check that the high words (being shuffled) are the identity in the
39475       // dword shuffle, and the low words are self-contained.
39476       if (Mask[2] != 2 || Mask[3] != 3 ||
39477           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
39478         return SDValue();
39479 
39480       Chain.push_back(V);
39481       continue;
39482 
39483     case X86ISD::UNPCKL:
39484     case X86ISD::UNPCKH:
39485       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
39486       // shuffle into a preceding word shuffle.
39487       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
39488           V.getSimpleValueType().getVectorElementType() != MVT::i16)
39489         return SDValue();
39490 
39491       // Search for a half-shuffle which we can combine with.
39492       unsigned CombineOp =
39493           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
39494       if (V.getOperand(0) != V.getOperand(1) ||
39495           !V->isOnlyUserOf(V.getOperand(0).getNode()))
39496         return SDValue();
39497       Chain.push_back(V);
39498       V = V.getOperand(0);
39499       do {
39500         switch (V.getOpcode()) {
39501         default:
39502           return SDValue(); // Nothing to combine.
39503 
39504         case X86ISD::PSHUFLW:
39505         case X86ISD::PSHUFHW:
39506           if (V.getOpcode() == CombineOp)
39507             break;
39508 
39509           Chain.push_back(V);
39510 
39511           [[fallthrough]];
39512         case ISD::BITCAST:
39513           V = V.getOperand(0);
39514           continue;
39515         }
39516         break;
39517       } while (V.hasOneUse());
39518       break;
39519     }
39520     // Break out of the loop if we break out of the switch.
39521     break;
39522   }
39523 
39524   if (!V.hasOneUse())
39525     // We fell out of the loop without finding a viable combining instruction.
39526     return SDValue();
39527 
39528   // Merge this node's mask and our incoming mask.
39529   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
39530   for (int &M : Mask)
39531     M = VMask[M];
39532   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
39533                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
39534 
39535   // Rebuild the chain around this new shuffle.
39536   while (!Chain.empty()) {
39537     SDValue W = Chain.pop_back_val();
39538 
39539     if (V.getValueType() != W.getOperand(0).getValueType())
39540       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
39541 
39542     switch (W.getOpcode()) {
39543     default:
39544       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
39545 
39546     case X86ISD::UNPCKL:
39547     case X86ISD::UNPCKH:
39548       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
39549       break;
39550 
39551     case X86ISD::PSHUFD:
39552     case X86ISD::PSHUFLW:
39553     case X86ISD::PSHUFHW:
39554       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
39555       break;
39556     }
39557   }
39558   if (V.getValueType() != N.getValueType())
39559     V = DAG.getBitcast(N.getValueType(), V);
39560 
39561   // Return the new chain to replace N.
39562   return V;
39563 }
39564 
39565 // Attempt to commute shufps LHS loads:
39566 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
combineCommutableSHUFP(SDValue N,MVT VT,const SDLoc & DL,SelectionDAG & DAG)39567 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
39568                                       SelectionDAG &DAG) {
39569   // TODO: Add vXf64 support.
39570   if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
39571     return SDValue();
39572 
39573   // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
39574   auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
39575     if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
39576       return SDValue();
39577     SDValue N0 = V.getOperand(0);
39578     SDValue N1 = V.getOperand(1);
39579     unsigned Imm = V.getConstantOperandVal(2);
39580     const X86Subtarget &Subtarget = DAG.getSubtarget<X86Subtarget>();
39581     if (!X86::mayFoldLoad(peekThroughOneUseBitcasts(N0), Subtarget) ||
39582         X86::mayFoldLoad(peekThroughOneUseBitcasts(N1), Subtarget))
39583       return SDValue();
39584     Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
39585     return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
39586                        DAG.getTargetConstant(Imm, DL, MVT::i8));
39587   };
39588 
39589   switch (N.getOpcode()) {
39590   case X86ISD::VPERMILPI:
39591     if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
39592       unsigned Imm = N.getConstantOperandVal(1);
39593       return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
39594                          DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
39595     }
39596     break;
39597   case X86ISD::SHUFP: {
39598     SDValue N0 = N.getOperand(0);
39599     SDValue N1 = N.getOperand(1);
39600     unsigned Imm = N.getConstantOperandVal(2);
39601     if (N0 == N1) {
39602       if (SDValue NewSHUFP = commuteSHUFP(N, N0))
39603         return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
39604                            DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
39605     } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
39606       return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
39607                          DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
39608     } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
39609       return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
39610                          DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
39611     }
39612     break;
39613   }
39614   }
39615 
39616   return SDValue();
39617 }
39618 
39619 // TODO - move this to TLI like isBinOp?
isUnaryOp(unsigned Opcode)39620 static bool isUnaryOp(unsigned Opcode) {
39621   switch (Opcode) {
39622   case ISD::CTLZ:
39623   case ISD::CTTZ:
39624   case ISD::CTPOP:
39625     return true;
39626   }
39627   return false;
39628 }
39629 
39630 // Canonicalize SHUFFLE(UNARYOP(X)) -> UNARYOP(SHUFFLE(X)).
39631 // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
canonicalizeShuffleWithOp(SDValue N,SelectionDAG & DAG,const SDLoc & DL)39632 static SDValue canonicalizeShuffleWithOp(SDValue N, SelectionDAG &DAG,
39633                                          const SDLoc &DL) {
39634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39635   EVT ShuffleVT = N.getValueType();
39636 
39637   auto IsMergeableWithShuffle = [&DAG](SDValue Op, bool FoldLoad = false) {
39638     // AllZeros/AllOnes constants are freely shuffled and will peek through
39639     // bitcasts. Other constant build vectors do not peek through bitcasts. Only
39640     // merge with target shuffles if it has one use so shuffle combining is
39641     // likely to kick in. Shuffles of splats are expected to be removed.
39642     return ISD::isBuildVectorAllOnes(Op.getNode()) ||
39643            ISD::isBuildVectorAllZeros(Op.getNode()) ||
39644            ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
39645            ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()) ||
39646            getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op)) ||
39647            (Op.getOpcode() == ISD::INSERT_SUBVECTOR && Op->hasOneUse()) ||
39648            (isTargetShuffle(Op.getOpcode()) && Op->hasOneUse()) ||
39649            (FoldLoad && isShuffleFoldableLoad(Op)) ||
39650            DAG.isSplatValue(Op, /*AllowUndefs*/ false);
39651   };
39652   auto IsSafeToMoveShuffle = [ShuffleVT](SDValue Op, unsigned BinOp) {
39653     // Ensure we only shuffle whole vector src elements, unless its a logical
39654     // binops where we can more aggressively move shuffles from dst to src.
39655     return BinOp == ISD::AND || BinOp == ISD::OR || BinOp == ISD::XOR ||
39656            BinOp == X86ISD::ANDNP ||
39657            (Op.getScalarValueSizeInBits() <= ShuffleVT.getScalarSizeInBits());
39658   };
39659 
39660   unsigned Opc = N.getOpcode();
39661   switch (Opc) {
39662   // Unary and Unary+Permute Shuffles.
39663   case X86ISD::PSHUFB: {
39664     // Don't merge PSHUFB if it contains zero'd elements.
39665     SmallVector<int> Mask;
39666     SmallVector<SDValue> Ops;
39667     if (!getTargetShuffleMask(N.getNode(), ShuffleVT.getSimpleVT(), false, Ops,
39668                               Mask))
39669       break;
39670     [[fallthrough]];
39671   }
39672   case X86ISD::VBROADCAST:
39673   case X86ISD::MOVDDUP:
39674   case X86ISD::PSHUFD:
39675   case X86ISD::PSHUFHW:
39676   case X86ISD::PSHUFLW:
39677   case X86ISD::VPERMI:
39678   case X86ISD::VPERMILPI: {
39679     if (N.getOperand(0).getValueType() == ShuffleVT &&
39680         N->isOnlyUserOf(N.getOperand(0).getNode())) {
39681       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
39682       unsigned SrcOpcode = N0.getOpcode();
39683       if (TLI.isBinOp(SrcOpcode) && IsSafeToMoveShuffle(N0, SrcOpcode)) {
39684         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
39685         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
39686         if (IsMergeableWithShuffle(Op00, Opc != X86ISD::PSHUFB) ||
39687             IsMergeableWithShuffle(Op01, Opc != X86ISD::PSHUFB)) {
39688           SDValue LHS, RHS;
39689           Op00 = DAG.getBitcast(ShuffleVT, Op00);
39690           Op01 = DAG.getBitcast(ShuffleVT, Op01);
39691           if (N.getNumOperands() == 2) {
39692             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, N.getOperand(1));
39693             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, N.getOperand(1));
39694           } else {
39695             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00);
39696             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01);
39697           }
39698           EVT OpVT = N0.getValueType();
39699           return DAG.getBitcast(ShuffleVT,
39700                                 DAG.getNode(SrcOpcode, DL, OpVT,
39701                                             DAG.getBitcast(OpVT, LHS),
39702                                             DAG.getBitcast(OpVT, RHS)));
39703         }
39704       }
39705     }
39706     break;
39707   }
39708   // Binary and Binary+Permute Shuffles.
39709   case X86ISD::INSERTPS: {
39710     // Don't merge INSERTPS if it contains zero'd elements.
39711     unsigned InsertPSMask = N.getConstantOperandVal(2);
39712     unsigned ZeroMask = InsertPSMask & 0xF;
39713     if (ZeroMask != 0)
39714       break;
39715     [[fallthrough]];
39716   }
39717   case X86ISD::MOVSD:
39718   case X86ISD::MOVSS:
39719   case X86ISD::BLENDI:
39720   case X86ISD::SHUFP:
39721   case X86ISD::UNPCKH:
39722   case X86ISD::UNPCKL: {
39723     if (N->isOnlyUserOf(N.getOperand(0).getNode()) &&
39724         N->isOnlyUserOf(N.getOperand(1).getNode())) {
39725       SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
39726       SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
39727       unsigned SrcOpcode = N0.getOpcode();
39728       if (TLI.isBinOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
39729           N0.getValueType() == N1.getValueType() &&
39730           IsSafeToMoveShuffle(N0, SrcOpcode) &&
39731           IsSafeToMoveShuffle(N1, SrcOpcode)) {
39732         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
39733         SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
39734         SDValue Op01 = peekThroughOneUseBitcasts(N0.getOperand(1));
39735         SDValue Op11 = peekThroughOneUseBitcasts(N1.getOperand(1));
39736         // Ensure the total number of shuffles doesn't increase by folding this
39737         // shuffle through to the source ops.
39738         if (((IsMergeableWithShuffle(Op00) && IsMergeableWithShuffle(Op10)) ||
39739              (IsMergeableWithShuffle(Op01) && IsMergeableWithShuffle(Op11))) ||
39740             ((IsMergeableWithShuffle(Op00) || IsMergeableWithShuffle(Op10)) &&
39741              (IsMergeableWithShuffle(Op01) || IsMergeableWithShuffle(Op11)))) {
39742           SDValue LHS, RHS;
39743           Op00 = DAG.getBitcast(ShuffleVT, Op00);
39744           Op10 = DAG.getBitcast(ShuffleVT, Op10);
39745           Op01 = DAG.getBitcast(ShuffleVT, Op01);
39746           Op11 = DAG.getBitcast(ShuffleVT, Op11);
39747           if (N.getNumOperands() == 3) {
39748             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
39749             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11, N.getOperand(2));
39750           } else {
39751             LHS = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
39752             RHS = DAG.getNode(Opc, DL, ShuffleVT, Op01, Op11);
39753           }
39754           EVT OpVT = N0.getValueType();
39755           return DAG.getBitcast(ShuffleVT,
39756                                 DAG.getNode(SrcOpcode, DL, OpVT,
39757                                             DAG.getBitcast(OpVT, LHS),
39758                                             DAG.getBitcast(OpVT, RHS)));
39759         }
39760       }
39761       if (isUnaryOp(SrcOpcode) && N1.getOpcode() == SrcOpcode &&
39762           N0.getValueType() == N1.getValueType() &&
39763           IsSafeToMoveShuffle(N0, SrcOpcode) &&
39764           IsSafeToMoveShuffle(N1, SrcOpcode)) {
39765         SDValue Op00 = peekThroughOneUseBitcasts(N0.getOperand(0));
39766         SDValue Op10 = peekThroughOneUseBitcasts(N1.getOperand(0));
39767         SDValue Res;
39768         Op00 = DAG.getBitcast(ShuffleVT, Op00);
39769         Op10 = DAG.getBitcast(ShuffleVT, Op10);
39770         if (N.getNumOperands() == 3) {
39771           Res = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10, N.getOperand(2));
39772         } else {
39773           Res = DAG.getNode(Opc, DL, ShuffleVT, Op00, Op10);
39774         }
39775         EVT OpVT = N0.getValueType();
39776         return DAG.getBitcast(
39777             ShuffleVT,
39778             DAG.getNode(SrcOpcode, DL, OpVT, DAG.getBitcast(OpVT, Res)));
39779       }
39780     }
39781     break;
39782   }
39783   }
39784   return SDValue();
39785 }
39786 
39787 /// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
canonicalizeLaneShuffleWithRepeatedOps(SDValue V,SelectionDAG & DAG,const SDLoc & DL)39788 static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
39789                                                       SelectionDAG &DAG,
39790                                                       const SDLoc &DL) {
39791   assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle");
39792 
39793   MVT VT = V.getSimpleValueType();
39794   SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
39795   SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
39796   unsigned SrcOpc0 = Src0.getOpcode();
39797   unsigned SrcOpc1 = Src1.getOpcode();
39798   EVT SrcVT0 = Src0.getValueType();
39799   EVT SrcVT1 = Src1.getValueType();
39800 
39801   if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
39802     return SDValue();
39803 
39804   switch (SrcOpc0) {
39805   case X86ISD::MOVDDUP: {
39806     SDValue LHS = Src0.getOperand(0);
39807     SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
39808     SDValue Res =
39809         DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS, V.getOperand(2));
39810     Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res);
39811     return DAG.getBitcast(VT, Res);
39812   }
39813   case X86ISD::VPERMILPI:
39814     // TODO: Handle v4f64 permutes with different low/high lane masks.
39815     if (SrcVT0 == MVT::v4f64) {
39816       uint64_t Mask = Src0.getConstantOperandVal(1);
39817       if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
39818         break;
39819     }
39820     [[fallthrough]];
39821   case X86ISD::VSHLI:
39822   case X86ISD::VSRLI:
39823   case X86ISD::VSRAI:
39824   case X86ISD::PSHUFD:
39825     if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
39826       SDValue LHS = Src0.getOperand(0);
39827       SDValue RHS = Src1.isUndef() ? Src1 : Src1.getOperand(0);
39828       SDValue Res = DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT0, LHS, RHS,
39829                                 V.getOperand(2));
39830       Res = DAG.getNode(SrcOpc0, DL, SrcVT0, Res, Src0.getOperand(1));
39831       return DAG.getBitcast(VT, Res);
39832     }
39833     break;
39834   }
39835 
39836   return SDValue();
39837 }
39838 
39839 /// Try to combine x86 target specific shuffles.
combineTargetShuffle(SDValue N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39840 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
39841                                     TargetLowering::DAGCombinerInfo &DCI,
39842                                     const X86Subtarget &Subtarget) {
39843   SDLoc DL(N);
39844   MVT VT = N.getSimpleValueType();
39845   SmallVector<int, 4> Mask;
39846   unsigned Opcode = N.getOpcode();
39847 
39848   if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
39849     return R;
39850 
39851   // Handle specific target shuffles.
39852   switch (Opcode) {
39853   case X86ISD::MOVDDUP: {
39854     SDValue Src = N.getOperand(0);
39855     // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
39856     if (VT == MVT::v2f64 && Src.hasOneUse() &&
39857         ISD::isNormalLoad(Src.getNode())) {
39858       LoadSDNode *LN = cast<LoadSDNode>(Src);
39859       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
39860         SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
39861         DCI.CombineTo(N.getNode(), Movddup);
39862         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
39863         DCI.recursivelyDeleteUnusedNodes(LN);
39864         return N; // Return N so it doesn't get rechecked!
39865       }
39866     }
39867 
39868     return SDValue();
39869   }
39870   case X86ISD::VBROADCAST: {
39871     SDValue Src = N.getOperand(0);
39872     SDValue BC = peekThroughBitcasts(Src);
39873     EVT SrcVT = Src.getValueType();
39874     EVT BCVT = BC.getValueType();
39875 
39876     // If broadcasting from another shuffle, attempt to simplify it.
39877     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
39878     if (isTargetShuffle(BC.getOpcode()) &&
39879         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
39880       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
39881       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
39882                                         SM_SentinelUndef);
39883       for (unsigned i = 0; i != Scale; ++i)
39884         DemandedMask[i] = i;
39885       if (SDValue Res = combineX86ShufflesRecursively(
39886               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
39887               X86::MaxShuffleCombineDepth,
39888               /*HasVarMask*/ false, /*AllowCrossLaneVarMask*/ true,
39889               /*AllowPerLaneVarMask*/ true, DAG, Subtarget))
39890         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
39891                            DAG.getBitcast(SrcVT, Res));
39892     }
39893 
39894     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
39895     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
39896     if (Src.getOpcode() == ISD::BITCAST &&
39897         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
39898         DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
39899         FixedVectorType::isValidElementType(
39900             BCVT.getScalarType().getTypeForEVT(*DAG.getContext()))) {
39901       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
39902                                    VT.getVectorNumElements());
39903       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
39904     }
39905 
39906     // vbroadcast(bitcast(vbroadcast(src))) -> bitcast(vbroadcast(src))
39907     // If we're re-broadcasting a smaller type then broadcast with that type and
39908     // bitcast.
39909     // TODO: Do this for any splat?
39910     if (Src.getOpcode() == ISD::BITCAST &&
39911         (BC.getOpcode() == X86ISD::VBROADCAST ||
39912          BC.getOpcode() == X86ISD::VBROADCAST_LOAD) &&
39913         (VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits()) == 0 &&
39914         (VT.getSizeInBits() % BCVT.getSizeInBits()) == 0) {
39915       MVT NewVT =
39916           MVT::getVectorVT(BCVT.getSimpleVT().getScalarType(),
39917                            VT.getSizeInBits() / BCVT.getScalarSizeInBits());
39918       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
39919     }
39920 
39921     // Reduce broadcast source vector to lowest 128-bits.
39922     if (SrcVT.getSizeInBits() > 128)
39923       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
39924                          extract128BitVector(Src, 0, DAG, DL));
39925 
39926     // broadcast(scalar_to_vector(x)) -> broadcast(x).
39927     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
39928         Src.getValueType().getScalarType() == Src.getOperand(0).getValueType())
39929       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
39930 
39931     // broadcast(extract_vector_elt(x, 0)) -> broadcast(x).
39932     if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
39933         isNullConstant(Src.getOperand(1)) &&
39934         Src.getValueType() ==
39935             Src.getOperand(0).getValueType().getScalarType() &&
39936         DAG.getTargetLoweringInfo().isTypeLegal(
39937             Src.getOperand(0).getValueType()))
39938       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
39939 
39940     // Share broadcast with the longest vector and extract low subvector (free).
39941     // Ensure the same SDValue from the SDNode use is being used.
39942     for (SDNode *User : Src->uses())
39943       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
39944           Src == User->getOperand(0) &&
39945           User->getValueSizeInBits(0).getFixedValue() >
39946               VT.getFixedSizeInBits()) {
39947         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
39948                                 VT.getSizeInBits());
39949       }
39950 
39951     // vbroadcast(scalarload X) -> vbroadcast_load X
39952     // For float loads, extract other uses of the scalar from the broadcast.
39953     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
39954         ISD::isNormalLoad(Src.getNode())) {
39955       LoadSDNode *LN = cast<LoadSDNode>(Src);
39956       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39957       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39958       SDValue BcastLd =
39959           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
39960                                   LN->getMemoryVT(), LN->getMemOperand());
39961       // If the load value is used only by N, replace it via CombineTo N.
39962       bool NoReplaceExtract = Src.hasOneUse();
39963       DCI.CombineTo(N.getNode(), BcastLd);
39964       if (NoReplaceExtract) {
39965         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39966         DCI.recursivelyDeleteUnusedNodes(LN);
39967       } else {
39968         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
39969                                   DAG.getIntPtrConstant(0, DL));
39970         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
39971       }
39972       return N; // Return N so it doesn't get rechecked!
39973     }
39974 
39975     // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
39976     // i16. So shrink it ourselves if we can make a broadcast_load.
39977     if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
39978         Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
39979       assert(Subtarget.hasAVX2() && "Expected AVX2");
39980       SDValue TruncIn = Src.getOperand(0);
39981 
39982       // If this is a truncate of a non extending load we can just narrow it to
39983       // use a broadcast_load.
39984       if (ISD::isNormalLoad(TruncIn.getNode())) {
39985         LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
39986         // Unless its volatile or atomic.
39987         if (LN->isSimple()) {
39988           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
39989           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
39990           SDValue BcastLd = DAG.getMemIntrinsicNode(
39991               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
39992               LN->getPointerInfo(), LN->getOriginalAlign(),
39993               LN->getMemOperand()->getFlags());
39994           DCI.CombineTo(N.getNode(), BcastLd);
39995           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
39996           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
39997           return N; // Return N so it doesn't get rechecked!
39998         }
39999       }
40000 
40001       // If this is a truncate of an i16 extload, we can directly replace it.
40002       if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
40003           ISD::isEXTLoad(Src.getOperand(0).getNode())) {
40004         LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
40005         if (LN->getMemoryVT().getSizeInBits() == 16) {
40006           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40007           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
40008           SDValue BcastLd =
40009               DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
40010                                       LN->getMemoryVT(), LN->getMemOperand());
40011           DCI.CombineTo(N.getNode(), BcastLd);
40012           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40013           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
40014           return N; // Return N so it doesn't get rechecked!
40015         }
40016       }
40017 
40018       // If this is a truncate of load that has been shifted right, we can
40019       // offset the pointer and use a narrower load.
40020       if (TruncIn.getOpcode() == ISD::SRL &&
40021           TruncIn.getOperand(0).hasOneUse() &&
40022           isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
40023           ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
40024         LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
40025         unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
40026         // Make sure the shift amount and the load size are divisible by 16.
40027         // Don't do this if the load is volatile or atomic.
40028         if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
40029             LN->isSimple()) {
40030           unsigned Offset = ShiftAmt / 8;
40031           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40032           SDValue Ptr = DAG.getMemBasePlusOffset(
40033               LN->getBasePtr(), TypeSize::getFixed(Offset), DL);
40034           SDValue Ops[] = { LN->getChain(), Ptr };
40035           SDValue BcastLd = DAG.getMemIntrinsicNode(
40036               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
40037               LN->getPointerInfo().getWithOffset(Offset),
40038               LN->getOriginalAlign(),
40039               LN->getMemOperand()->getFlags());
40040           DCI.CombineTo(N.getNode(), BcastLd);
40041           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40042           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
40043           return N; // Return N so it doesn't get rechecked!
40044         }
40045       }
40046     }
40047 
40048     // vbroadcast(vzload X) -> vbroadcast_load X
40049     if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
40050       MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
40051       if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
40052         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40053         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
40054         SDValue BcastLd =
40055             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
40056                                     LN->getMemoryVT(), LN->getMemOperand());
40057         DCI.CombineTo(N.getNode(), BcastLd);
40058         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40059         DCI.recursivelyDeleteUnusedNodes(LN);
40060         return N; // Return N so it doesn't get rechecked!
40061       }
40062     }
40063 
40064     // vbroadcast(vector load X) -> vbroadcast_load
40065     if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
40066          SrcVT == MVT::v4i32) &&
40067         Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
40068       LoadSDNode *LN = cast<LoadSDNode>(Src);
40069       // Unless the load is volatile or atomic.
40070       if (LN->isSimple()) {
40071         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40072         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
40073         SDValue BcastLd = DAG.getMemIntrinsicNode(
40074             X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
40075             LN->getPointerInfo(), LN->getOriginalAlign(),
40076             LN->getMemOperand()->getFlags());
40077         DCI.CombineTo(N.getNode(), BcastLd);
40078         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
40079         DCI.recursivelyDeleteUnusedNodes(LN);
40080         return N; // Return N so it doesn't get rechecked!
40081       }
40082     }
40083 
40084     return SDValue();
40085   }
40086   case X86ISD::VZEXT_MOVL: {
40087     SDValue N0 = N.getOperand(0);
40088 
40089     // If this a vzmovl of a full vector load, replace it with a vzload, unless
40090     // the load is volatile.
40091     if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
40092       auto *LN = cast<LoadSDNode>(N0);
40093       if (SDValue VZLoad =
40094               narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
40095         DCI.CombineTo(N.getNode(), VZLoad);
40096         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
40097         DCI.recursivelyDeleteUnusedNodes(LN);
40098         return N;
40099       }
40100     }
40101 
40102     // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
40103     // and can just use a VZEXT_LOAD.
40104     // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
40105     if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
40106       auto *LN = cast<MemSDNode>(N0);
40107       if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
40108         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
40109         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
40110         SDValue VZLoad =
40111             DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
40112                                     LN->getMemoryVT(), LN->getMemOperand());
40113         DCI.CombineTo(N.getNode(), VZLoad);
40114         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
40115         DCI.recursivelyDeleteUnusedNodes(LN);
40116         return N;
40117       }
40118     }
40119 
40120     // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
40121     // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
40122     // if the upper bits of the i64 are zero.
40123     if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
40124         N0.getOperand(0).hasOneUse() &&
40125         N0.getOperand(0).getValueType() == MVT::i64) {
40126       SDValue In = N0.getOperand(0);
40127       APInt Mask = APInt::getHighBitsSet(64, 32);
40128       if (DAG.MaskedValueIsZero(In, Mask)) {
40129         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
40130         MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
40131         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
40132         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
40133         return DAG.getBitcast(VT, Movl);
40134       }
40135     }
40136 
40137     // Load a scalar integer constant directly to XMM instead of transferring an
40138     // immediate value from GPR.
40139     // vzext_movl (scalar_to_vector C) --> load [C,0...]
40140     if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
40141       if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
40142         // Create a vector constant - scalar constant followed by zeros.
40143         EVT ScalarVT = N0.getOperand(0).getValueType();
40144         Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
40145         unsigned NumElts = VT.getVectorNumElements();
40146         Constant *Zero = ConstantInt::getNullValue(ScalarTy);
40147         SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
40148         ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
40149 
40150         // Load the vector constant from constant pool.
40151         MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
40152         SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
40153         MachinePointerInfo MPI =
40154             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
40155         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
40156         return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
40157                            MachineMemOperand::MOLoad);
40158       }
40159     }
40160 
40161     // Pull subvector inserts into undef through VZEXT_MOVL by making it an
40162     // insert into a zero vector. This helps get VZEXT_MOVL closer to
40163     // scalar_to_vectors where 256/512 are canonicalized to an insert and a
40164     // 128-bit scalar_to_vector. This reduces the number of isel patterns.
40165     if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
40166       SDValue V = peekThroughOneUseBitcasts(N0);
40167 
40168       if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
40169           isNullConstant(V.getOperand(2))) {
40170         SDValue In = V.getOperand(1);
40171         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
40172                                      In.getValueSizeInBits() /
40173                                          VT.getScalarSizeInBits());
40174         In = DAG.getBitcast(SubVT, In);
40175         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
40176         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
40177                            getZeroVector(VT, Subtarget, DAG, DL), Movl,
40178                            V.getOperand(2));
40179       }
40180     }
40181 
40182     return SDValue();
40183   }
40184   case X86ISD::BLENDI: {
40185     SDValue N0 = N.getOperand(0);
40186     SDValue N1 = N.getOperand(1);
40187 
40188     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
40189     // TODO: Handle MVT::v16i16 repeated blend mask.
40190     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
40191         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
40192       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
40193       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
40194           SrcVT.getScalarSizeInBits() >= 32) {
40195         unsigned BlendMask = N.getConstantOperandVal(2);
40196         unsigned Size = VT.getVectorNumElements();
40197         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
40198         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
40199         return DAG.getBitcast(
40200             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
40201                             N1.getOperand(0),
40202                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
40203       }
40204     }
40205     return SDValue();
40206   }
40207   case X86ISD::SHUFP: {
40208     // Fold shufps(shuffle(x),shuffle(y)) -> shufps(x,y).
40209     // This is a more relaxed shuffle combiner that can ignore oneuse limits.
40210     // TODO: Support types other than v4f32.
40211     if (VT == MVT::v4f32) {
40212       bool Updated = false;
40213       SmallVector<int> Mask;
40214       SmallVector<SDValue> Ops;
40215       if (getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask) &&
40216           Ops.size() == 2) {
40217         for (int i = 0; i != 2; ++i) {
40218           SmallVector<SDValue> SubOps;
40219           SmallVector<int> SubMask, SubScaledMask;
40220           SDValue Sub = peekThroughBitcasts(Ops[i]);
40221           // TODO: Scaling might be easier if we specify the demanded elts.
40222           if (getTargetShuffleInputs(Sub, SubOps, SubMask, DAG, 0, false) &&
40223               scaleShuffleElements(SubMask, 4, SubScaledMask) &&
40224               SubOps.size() == 1 && isUndefOrInRange(SubScaledMask, 0, 4)) {
40225             int Ofs = i * 2;
40226             Mask[Ofs + 0] = SubScaledMask[Mask[Ofs + 0] % 4] + (i * 4);
40227             Mask[Ofs + 1] = SubScaledMask[Mask[Ofs + 1] % 4] + (i * 4);
40228             Ops[i] = DAG.getBitcast(VT, SubOps[0]);
40229             Updated = true;
40230           }
40231         }
40232       }
40233       if (Updated) {
40234         for (int &M : Mask)
40235           M %= 4;
40236         Ops.push_back(getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
40237         return DAG.getNode(X86ISD::SHUFP, DL, VT, Ops);
40238       }
40239     }
40240     return SDValue();
40241   }
40242   case X86ISD::VPERMI: {
40243     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
40244     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
40245     SDValue N0 = N.getOperand(0);
40246     SDValue N1 = N.getOperand(1);
40247     unsigned EltSizeInBits = VT.getScalarSizeInBits();
40248     if (N0.getOpcode() == ISD::BITCAST &&
40249         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
40250       SDValue Src = N0.getOperand(0);
40251       EVT SrcVT = Src.getValueType();
40252       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
40253       return DAG.getBitcast(VT, Res);
40254     }
40255     return SDValue();
40256   }
40257   case X86ISD::SHUF128: {
40258     // If we're permuting the upper 256-bits subvectors of a concatenation, then
40259     // see if we can peek through and access the subvector directly.
40260     if (VT.is512BitVector()) {
40261       // 512-bit mask uses 4 x i2 indices - if the msb is always set then only the
40262       // upper subvector is used.
40263       SDValue LHS = N->getOperand(0);
40264       SDValue RHS = N->getOperand(1);
40265       uint64_t Mask = N->getConstantOperandVal(2);
40266       SmallVector<SDValue> LHSOps, RHSOps;
40267       SDValue NewLHS, NewRHS;
40268       if ((Mask & 0x0A) == 0x0A &&
40269           collectConcatOps(LHS.getNode(), LHSOps, DAG) && LHSOps.size() == 2) {
40270         NewLHS = widenSubVector(LHSOps[1], false, Subtarget, DAG, DL, 512);
40271         Mask &= ~0x0A;
40272       }
40273       if ((Mask & 0xA0) == 0xA0 &&
40274           collectConcatOps(RHS.getNode(), RHSOps, DAG) && RHSOps.size() == 2) {
40275         NewRHS = widenSubVector(RHSOps[1], false, Subtarget, DAG, DL, 512);
40276         Mask &= ~0xA0;
40277       }
40278       if (NewLHS || NewRHS)
40279         return DAG.getNode(X86ISD::SHUF128, DL, VT, NewLHS ? NewLHS : LHS,
40280                            NewRHS ? NewRHS : RHS,
40281                            DAG.getTargetConstant(Mask, DL, MVT::i8));
40282     }
40283     return SDValue();
40284   }
40285   case X86ISD::VPERM2X128: {
40286     // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
40287     SDValue LHS = N->getOperand(0);
40288     SDValue RHS = N->getOperand(1);
40289     if (LHS.getOpcode() == ISD::BITCAST &&
40290         (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
40291       EVT SrcVT = LHS.getOperand(0).getValueType();
40292       if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
40293         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
40294                                               DAG.getBitcast(SrcVT, LHS),
40295                                               DAG.getBitcast(SrcVT, RHS),
40296                                               N->getOperand(2)));
40297       }
40298     }
40299 
40300     // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
40301     if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
40302       return Res;
40303 
40304     // Fold vperm2x128 subvector shuffle with an inner concat pattern.
40305     // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
40306     auto FindSubVector128 = [&](unsigned Idx) {
40307       if (Idx > 3)
40308         return SDValue();
40309       SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
40310       SmallVector<SDValue> SubOps;
40311       if (collectConcatOps(Src.getNode(), SubOps, DAG) && SubOps.size() == 2)
40312         return SubOps[Idx & 1];
40313       unsigned NumElts = Src.getValueType().getVectorNumElements();
40314       if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
40315           Src.getOperand(1).getValueSizeInBits() == 128 &&
40316           Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
40317         return Src.getOperand(1);
40318       }
40319       return SDValue();
40320     };
40321     unsigned Imm = N.getConstantOperandVal(2);
40322     if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
40323       if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
40324         MVT SubVT = VT.getHalfNumVectorElementsVT();
40325         SubLo = DAG.getBitcast(SubVT, SubLo);
40326         SubHi = DAG.getBitcast(SubVT, SubHi);
40327         return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
40328       }
40329     }
40330     return SDValue();
40331   }
40332   case X86ISD::PSHUFD:
40333   case X86ISD::PSHUFLW:
40334   case X86ISD::PSHUFHW: {
40335     SDValue N0 = N.getOperand(0);
40336     SDValue N1 = N.getOperand(1);
40337     if (N0->hasOneUse()) {
40338       SDValue V = peekThroughOneUseBitcasts(N0);
40339       switch (V.getOpcode()) {
40340       case X86ISD::VSHL:
40341       case X86ISD::VSRL:
40342       case X86ISD::VSRA:
40343       case X86ISD::VSHLI:
40344       case X86ISD::VSRLI:
40345       case X86ISD::VSRAI:
40346       case X86ISD::VROTLI:
40347       case X86ISD::VROTRI: {
40348         MVT InnerVT = V.getSimpleValueType();
40349         if (InnerVT.getScalarSizeInBits() <= VT.getScalarSizeInBits()) {
40350           SDValue Res = DAG.getNode(Opcode, DL, VT,
40351                                     DAG.getBitcast(VT, V.getOperand(0)), N1);
40352           Res = DAG.getBitcast(InnerVT, Res);
40353           Res = DAG.getNode(V.getOpcode(), DL, InnerVT, Res, V.getOperand(1));
40354           return DAG.getBitcast(VT, Res);
40355         }
40356         break;
40357       }
40358       }
40359     }
40360 
40361     Mask = getPSHUFShuffleMask(N);
40362     assert(Mask.size() == 4);
40363     break;
40364   }
40365   case X86ISD::MOVSD:
40366   case X86ISD::MOVSH:
40367   case X86ISD::MOVSS: {
40368     SDValue N0 = N.getOperand(0);
40369     SDValue N1 = N.getOperand(1);
40370 
40371     // Canonicalize scalar FPOps:
40372     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
40373     // If commutable, allow OP(N1[0], N0[0]).
40374     unsigned Opcode1 = N1.getOpcode();
40375     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
40376         Opcode1 == ISD::FDIV) {
40377       SDValue N10 = N1.getOperand(0);
40378       SDValue N11 = N1.getOperand(1);
40379       if (N10 == N0 ||
40380           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
40381         if (N10 != N0)
40382           std::swap(N10, N11);
40383         MVT SVT = VT.getVectorElementType();
40384         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
40385         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
40386         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
40387         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
40388         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
40389         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
40390       }
40391     }
40392 
40393     return SDValue();
40394   }
40395   case X86ISD::INSERTPS: {
40396     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
40397     SDValue Op0 = N.getOperand(0);
40398     SDValue Op1 = N.getOperand(1);
40399     unsigned InsertPSMask = N.getConstantOperandVal(2);
40400     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
40401     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
40402     unsigned ZeroMask = InsertPSMask & 0xF;
40403 
40404     // If we zero out all elements from Op0 then we don't need to reference it.
40405     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
40406       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
40407                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40408 
40409     // If we zero out the element from Op1 then we don't need to reference it.
40410     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
40411       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
40412                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40413 
40414     // Attempt to merge insertps Op1 with an inner target shuffle node.
40415     SmallVector<int, 8> TargetMask1;
40416     SmallVector<SDValue, 2> Ops1;
40417     APInt KnownUndef1, KnownZero1;
40418     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
40419                                      KnownZero1)) {
40420       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
40421         // Zero/UNDEF insertion - zero out element and remove dependency.
40422         InsertPSMask |= (1u << DstIdx);
40423         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
40424                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40425       }
40426       // Update insertps mask srcidx and reference the source input directly.
40427       int M = TargetMask1[SrcIdx];
40428       assert(0 <= M && M < 8 && "Shuffle index out of range");
40429       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
40430       Op1 = Ops1[M < 4 ? 0 : 1];
40431       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
40432                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40433     }
40434 
40435     // Attempt to merge insertps Op0 with an inner target shuffle node.
40436     SmallVector<int, 8> TargetMask0;
40437     SmallVector<SDValue, 2> Ops0;
40438     APInt KnownUndef0, KnownZero0;
40439     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
40440                                      KnownZero0)) {
40441       bool Updated = false;
40442       bool UseInput00 = false;
40443       bool UseInput01 = false;
40444       for (int i = 0; i != 4; ++i) {
40445         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
40446           // No change if element is already zero or the inserted element.
40447           continue;
40448         }
40449 
40450         if (KnownUndef0[i] || KnownZero0[i]) {
40451           // If the target mask is undef/zero then we must zero the element.
40452           InsertPSMask |= (1u << i);
40453           Updated = true;
40454           continue;
40455         }
40456 
40457         // The input vector element must be inline.
40458         int M = TargetMask0[i];
40459         if (M != i && M != (i + 4))
40460           return SDValue();
40461 
40462         // Determine which inputs of the target shuffle we're using.
40463         UseInput00 |= (0 <= M && M < 4);
40464         UseInput01 |= (4 <= M);
40465       }
40466 
40467       // If we're not using both inputs of the target shuffle then use the
40468       // referenced input directly.
40469       if (UseInput00 && !UseInput01) {
40470         Updated = true;
40471         Op0 = Ops0[0];
40472       } else if (!UseInput00 && UseInput01) {
40473         Updated = true;
40474         Op0 = Ops0[1];
40475       }
40476 
40477       if (Updated)
40478         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
40479                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
40480     }
40481 
40482     // If we're inserting an element from a vbroadcast load, fold the
40483     // load into the X86insertps instruction. We need to convert the scalar
40484     // load to a vector and clear the source lane of the INSERTPS control.
40485     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
40486       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
40487       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
40488         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
40489                                    MemIntr->getBasePtr(),
40490                                    MemIntr->getMemOperand());
40491         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
40492                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
40493                                        Load),
40494                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
40495         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
40496         return Insert;
40497       }
40498     }
40499 
40500     return SDValue();
40501   }
40502   default:
40503     return SDValue();
40504   }
40505 
40506   // Nuke no-op shuffles that show up after combining.
40507   if (isNoopShuffleMask(Mask))
40508     return N.getOperand(0);
40509 
40510   // Look for simplifications involving one or two shuffle instructions.
40511   SDValue V = N.getOperand(0);
40512   switch (N.getOpcode()) {
40513   default:
40514     break;
40515   case X86ISD::PSHUFLW:
40516   case X86ISD::PSHUFHW:
40517     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
40518 
40519     // See if this reduces to a PSHUFD which is no more expensive and can
40520     // combine with more operations. Note that it has to at least flip the
40521     // dwords as otherwise it would have been removed as a no-op.
40522     if (ArrayRef<int>(Mask).equals({2, 3, 0, 1})) {
40523       int DMask[] = {0, 1, 2, 3};
40524       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
40525       DMask[DOffset + 0] = DOffset + 1;
40526       DMask[DOffset + 1] = DOffset + 0;
40527       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
40528       V = DAG.getBitcast(DVT, V);
40529       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
40530                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
40531       return DAG.getBitcast(VT, V);
40532     }
40533 
40534     // Look for shuffle patterns which can be implemented as a single unpack.
40535     // FIXME: This doesn't handle the location of the PSHUFD generically, and
40536     // only works when we have a PSHUFD followed by two half-shuffles.
40537     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
40538         (V.getOpcode() == X86ISD::PSHUFLW ||
40539          V.getOpcode() == X86ISD::PSHUFHW) &&
40540         V.getOpcode() != N.getOpcode() &&
40541         V.hasOneUse() && V.getOperand(0).hasOneUse()) {
40542       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
40543       if (D.getOpcode() == X86ISD::PSHUFD) {
40544         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
40545         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
40546         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
40547         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
40548         int WordMask[8];
40549         for (int i = 0; i < 4; ++i) {
40550           WordMask[i + NOffset] = Mask[i] + NOffset;
40551           WordMask[i + VOffset] = VMask[i] + VOffset;
40552         }
40553         // Map the word mask through the DWord mask.
40554         int MappedMask[8];
40555         for (int i = 0; i < 8; ++i)
40556           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
40557         if (ArrayRef<int>(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
40558             ArrayRef<int>(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
40559           // We can replace all three shuffles with an unpack.
40560           V = DAG.getBitcast(VT, D.getOperand(0));
40561           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
40562                                                 : X86ISD::UNPCKH,
40563                              DL, VT, V, V);
40564         }
40565       }
40566     }
40567 
40568     break;
40569 
40570   case X86ISD::PSHUFD:
40571     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
40572       return NewN;
40573 
40574     break;
40575   }
40576 
40577   return SDValue();
40578 }
40579 
40580 /// Checks if the shuffle mask takes subsequent elements
40581 /// alternately from two vectors.
40582 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
isAddSubOrSubAddMask(ArrayRef<int> Mask,bool & Op0Even)40583 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
40584 
40585   int ParitySrc[2] = {-1, -1};
40586   unsigned Size = Mask.size();
40587   for (unsigned i = 0; i != Size; ++i) {
40588     int M = Mask[i];
40589     if (M < 0)
40590       continue;
40591 
40592     // Make sure we are using the matching element from the input.
40593     if ((M % Size) != i)
40594       return false;
40595 
40596     // Make sure we use the same input for all elements of the same parity.
40597     int Src = M / Size;
40598     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
40599       return false;
40600     ParitySrc[i % 2] = Src;
40601   }
40602 
40603   // Make sure each input is used.
40604   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
40605     return false;
40606 
40607   Op0Even = ParitySrc[0] == 0;
40608   return true;
40609 }
40610 
40611 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
40612 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
40613 /// are written to the parameters \p Opnd0 and \p Opnd1.
40614 ///
40615 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
40616 /// so it is easier to generically match. We also insert dummy vector shuffle
40617 /// nodes for the operands which explicitly discard the lanes which are unused
40618 /// by this operation to try to flow through the rest of the combiner
40619 /// the fact that they're unused.
isAddSubOrSubAdd(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,bool & IsSubAdd)40620 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
40621                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
40622                              bool &IsSubAdd) {
40623 
40624   EVT VT = N->getValueType(0);
40625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40626   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
40627       !VT.getSimpleVT().isFloatingPoint())
40628     return false;
40629 
40630   // We only handle target-independent shuffles.
40631   // FIXME: It would be easy and harmless to use the target shuffle mask
40632   // extraction tool to support more.
40633   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
40634     return false;
40635 
40636   SDValue V1 = N->getOperand(0);
40637   SDValue V2 = N->getOperand(1);
40638 
40639   // Make sure we have an FADD and an FSUB.
40640   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
40641       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
40642       V1.getOpcode() == V2.getOpcode())
40643     return false;
40644 
40645   // If there are other uses of these operations we can't fold them.
40646   if (!V1->hasOneUse() || !V2->hasOneUse())
40647     return false;
40648 
40649   // Ensure that both operations have the same operands. Note that we can
40650   // commute the FADD operands.
40651   SDValue LHS, RHS;
40652   if (V1.getOpcode() == ISD::FSUB) {
40653     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
40654     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
40655         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
40656       return false;
40657   } else {
40658     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
40659     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
40660     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
40661         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
40662       return false;
40663   }
40664 
40665   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
40666   bool Op0Even;
40667   if (!isAddSubOrSubAddMask(Mask, Op0Even))
40668     return false;
40669 
40670   // It's a subadd if the vector in the even parity is an FADD.
40671   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
40672                      : V2->getOpcode() == ISD::FADD;
40673 
40674   Opnd0 = LHS;
40675   Opnd1 = RHS;
40676   return true;
40677 }
40678 
40679 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
combineShuffleToFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)40680 static SDValue combineShuffleToFMAddSub(SDNode *N,
40681                                         const X86Subtarget &Subtarget,
40682                                         SelectionDAG &DAG) {
40683   // We only handle target-independent shuffles.
40684   // FIXME: It would be easy and harmless to use the target shuffle mask
40685   // extraction tool to support more.
40686   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
40687     return SDValue();
40688 
40689   MVT VT = N->getSimpleValueType(0);
40690   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40691   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
40692     return SDValue();
40693 
40694   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
40695   SDValue Op0 = N->getOperand(0);
40696   SDValue Op1 = N->getOperand(1);
40697   SDValue FMAdd = Op0, FMSub = Op1;
40698   if (FMSub.getOpcode() != X86ISD::FMSUB)
40699     std::swap(FMAdd, FMSub);
40700 
40701   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
40702       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
40703       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
40704       FMAdd.getOperand(2) != FMSub.getOperand(2))
40705     return SDValue();
40706 
40707   // Check for correct shuffle mask.
40708   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
40709   bool Op0Even;
40710   if (!isAddSubOrSubAddMask(Mask, Op0Even))
40711     return SDValue();
40712 
40713   // FMAddSub takes zeroth operand from FMSub node.
40714   SDLoc DL(N);
40715   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
40716   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
40717   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
40718                      FMAdd.getOperand(2));
40719 }
40720 
40721 /// Try to combine a shuffle into a target-specific add-sub or
40722 /// mul-add-sub node.
combineShuffleToAddSubOrFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)40723 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
40724                                                 const X86Subtarget &Subtarget,
40725                                                 SelectionDAG &DAG) {
40726   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
40727     return V;
40728 
40729   SDValue Opnd0, Opnd1;
40730   bool IsSubAdd;
40731   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
40732     return SDValue();
40733 
40734   MVT VT = N->getSimpleValueType(0);
40735   SDLoc DL(N);
40736 
40737   // Try to generate X86ISD::FMADDSUB node here.
40738   SDValue Opnd2;
40739   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
40740     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
40741     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
40742   }
40743 
40744   if (IsSubAdd)
40745     return SDValue();
40746 
40747   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
40748   // the ADDSUB idiom has been successfully recognized. There are no known
40749   // X86 targets with 512-bit ADDSUB instructions!
40750   if (VT.is512BitVector())
40751     return SDValue();
40752 
40753   // Do not generate X86ISD::ADDSUB node for FP16's vector types even though
40754   // the ADDSUB idiom has been successfully recognized. There are no known
40755   // X86 targets with FP16 ADDSUB instructions!
40756   if (VT.getVectorElementType() == MVT::f16)
40757     return SDValue();
40758 
40759   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
40760 }
40761 
40762 // We are looking for a shuffle where both sources are concatenated with undef
40763 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
40764 // if we can express this as a single-source shuffle, that's preferable.
combineShuffleOfConcatUndef(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)40765 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
40766                                            const X86Subtarget &Subtarget) {
40767   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
40768     return SDValue();
40769 
40770   EVT VT = N->getValueType(0);
40771 
40772   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
40773   if (!VT.is128BitVector() && !VT.is256BitVector())
40774     return SDValue();
40775 
40776   if (VT.getVectorElementType() != MVT::i32 &&
40777       VT.getVectorElementType() != MVT::i64 &&
40778       VT.getVectorElementType() != MVT::f32 &&
40779       VT.getVectorElementType() != MVT::f64)
40780     return SDValue();
40781 
40782   SDValue N0 = N->getOperand(0);
40783   SDValue N1 = N->getOperand(1);
40784 
40785   // Check that both sources are concats with undef.
40786   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
40787       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
40788       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
40789       !N1.getOperand(1).isUndef())
40790     return SDValue();
40791 
40792   // Construct the new shuffle mask. Elements from the first source retain their
40793   // index, but elements from the second source no longer need to skip an undef.
40794   SmallVector<int, 8> Mask;
40795   int NumElts = VT.getVectorNumElements();
40796 
40797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
40798   for (int Elt : SVOp->getMask())
40799     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
40800 
40801   SDLoc DL(N);
40802   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
40803                                N1.getOperand(0));
40804   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
40805 }
40806 
40807 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
40808 /// low half of each source vector and does not set any high half elements in
40809 /// the destination vector, narrow the shuffle to half its original size.
narrowShuffle(ShuffleVectorSDNode * Shuf,SelectionDAG & DAG)40810 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
40811   EVT VT = Shuf->getValueType(0);
40812   if (!DAG.getTargetLoweringInfo().isTypeLegal(Shuf->getValueType(0)))
40813     return SDValue();
40814   if (!VT.is256BitVector() && !VT.is512BitVector())
40815     return SDValue();
40816 
40817   // See if we can ignore all of the high elements of the shuffle.
40818   ArrayRef<int> Mask = Shuf->getMask();
40819   if (!isUndefUpperHalf(Mask))
40820     return SDValue();
40821 
40822   // Check if the shuffle mask accesses only the low half of each input vector
40823   // (half-index output is 0 or 2).
40824   int HalfIdx1, HalfIdx2;
40825   SmallVector<int, 8> HalfMask(Mask.size() / 2);
40826   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
40827       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
40828     return SDValue();
40829 
40830   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
40831   // The trick is knowing that all of the insert/extract are actually free
40832   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
40833   // of narrow inputs into a narrow output, and that is always cheaper than
40834   // the wide shuffle that we started with.
40835   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
40836                                Shuf->getOperand(1), HalfMask, HalfIdx1,
40837                                HalfIdx2, false, DAG, /*UseConcat*/ true);
40838 }
40839 
combineShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)40840 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
40841                               TargetLowering::DAGCombinerInfo &DCI,
40842                               const X86Subtarget &Subtarget) {
40843   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
40844     if (SDValue V = narrowShuffle(Shuf, DAG))
40845       return V;
40846 
40847   // If we have legalized the vector types, look for blends of FADD and FSUB
40848   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
40849   SDLoc dl(N);
40850   EVT VT = N->getValueType(0);
40851   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40852   if (TLI.isTypeLegal(VT) && !isSoftF16(VT, Subtarget))
40853     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
40854       return AddSub;
40855 
40856   // Attempt to combine into a vector load/broadcast.
40857   if (SDValue LD = combineToConsecutiveLoads(
40858           VT, SDValue(N, 0), dl, DAG, Subtarget, /*IsAfterLegalize*/ true))
40859     return LD;
40860 
40861   // For AVX2, we sometimes want to combine
40862   // (vector_shuffle <mask> (concat_vectors t1, undef)
40863   //                        (concat_vectors t2, undef))
40864   // Into:
40865   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
40866   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
40867   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
40868     return ShufConcat;
40869 
40870   if (isTargetShuffle(N->getOpcode())) {
40871     SDValue Op(N, 0);
40872     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
40873       return Shuffle;
40874 
40875     // Try recursively combining arbitrary sequences of x86 shuffle
40876     // instructions into higher-order shuffles. We do this after combining
40877     // specific PSHUF instruction sequences into their minimal form so that we
40878     // can evaluate how many specialized shuffle instructions are involved in
40879     // a particular chain.
40880     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
40881       return Res;
40882 
40883     // Simplify source operands based on shuffle mask.
40884     // TODO - merge this into combineX86ShufflesRecursively.
40885     APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
40886     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, DCI))
40887       return SDValue(N, 0);
40888 
40889     // Canonicalize SHUFFLE(UNARYOP(X)) -> UNARYOP(SHUFFLE(X)).
40890     // Canonicalize SHUFFLE(BINOP(X,Y)) -> BINOP(SHUFFLE(X),SHUFFLE(Y)).
40891     // Perform this after other shuffle combines to allow inner shuffles to be
40892     // combined away first.
40893     if (SDValue BinOp = canonicalizeShuffleWithOp(Op, DAG, dl))
40894       return BinOp;
40895   }
40896 
40897   return SDValue();
40898 }
40899 
40900 // Simplify variable target shuffle masks based on the demanded elements.
40901 // TODO: Handle DemandedBits in mask indices as well?
SimplifyDemandedVectorEltsForTargetShuffle(SDValue Op,const APInt & DemandedElts,unsigned MaskIndex,TargetLowering::TargetLoweringOpt & TLO,unsigned Depth) const40902 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
40903     SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
40904     TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
40905   // If we're demanding all elements don't bother trying to simplify the mask.
40906   unsigned NumElts = DemandedElts.getBitWidth();
40907   if (DemandedElts.isAllOnes())
40908     return false;
40909 
40910   SDValue Mask = Op.getOperand(MaskIndex);
40911   if (!Mask.hasOneUse())
40912     return false;
40913 
40914   // Attempt to generically simplify the variable shuffle mask.
40915   APInt MaskUndef, MaskZero;
40916   if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
40917                                  Depth + 1))
40918     return true;
40919 
40920   // Attempt to extract+simplify a (constant pool load) shuffle mask.
40921   // TODO: Support other types from getTargetShuffleMaskIndices?
40922   SDValue BC = peekThroughOneUseBitcasts(Mask);
40923   EVT BCVT = BC.getValueType();
40924   auto *Load = dyn_cast<LoadSDNode>(BC);
40925   if (!Load || !Load->getBasePtr().hasOneUse())
40926     return false;
40927 
40928   const Constant *C = getTargetConstantFromNode(Load);
40929   if (!C)
40930     return false;
40931 
40932   Type *CTy = C->getType();
40933   if (!CTy->isVectorTy() ||
40934       CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
40935     return false;
40936 
40937   // Handle scaling for i64 elements on 32-bit targets.
40938   unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
40939   if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
40940     return false;
40941   unsigned Scale = NumCstElts / NumElts;
40942 
40943   // Simplify mask if we have an undemanded element that is not undef.
40944   bool Simplified = false;
40945   SmallVector<Constant *, 32> ConstVecOps;
40946   for (unsigned i = 0; i != NumCstElts; ++i) {
40947     Constant *Elt = C->getAggregateElement(i);
40948     if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
40949       ConstVecOps.push_back(UndefValue::get(Elt->getType()));
40950       Simplified = true;
40951       continue;
40952     }
40953     ConstVecOps.push_back(Elt);
40954   }
40955   if (!Simplified)
40956     return false;
40957 
40958   // Generate new constant pool entry + legalize immediately for the load.
40959   SDLoc DL(Op);
40960   SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
40961   SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
40962   SDValue NewMask = TLO.DAG.getLoad(
40963       BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
40964       MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
40965       Load->getAlign());
40966   return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
40967 }
40968 
SimplifyDemandedVectorEltsForTargetNode(SDValue Op,const APInt & DemandedElts,APInt & KnownUndef,APInt & KnownZero,TargetLoweringOpt & TLO,unsigned Depth) const40969 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
40970     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
40971     TargetLoweringOpt &TLO, unsigned Depth) const {
40972   int NumElts = DemandedElts.getBitWidth();
40973   unsigned Opc = Op.getOpcode();
40974   EVT VT = Op.getValueType();
40975 
40976   // Handle special case opcodes.
40977   switch (Opc) {
40978   case X86ISD::PMULDQ:
40979   case X86ISD::PMULUDQ: {
40980     APInt LHSUndef, LHSZero;
40981     APInt RHSUndef, RHSZero;
40982     SDValue LHS = Op.getOperand(0);
40983     SDValue RHS = Op.getOperand(1);
40984     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
40985                                    Depth + 1))
40986       return true;
40987     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
40988                                    Depth + 1))
40989       return true;
40990     // Multiply by zero.
40991     KnownZero = LHSZero | RHSZero;
40992     break;
40993   }
40994   case X86ISD::VPMADDWD: {
40995     APInt LHSUndef, LHSZero;
40996     APInt RHSUndef, RHSZero;
40997     SDValue LHS = Op.getOperand(0);
40998     SDValue RHS = Op.getOperand(1);
40999     APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, 2 * NumElts);
41000 
41001     if (SimplifyDemandedVectorElts(LHS, DemandedSrcElts, LHSUndef, LHSZero, TLO,
41002                                    Depth + 1))
41003       return true;
41004     if (SimplifyDemandedVectorElts(RHS, DemandedSrcElts, RHSUndef, RHSZero, TLO,
41005                                    Depth + 1))
41006       return true;
41007 
41008     // TODO: Multiply by zero.
41009 
41010     // If RHS/LHS elements are known zero then we don't need the LHS/RHS equivalent.
41011     APInt DemandedLHSElts = DemandedSrcElts & ~RHSZero;
41012     if (SimplifyDemandedVectorElts(LHS, DemandedLHSElts, LHSUndef, LHSZero, TLO,
41013                                    Depth + 1))
41014       return true;
41015     APInt DemandedRHSElts = DemandedSrcElts & ~LHSZero;
41016     if (SimplifyDemandedVectorElts(RHS, DemandedRHSElts, RHSUndef, RHSZero, TLO,
41017                                    Depth + 1))
41018       return true;
41019     break;
41020   }
41021   case X86ISD::PSADBW: {
41022     SDValue LHS = Op.getOperand(0);
41023     SDValue RHS = Op.getOperand(1);
41024     assert(VT.getScalarType() == MVT::i64 &&
41025            LHS.getValueType() == RHS.getValueType() &&
41026            LHS.getValueType().getScalarType() == MVT::i8 &&
41027            "Unexpected PSADBW types");
41028 
41029     // Aggressively peek through ops to get at the demanded elts.
41030     if (!DemandedElts.isAllOnes()) {
41031       unsigned NumSrcElts = LHS.getValueType().getVectorNumElements();
41032       APInt DemandedSrcElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
41033       SDValue NewLHS = SimplifyMultipleUseDemandedVectorElts(
41034           LHS, DemandedSrcElts, TLO.DAG, Depth + 1);
41035       SDValue NewRHS = SimplifyMultipleUseDemandedVectorElts(
41036           RHS, DemandedSrcElts, TLO.DAG, Depth + 1);
41037       if (NewLHS || NewRHS) {
41038         NewLHS = NewLHS ? NewLHS : LHS;
41039         NewRHS = NewRHS ? NewRHS : RHS;
41040         return TLO.CombineTo(
41041             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
41042       }
41043     }
41044     break;
41045   }
41046   case X86ISD::VSHL:
41047   case X86ISD::VSRL:
41048   case X86ISD::VSRA: {
41049     // We only need the bottom 64-bits of the (128-bit) shift amount.
41050     SDValue Amt = Op.getOperand(1);
41051     MVT AmtVT = Amt.getSimpleValueType();
41052     assert(AmtVT.is128BitVector() && "Unexpected value type");
41053 
41054     // If we reuse the shift amount just for sse shift amounts then we know that
41055     // only the bottom 64-bits are only ever used.
41056     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
41057       unsigned UseOpc = Use->getOpcode();
41058       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
41059               UseOpc == X86ISD::VSRA) &&
41060              Use->getOperand(0) != Amt;
41061     });
41062 
41063     APInt AmtUndef, AmtZero;
41064     unsigned NumAmtElts = AmtVT.getVectorNumElements();
41065     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
41066     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
41067                                    Depth + 1, AssumeSingleUse))
41068       return true;
41069     [[fallthrough]];
41070   }
41071   case X86ISD::VSHLI:
41072   case X86ISD::VSRLI:
41073   case X86ISD::VSRAI: {
41074     SDValue Src = Op.getOperand(0);
41075     APInt SrcUndef;
41076     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
41077                                    Depth + 1))
41078       return true;
41079 
41080     // Fold shift(0,x) -> 0
41081     if (DemandedElts.isSubsetOf(KnownZero))
41082       return TLO.CombineTo(
41083           Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
41084 
41085     // Aggressively peek through ops to get at the demanded elts.
41086     if (!DemandedElts.isAllOnes())
41087       if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
41088               Src, DemandedElts, TLO.DAG, Depth + 1))
41089         return TLO.CombineTo(
41090             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
41091     break;
41092   }
41093   case X86ISD::VPSHA:
41094   case X86ISD::VPSHL:
41095   case X86ISD::VSHLV:
41096   case X86ISD::VSRLV:
41097   case X86ISD::VSRAV: {
41098     APInt LHSUndef, LHSZero;
41099     APInt RHSUndef, RHSZero;
41100     SDValue LHS = Op.getOperand(0);
41101     SDValue RHS = Op.getOperand(1);
41102     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
41103                                    Depth + 1))
41104       return true;
41105 
41106     // Fold shift(0,x) -> 0
41107     if (DemandedElts.isSubsetOf(LHSZero))
41108       return TLO.CombineTo(
41109           Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
41110 
41111     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
41112                                    Depth + 1))
41113       return true;
41114 
41115     KnownZero = LHSZero;
41116     break;
41117   }
41118   case X86ISD::KSHIFTL: {
41119     SDValue Src = Op.getOperand(0);
41120     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
41121     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
41122     unsigned ShiftAmt = Amt->getZExtValue();
41123 
41124     if (ShiftAmt == 0)
41125       return TLO.CombineTo(Op, Src);
41126 
41127     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
41128     // single shift.  We can do this if the bottom bits (which are shifted
41129     // out) are never demanded.
41130     if (Src.getOpcode() == X86ISD::KSHIFTR) {
41131       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
41132         unsigned C1 = Src.getConstantOperandVal(1);
41133         unsigned NewOpc = X86ISD::KSHIFTL;
41134         int Diff = ShiftAmt - C1;
41135         if (Diff < 0) {
41136           Diff = -Diff;
41137           NewOpc = X86ISD::KSHIFTR;
41138         }
41139 
41140         SDLoc dl(Op);
41141         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
41142         return TLO.CombineTo(
41143             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
41144       }
41145     }
41146 
41147     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
41148     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
41149                                    Depth + 1))
41150       return true;
41151 
41152     KnownUndef <<= ShiftAmt;
41153     KnownZero <<= ShiftAmt;
41154     KnownZero.setLowBits(ShiftAmt);
41155     break;
41156   }
41157   case X86ISD::KSHIFTR: {
41158     SDValue Src = Op.getOperand(0);
41159     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
41160     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
41161     unsigned ShiftAmt = Amt->getZExtValue();
41162 
41163     if (ShiftAmt == 0)
41164       return TLO.CombineTo(Op, Src);
41165 
41166     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
41167     // single shift.  We can do this if the top bits (which are shifted
41168     // out) are never demanded.
41169     if (Src.getOpcode() == X86ISD::KSHIFTL) {
41170       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
41171         unsigned C1 = Src.getConstantOperandVal(1);
41172         unsigned NewOpc = X86ISD::KSHIFTR;
41173         int Diff = ShiftAmt - C1;
41174         if (Diff < 0) {
41175           Diff = -Diff;
41176           NewOpc = X86ISD::KSHIFTL;
41177         }
41178 
41179         SDLoc dl(Op);
41180         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
41181         return TLO.CombineTo(
41182             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
41183       }
41184     }
41185 
41186     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
41187     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
41188                                    Depth + 1))
41189       return true;
41190 
41191     KnownUndef.lshrInPlace(ShiftAmt);
41192     KnownZero.lshrInPlace(ShiftAmt);
41193     KnownZero.setHighBits(ShiftAmt);
41194     break;
41195   }
41196   case X86ISD::ANDNP: {
41197     // ANDNP = (~LHS & RHS);
41198     SDValue LHS = Op.getOperand(0);
41199     SDValue RHS = Op.getOperand(1);
41200 
41201     auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
41202       APInt UndefElts;
41203       SmallVector<APInt> EltBits;
41204       int NumElts = VT.getVectorNumElements();
41205       int EltSizeInBits = VT.getScalarSizeInBits();
41206       APInt OpBits = APInt::getAllOnes(EltSizeInBits);
41207       APInt OpElts = DemandedElts;
41208       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
41209                                         EltBits)) {
41210         OpBits.clearAllBits();
41211         OpElts.clearAllBits();
41212         for (int I = 0; I != NumElts; ++I) {
41213           if (!DemandedElts[I])
41214             continue;
41215           if (UndefElts[I]) {
41216             // We can't assume an undef src element gives an undef dst - the
41217             // other src might be zero.
41218             OpBits.setAllBits();
41219             OpElts.setBit(I);
41220           } else if ((Invert && !EltBits[I].isAllOnes()) ||
41221                      (!Invert && !EltBits[I].isZero())) {
41222             OpBits |= Invert ? ~EltBits[I] : EltBits[I];
41223             OpElts.setBit(I);
41224           }
41225         }
41226       }
41227       return std::make_pair(OpBits, OpElts);
41228     };
41229     APInt BitsLHS, EltsLHS;
41230     APInt BitsRHS, EltsRHS;
41231     std::tie(BitsLHS, EltsLHS) = GetDemandedMasks(RHS);
41232     std::tie(BitsRHS, EltsRHS) = GetDemandedMasks(LHS, true);
41233 
41234     APInt LHSUndef, LHSZero;
41235     APInt RHSUndef, RHSZero;
41236     if (SimplifyDemandedVectorElts(LHS, EltsLHS, LHSUndef, LHSZero, TLO,
41237                                    Depth + 1))
41238       return true;
41239     if (SimplifyDemandedVectorElts(RHS, EltsRHS, RHSUndef, RHSZero, TLO,
41240                                    Depth + 1))
41241       return true;
41242 
41243     if (!DemandedElts.isAllOnes()) {
41244       SDValue NewLHS = SimplifyMultipleUseDemandedBits(LHS, BitsLHS, EltsLHS,
41245                                                        TLO.DAG, Depth + 1);
41246       SDValue NewRHS = SimplifyMultipleUseDemandedBits(RHS, BitsRHS, EltsRHS,
41247                                                        TLO.DAG, Depth + 1);
41248       if (NewLHS || NewRHS) {
41249         NewLHS = NewLHS ? NewLHS : LHS;
41250         NewRHS = NewRHS ? NewRHS : RHS;
41251         return TLO.CombineTo(
41252             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewLHS, NewRHS));
41253       }
41254     }
41255     break;
41256   }
41257   case X86ISD::CVTSI2P:
41258   case X86ISD::CVTUI2P: {
41259     SDValue Src = Op.getOperand(0);
41260     MVT SrcVT = Src.getSimpleValueType();
41261     APInt SrcUndef, SrcZero;
41262     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
41263     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
41264                                    Depth + 1))
41265       return true;
41266     break;
41267   }
41268   case X86ISD::PACKSS:
41269   case X86ISD::PACKUS: {
41270     SDValue N0 = Op.getOperand(0);
41271     SDValue N1 = Op.getOperand(1);
41272 
41273     APInt DemandedLHS, DemandedRHS;
41274     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
41275 
41276     APInt LHSUndef, LHSZero;
41277     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
41278                                    Depth + 1))
41279       return true;
41280     APInt RHSUndef, RHSZero;
41281     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
41282                                    Depth + 1))
41283       return true;
41284 
41285     // TODO - pass on known zero/undef.
41286 
41287     // Aggressively peek through ops to get at the demanded elts.
41288     // TODO - we should do this for all target/faux shuffles ops.
41289     if (!DemandedElts.isAllOnes()) {
41290       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
41291                                                             TLO.DAG, Depth + 1);
41292       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
41293                                                             TLO.DAG, Depth + 1);
41294       if (NewN0 || NewN1) {
41295         NewN0 = NewN0 ? NewN0 : N0;
41296         NewN1 = NewN1 ? NewN1 : N1;
41297         return TLO.CombineTo(Op,
41298                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
41299       }
41300     }
41301     break;
41302   }
41303   case X86ISD::HADD:
41304   case X86ISD::HSUB:
41305   case X86ISD::FHADD:
41306   case X86ISD::FHSUB: {
41307     SDValue N0 = Op.getOperand(0);
41308     SDValue N1 = Op.getOperand(1);
41309 
41310     APInt DemandedLHS, DemandedRHS;
41311     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
41312 
41313     APInt LHSUndef, LHSZero;
41314     if (SimplifyDemandedVectorElts(N0, DemandedLHS, LHSUndef, LHSZero, TLO,
41315                                    Depth + 1))
41316       return true;
41317     APInt RHSUndef, RHSZero;
41318     if (SimplifyDemandedVectorElts(N1, DemandedRHS, RHSUndef, RHSZero, TLO,
41319                                    Depth + 1))
41320       return true;
41321 
41322     // TODO - pass on known zero/undef.
41323 
41324     // Aggressively peek through ops to get at the demanded elts.
41325     // TODO: Handle repeated operands.
41326     if (N0 != N1 && !DemandedElts.isAllOnes()) {
41327       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
41328                                                             TLO.DAG, Depth + 1);
41329       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
41330                                                             TLO.DAG, Depth + 1);
41331       if (NewN0 || NewN1) {
41332         NewN0 = NewN0 ? NewN0 : N0;
41333         NewN1 = NewN1 ? NewN1 : N1;
41334         return TLO.CombineTo(Op,
41335                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
41336       }
41337     }
41338     break;
41339   }
41340   case X86ISD::VTRUNC:
41341   case X86ISD::VTRUNCS:
41342   case X86ISD::VTRUNCUS: {
41343     SDValue Src = Op.getOperand(0);
41344     MVT SrcVT = Src.getSimpleValueType();
41345     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
41346     APInt SrcUndef, SrcZero;
41347     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
41348                                    Depth + 1))
41349       return true;
41350     KnownZero = SrcZero.zextOrTrunc(NumElts);
41351     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
41352     break;
41353   }
41354   case X86ISD::BLENDV: {
41355     APInt SelUndef, SelZero;
41356     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
41357                                    SelZero, TLO, Depth + 1))
41358       return true;
41359 
41360     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
41361     APInt LHSUndef, LHSZero;
41362     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
41363                                    LHSZero, TLO, Depth + 1))
41364       return true;
41365 
41366     APInt RHSUndef, RHSZero;
41367     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
41368                                    RHSZero, TLO, Depth + 1))
41369       return true;
41370 
41371     KnownZero = LHSZero & RHSZero;
41372     KnownUndef = LHSUndef & RHSUndef;
41373     break;
41374   }
41375   case X86ISD::VZEXT_MOVL: {
41376     // If upper demanded elements are already zero then we have nothing to do.
41377     SDValue Src = Op.getOperand(0);
41378     APInt DemandedUpperElts = DemandedElts;
41379     DemandedUpperElts.clearLowBits(1);
41380     if (TLO.DAG.MaskedVectorIsZero(Src, DemandedUpperElts, Depth + 1))
41381       return TLO.CombineTo(Op, Src);
41382     break;
41383   }
41384   case X86ISD::VZEXT_LOAD: {
41385     // If upper demanded elements are not demanded then simplify to a
41386     // scalar_to_vector(load()).
41387     MVT SVT = VT.getSimpleVT().getVectorElementType();
41388     if (DemandedElts == 1 && Op.getValue(1).use_empty() && isTypeLegal(SVT)) {
41389       SDLoc DL(Op);
41390       auto *Mem = cast<MemSDNode>(Op);
41391       SDValue Elt = TLO.DAG.getLoad(SVT, DL, Mem->getChain(), Mem->getBasePtr(),
41392                                     Mem->getMemOperand());
41393       SDValue Vec = TLO.DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Elt);
41394       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Vec));
41395     }
41396     break;
41397   }
41398   case X86ISD::VBROADCAST: {
41399     SDValue Src = Op.getOperand(0);
41400     MVT SrcVT = Src.getSimpleValueType();
41401     if (!SrcVT.isVector())
41402       break;
41403     // Don't bother broadcasting if we just need the 0'th element.
41404     if (DemandedElts == 1) {
41405       if (Src.getValueType() != VT)
41406         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
41407                              SDLoc(Op));
41408       return TLO.CombineTo(Op, Src);
41409     }
41410     APInt SrcUndef, SrcZero;
41411     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
41412     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
41413                                    Depth + 1))
41414       return true;
41415     // Aggressively peek through src to get at the demanded elt.
41416     // TODO - we should do this for all target/faux shuffles ops.
41417     if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
41418             Src, SrcElts, TLO.DAG, Depth + 1))
41419       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
41420     break;
41421   }
41422   case X86ISD::VPERMV:
41423     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
41424                                                    Depth))
41425       return true;
41426     break;
41427   case X86ISD::PSHUFB:
41428   case X86ISD::VPERMV3:
41429   case X86ISD::VPERMILPV:
41430     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
41431                                                    Depth))
41432       return true;
41433     break;
41434   case X86ISD::VPPERM:
41435   case X86ISD::VPERMIL2:
41436     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
41437                                                    Depth))
41438       return true;
41439     break;
41440   }
41441 
41442   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
41443   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
41444   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
41445   if ((VT.is256BitVector() || VT.is512BitVector()) &&
41446       DemandedElts.lshr(NumElts / 2) == 0) {
41447     unsigned SizeInBits = VT.getSizeInBits();
41448     unsigned ExtSizeInBits = SizeInBits / 2;
41449 
41450     // See if 512-bit ops only use the bottom 128-bits.
41451     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
41452       ExtSizeInBits = SizeInBits / 4;
41453 
41454     switch (Opc) {
41455       // Scalar broadcast.
41456     case X86ISD::VBROADCAST: {
41457       SDLoc DL(Op);
41458       SDValue Src = Op.getOperand(0);
41459       if (Src.getValueSizeInBits() > ExtSizeInBits)
41460         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
41461       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
41462                                     ExtSizeInBits / VT.getScalarSizeInBits());
41463       SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
41464       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
41465                                                TLO.DAG, DL, ExtSizeInBits));
41466     }
41467     case X86ISD::VBROADCAST_LOAD: {
41468       SDLoc DL(Op);
41469       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
41470       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
41471                                     ExtSizeInBits / VT.getScalarSizeInBits());
41472       SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
41473       SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
41474       SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
41475           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
41476           MemIntr->getMemOperand());
41477       TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
41478                                            Bcst.getValue(1));
41479       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
41480                                                TLO.DAG, DL, ExtSizeInBits));
41481     }
41482       // Subvector broadcast.
41483     case X86ISD::SUBV_BROADCAST_LOAD: {
41484       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
41485       EVT MemVT = MemIntr->getMemoryVT();
41486       if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
41487         SDLoc DL(Op);
41488         SDValue Ld =
41489             TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
41490                             MemIntr->getBasePtr(), MemIntr->getMemOperand());
41491         TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
41492                                              Ld.getValue(1));
41493         return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
41494                                                  TLO.DAG, DL, ExtSizeInBits));
41495       } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
41496         SDLoc DL(Op);
41497         EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
41498                                       ExtSizeInBits / VT.getScalarSizeInBits());
41499         if (SDValue BcstLd =
41500                 getBROADCAST_LOAD(Opc, DL, BcstVT, MemVT, MemIntr, 0, TLO.DAG))
41501           return TLO.CombineTo(Op,
41502                                insertSubVector(TLO.DAG.getUNDEF(VT), BcstLd, 0,
41503                                                TLO.DAG, DL, ExtSizeInBits));
41504       }
41505       break;
41506     }
41507       // Byte shifts by immediate.
41508     case X86ISD::VSHLDQ:
41509     case X86ISD::VSRLDQ:
41510       // Shift by uniform.
41511     case X86ISD::VSHL:
41512     case X86ISD::VSRL:
41513     case X86ISD::VSRA:
41514       // Shift by immediate.
41515     case X86ISD::VSHLI:
41516     case X86ISD::VSRLI:
41517     case X86ISD::VSRAI: {
41518       SDLoc DL(Op);
41519       SDValue Ext0 =
41520           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
41521       SDValue ExtOp =
41522           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
41523       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41524       SDValue Insert =
41525           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
41526       return TLO.CombineTo(Op, Insert);
41527     }
41528     case X86ISD::VPERMI: {
41529       // Simplify PERMPD/PERMQ to extract_subvector.
41530       // TODO: This should be done in shuffle combining.
41531       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
41532         SmallVector<int, 4> Mask;
41533         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
41534         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
41535           SDLoc DL(Op);
41536           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
41537           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41538           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
41539           return TLO.CombineTo(Op, Insert);
41540         }
41541       }
41542       break;
41543     }
41544     case X86ISD::VPERM2X128: {
41545       // Simplify VPERM2F128/VPERM2I128 to extract_subvector.
41546       SDLoc DL(Op);
41547       unsigned LoMask = Op.getConstantOperandVal(2) & 0xF;
41548       if (LoMask & 0x8)
41549         return TLO.CombineTo(
41550             Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, DL));
41551       unsigned EltIdx = (LoMask & 0x1) * (NumElts / 2);
41552       unsigned SrcIdx = (LoMask & 0x2) >> 1;
41553       SDValue ExtOp =
41554           extractSubVector(Op.getOperand(SrcIdx), EltIdx, TLO.DAG, DL, 128);
41555       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41556       SDValue Insert =
41557           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
41558       return TLO.CombineTo(Op, Insert);
41559     }
41560       // Zero upper elements.
41561     case X86ISD::VZEXT_MOVL:
41562       // Target unary shuffles by immediate:
41563     case X86ISD::PSHUFD:
41564     case X86ISD::PSHUFLW:
41565     case X86ISD::PSHUFHW:
41566     case X86ISD::VPERMILPI:
41567       // (Non-Lane Crossing) Target Shuffles.
41568     case X86ISD::VPERMILPV:
41569     case X86ISD::VPERMIL2:
41570     case X86ISD::PSHUFB:
41571     case X86ISD::UNPCKL:
41572     case X86ISD::UNPCKH:
41573     case X86ISD::BLENDI:
41574       // Integer ops.
41575     case X86ISD::PACKSS:
41576     case X86ISD::PACKUS:
41577     case X86ISD::PCMPEQ:
41578     case X86ISD::PCMPGT:
41579     case X86ISD::PMULUDQ:
41580     case X86ISD::PMULDQ:
41581     case X86ISD::VSHLV:
41582     case X86ISD::VSRLV:
41583     case X86ISD::VSRAV:
41584       // Float ops.
41585     case X86ISD::FMAX:
41586     case X86ISD::FMIN:
41587     case X86ISD::FMAXC:
41588     case X86ISD::FMINC:
41589       // Horizontal Ops.
41590     case X86ISD::HADD:
41591     case X86ISD::HSUB:
41592     case X86ISD::FHADD:
41593     case X86ISD::FHSUB: {
41594       SDLoc DL(Op);
41595       SmallVector<SDValue, 4> Ops;
41596       for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
41597         SDValue SrcOp = Op.getOperand(i);
41598         EVT SrcVT = SrcOp.getValueType();
41599         assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
41600                "Unsupported vector size");
41601         Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
41602                                                           ExtSizeInBits)
41603                                        : SrcOp);
41604       }
41605       MVT ExtVT = VT.getSimpleVT();
41606       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
41607                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
41608       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
41609       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
41610       SDValue Insert =
41611           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
41612       return TLO.CombineTo(Op, Insert);
41613     }
41614     }
41615   }
41616 
41617   // For splats, unless we *only* demand the 0'th element,
41618   // stop attempts at simplification here, we aren't going to improve things,
41619   // this is better than any potential shuffle.
41620   if (!DemandedElts.isOne() && TLO.DAG.isSplatValue(Op, /*AllowUndefs*/false))
41621     return false;
41622 
41623   // Get target/faux shuffle mask.
41624   APInt OpUndef, OpZero;
41625   SmallVector<int, 64> OpMask;
41626   SmallVector<SDValue, 2> OpInputs;
41627   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
41628                               OpZero, TLO.DAG, Depth, false))
41629     return false;
41630 
41631   // Shuffle inputs must be the same size as the result.
41632   if (OpMask.size() != (unsigned)NumElts ||
41633       llvm::any_of(OpInputs, [VT](SDValue V) {
41634         return VT.getSizeInBits() != V.getValueSizeInBits() ||
41635                !V.getValueType().isVector();
41636       }))
41637     return false;
41638 
41639   KnownZero = OpZero;
41640   KnownUndef = OpUndef;
41641 
41642   // Check if shuffle mask can be simplified to undef/zero/identity.
41643   int NumSrcs = OpInputs.size();
41644   for (int i = 0; i != NumElts; ++i)
41645     if (!DemandedElts[i])
41646       OpMask[i] = SM_SentinelUndef;
41647 
41648   if (isUndefInRange(OpMask, 0, NumElts)) {
41649     KnownUndef.setAllBits();
41650     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
41651   }
41652   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
41653     KnownZero.setAllBits();
41654     return TLO.CombineTo(
41655         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
41656   }
41657   for (int Src = 0; Src != NumSrcs; ++Src)
41658     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
41659       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
41660 
41661   // Attempt to simplify inputs.
41662   for (int Src = 0; Src != NumSrcs; ++Src) {
41663     // TODO: Support inputs of different types.
41664     if (OpInputs[Src].getValueType() != VT)
41665       continue;
41666 
41667     int Lo = Src * NumElts;
41668     APInt SrcElts = APInt::getZero(NumElts);
41669     for (int i = 0; i != NumElts; ++i)
41670       if (DemandedElts[i]) {
41671         int M = OpMask[i] - Lo;
41672         if (0 <= M && M < NumElts)
41673           SrcElts.setBit(M);
41674       }
41675 
41676     // TODO - Propagate input undef/zero elts.
41677     APInt SrcUndef, SrcZero;
41678     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
41679                                    TLO, Depth + 1))
41680       return true;
41681   }
41682 
41683   // If we don't demand all elements, then attempt to combine to a simpler
41684   // shuffle.
41685   // We need to convert the depth to something combineX86ShufflesRecursively
41686   // can handle - so pretend its Depth == 0 again, and reduce the max depth
41687   // to match. This prevents combineX86ShuffleChain from returning a
41688   // combined shuffle that's the same as the original root, causing an
41689   // infinite loop.
41690   if (!DemandedElts.isAllOnes()) {
41691     assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range");
41692 
41693     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
41694     for (int i = 0; i != NumElts; ++i)
41695       if (DemandedElts[i])
41696         DemandedMask[i] = i;
41697 
41698     SDValue NewShuffle = combineX86ShufflesRecursively(
41699         {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
41700         /*HasVarMask*/ false,
41701         /*AllowCrossLaneVarMask*/ true, /*AllowPerLaneVarMask*/ true, TLO.DAG,
41702         Subtarget);
41703     if (NewShuffle)
41704       return TLO.CombineTo(Op, NewShuffle);
41705   }
41706 
41707   return false;
41708 }
41709 
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const41710 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
41711     SDValue Op, const APInt &OriginalDemandedBits,
41712     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
41713     unsigned Depth) const {
41714   EVT VT = Op.getValueType();
41715   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
41716   unsigned Opc = Op.getOpcode();
41717   switch(Opc) {
41718   case X86ISD::VTRUNC: {
41719     KnownBits KnownOp;
41720     SDValue Src = Op.getOperand(0);
41721     MVT SrcVT = Src.getSimpleValueType();
41722 
41723     // Simplify the input, using demanded bit information.
41724     APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
41725     APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
41726     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
41727       return true;
41728     break;
41729   }
41730   case X86ISD::PMULDQ:
41731   case X86ISD::PMULUDQ: {
41732     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
41733     KnownBits KnownLHS, KnownRHS;
41734     SDValue LHS = Op.getOperand(0);
41735     SDValue RHS = Op.getOperand(1);
41736 
41737     // Don't mask bits on 32-bit AVX512 targets which might lose a broadcast.
41738     // FIXME: Can we bound this better?
41739     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
41740     APInt DemandedMaskLHS = APInt::getAllOnes(64);
41741     APInt DemandedMaskRHS = APInt::getAllOnes(64);
41742 
41743     bool Is32BitAVX512 = !Subtarget.is64Bit() && Subtarget.hasAVX512();
41744     if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(LHS))
41745       DemandedMaskLHS = DemandedMask;
41746     if (!Is32BitAVX512 || !TLO.DAG.isSplatValue(RHS))
41747       DemandedMaskRHS = DemandedMask;
41748 
41749     if (SimplifyDemandedBits(LHS, DemandedMaskLHS, OriginalDemandedElts,
41750                              KnownLHS, TLO, Depth + 1))
41751       return true;
41752     if (SimplifyDemandedBits(RHS, DemandedMaskRHS, OriginalDemandedElts,
41753                              KnownRHS, TLO, Depth + 1))
41754       return true;
41755 
41756     // PMULUDQ(X,1) -> AND(X,(1<<32)-1) 'getZeroExtendInReg'.
41757     KnownRHS = KnownRHS.trunc(32);
41758     if (Opc == X86ISD::PMULUDQ && KnownRHS.isConstant() &&
41759         KnownRHS.getConstant().isOne()) {
41760       SDLoc DL(Op);
41761       SDValue Mask = TLO.DAG.getConstant(DemandedMask, DL, VT);
41762       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, DL, VT, LHS, Mask));
41763     }
41764 
41765     // Aggressively peek through ops to get at the demanded low bits.
41766     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
41767         LHS, DemandedMaskLHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
41768     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
41769         RHS, DemandedMaskRHS, OriginalDemandedElts, TLO.DAG, Depth + 1);
41770     if (DemandedLHS || DemandedRHS) {
41771       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
41772       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
41773       return TLO.CombineTo(
41774           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
41775     }
41776     break;
41777   }
41778   case X86ISD::ANDNP: {
41779     KnownBits Known2;
41780     SDValue Op0 = Op.getOperand(0);
41781     SDValue Op1 = Op.getOperand(1);
41782 
41783     if (SimplifyDemandedBits(Op1, OriginalDemandedBits, OriginalDemandedElts,
41784                              Known, TLO, Depth + 1))
41785       return true;
41786     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41787 
41788     if (SimplifyDemandedBits(Op0, ~Known.Zero & OriginalDemandedBits,
41789                              OriginalDemandedElts, Known2, TLO, Depth + 1))
41790       return true;
41791     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
41792 
41793     // If the RHS is a constant, see if we can simplify it.
41794     if (ShrinkDemandedConstant(Op, ~Known2.One & OriginalDemandedBits,
41795                                OriginalDemandedElts, TLO))
41796       return true;
41797 
41798     // ANDNP = (~Op0 & Op1);
41799     Known.One &= Known2.Zero;
41800     Known.Zero |= Known2.One;
41801     break;
41802   }
41803   case X86ISD::VSHLI: {
41804     SDValue Op0 = Op.getOperand(0);
41805 
41806     unsigned ShAmt = Op.getConstantOperandVal(1);
41807     if (ShAmt >= BitWidth)
41808       break;
41809 
41810     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
41811 
41812     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
41813     // single shift.  We can do this if the bottom bits (which are shifted
41814     // out) are never demanded.
41815     if (Op0.getOpcode() == X86ISD::VSRLI &&
41816         OriginalDemandedBits.countr_zero() >= ShAmt) {
41817       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
41818       if (Shift2Amt < BitWidth) {
41819         int Diff = ShAmt - Shift2Amt;
41820         if (Diff == 0)
41821           return TLO.CombineTo(Op, Op0.getOperand(0));
41822 
41823         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
41824         SDValue NewShift = TLO.DAG.getNode(
41825             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
41826             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
41827         return TLO.CombineTo(Op, NewShift);
41828       }
41829     }
41830 
41831     // If we are only demanding sign bits then we can use the shift source directly.
41832     unsigned NumSignBits =
41833         TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
41834     unsigned UpperDemandedBits = BitWidth - OriginalDemandedBits.countr_zero();
41835     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
41836       return TLO.CombineTo(Op, Op0);
41837 
41838     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
41839                              TLO, Depth + 1))
41840       return true;
41841 
41842     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41843     Known.Zero <<= ShAmt;
41844     Known.One <<= ShAmt;
41845 
41846     // Low bits known zero.
41847     Known.Zero.setLowBits(ShAmt);
41848     return false;
41849   }
41850   case X86ISD::VSRLI: {
41851     unsigned ShAmt = Op.getConstantOperandVal(1);
41852     if (ShAmt >= BitWidth)
41853       break;
41854 
41855     APInt DemandedMask = OriginalDemandedBits << ShAmt;
41856 
41857     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
41858                              OriginalDemandedElts, Known, TLO, Depth + 1))
41859       return true;
41860 
41861     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41862     Known.Zero.lshrInPlace(ShAmt);
41863     Known.One.lshrInPlace(ShAmt);
41864 
41865     // High bits known zero.
41866     Known.Zero.setHighBits(ShAmt);
41867     return false;
41868   }
41869   case X86ISD::VSRAI: {
41870     SDValue Op0 = Op.getOperand(0);
41871     SDValue Op1 = Op.getOperand(1);
41872 
41873     unsigned ShAmt = Op1->getAsZExtVal();
41874     if (ShAmt >= BitWidth)
41875       break;
41876 
41877     APInt DemandedMask = OriginalDemandedBits << ShAmt;
41878 
41879     // If we just want the sign bit then we don't need to shift it.
41880     if (OriginalDemandedBits.isSignMask())
41881       return TLO.CombineTo(Op, Op0);
41882 
41883     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
41884     if (Op0.getOpcode() == X86ISD::VSHLI &&
41885         Op.getOperand(1) == Op0.getOperand(1)) {
41886       SDValue Op00 = Op0.getOperand(0);
41887       unsigned NumSignBits =
41888           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
41889       if (ShAmt < NumSignBits)
41890         return TLO.CombineTo(Op, Op00);
41891     }
41892 
41893     // If any of the demanded bits are produced by the sign extension, we also
41894     // demand the input sign bit.
41895     if (OriginalDemandedBits.countl_zero() < ShAmt)
41896       DemandedMask.setSignBit();
41897 
41898     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
41899                              TLO, Depth + 1))
41900       return true;
41901 
41902     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
41903     Known.Zero.lshrInPlace(ShAmt);
41904     Known.One.lshrInPlace(ShAmt);
41905 
41906     // If the input sign bit is known to be zero, or if none of the top bits
41907     // are demanded, turn this into an unsigned shift right.
41908     if (Known.Zero[BitWidth - ShAmt - 1] ||
41909         OriginalDemandedBits.countl_zero() >= ShAmt)
41910       return TLO.CombineTo(
41911           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
41912 
41913     // High bits are known one.
41914     if (Known.One[BitWidth - ShAmt - 1])
41915       Known.One.setHighBits(ShAmt);
41916     return false;
41917   }
41918   case X86ISD::BLENDV: {
41919     SDValue Sel = Op.getOperand(0);
41920     SDValue LHS = Op.getOperand(1);
41921     SDValue RHS = Op.getOperand(2);
41922 
41923     APInt SignMask = APInt::getSignMask(BitWidth);
41924     SDValue NewSel = SimplifyMultipleUseDemandedBits(
41925         Sel, SignMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
41926     SDValue NewLHS = SimplifyMultipleUseDemandedBits(
41927         LHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
41928     SDValue NewRHS = SimplifyMultipleUseDemandedBits(
41929         RHS, OriginalDemandedBits, OriginalDemandedElts, TLO.DAG, Depth + 1);
41930 
41931     if (NewSel || NewLHS || NewRHS) {
41932       NewSel = NewSel ? NewSel : Sel;
41933       NewLHS = NewLHS ? NewLHS : LHS;
41934       NewRHS = NewRHS ? NewRHS : RHS;
41935       return TLO.CombineTo(Op, TLO.DAG.getNode(X86ISD::BLENDV, SDLoc(Op), VT,
41936                                                NewSel, NewLHS, NewRHS));
41937     }
41938     break;
41939   }
41940   case X86ISD::PEXTRB:
41941   case X86ISD::PEXTRW: {
41942     SDValue Vec = Op.getOperand(0);
41943     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
41944     MVT VecVT = Vec.getSimpleValueType();
41945     unsigned NumVecElts = VecVT.getVectorNumElements();
41946 
41947     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
41948       unsigned Idx = CIdx->getZExtValue();
41949       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
41950 
41951       // If we demand no bits from the vector then we must have demanded
41952       // bits from the implict zext - simplify to zero.
41953       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
41954       if (DemandedVecBits == 0)
41955         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
41956 
41957       APInt KnownUndef, KnownZero;
41958       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
41959       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
41960                                      KnownZero, TLO, Depth + 1))
41961         return true;
41962 
41963       KnownBits KnownVec;
41964       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
41965                                KnownVec, TLO, Depth + 1))
41966         return true;
41967 
41968       if (SDValue V = SimplifyMultipleUseDemandedBits(
41969               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
41970         return TLO.CombineTo(
41971             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
41972 
41973       Known = KnownVec.zext(BitWidth);
41974       return false;
41975     }
41976     break;
41977   }
41978   case X86ISD::PINSRB:
41979   case X86ISD::PINSRW: {
41980     SDValue Vec = Op.getOperand(0);
41981     SDValue Scl = Op.getOperand(1);
41982     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
41983     MVT VecVT = Vec.getSimpleValueType();
41984 
41985     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
41986       unsigned Idx = CIdx->getZExtValue();
41987       if (!OriginalDemandedElts[Idx])
41988         return TLO.CombineTo(Op, Vec);
41989 
41990       KnownBits KnownVec;
41991       APInt DemandedVecElts(OriginalDemandedElts);
41992       DemandedVecElts.clearBit(Idx);
41993       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
41994                                KnownVec, TLO, Depth + 1))
41995         return true;
41996 
41997       KnownBits KnownScl;
41998       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
41999       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
42000       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
42001         return true;
42002 
42003       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
42004       Known = KnownVec.intersectWith(KnownScl);
42005       return false;
42006     }
42007     break;
42008   }
42009   case X86ISD::PACKSS:
42010     // PACKSS saturates to MIN/MAX integer values. So if we just want the
42011     // sign bit then we can just ask for the source operands sign bit.
42012     // TODO - add known bits handling.
42013     if (OriginalDemandedBits.isSignMask()) {
42014       APInt DemandedLHS, DemandedRHS;
42015       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
42016 
42017       KnownBits KnownLHS, KnownRHS;
42018       APInt SignMask = APInt::getSignMask(BitWidth * 2);
42019       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
42020                                KnownLHS, TLO, Depth + 1))
42021         return true;
42022       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
42023                                KnownRHS, TLO, Depth + 1))
42024         return true;
42025 
42026       // Attempt to avoid multi-use ops if we don't need anything from them.
42027       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
42028           Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
42029       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
42030           Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
42031       if (DemandedOp0 || DemandedOp1) {
42032         SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
42033         SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
42034         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
42035       }
42036     }
42037     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
42038     break;
42039   case X86ISD::VBROADCAST: {
42040     SDValue Src = Op.getOperand(0);
42041     MVT SrcVT = Src.getSimpleValueType();
42042     APInt DemandedElts = APInt::getOneBitSet(
42043         SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1, 0);
42044     if (SimplifyDemandedBits(Src, OriginalDemandedBits, DemandedElts, Known,
42045                              TLO, Depth + 1))
42046       return true;
42047     // If we don't need the upper bits, attempt to narrow the broadcast source.
42048     // Don't attempt this on AVX512 as it might affect broadcast folding.
42049     // TODO: Should we attempt this for i32/i16 splats? They tend to be slower.
42050     if ((BitWidth == 64) && SrcVT.isScalarInteger() && !Subtarget.hasAVX512() &&
42051         OriginalDemandedBits.countl_zero() >= (BitWidth / 2) &&
42052         Src->hasOneUse()) {
42053       MVT NewSrcVT = MVT::getIntegerVT(BitWidth / 2);
42054       SDValue NewSrc =
42055           TLO.DAG.getNode(ISD::TRUNCATE, SDLoc(Src), NewSrcVT, Src);
42056       MVT NewVT = MVT::getVectorVT(NewSrcVT, VT.getVectorNumElements() * 2);
42057       SDValue NewBcst =
42058           TLO.DAG.getNode(X86ISD::VBROADCAST, SDLoc(Op), NewVT, NewSrc);
42059       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, NewBcst));
42060     }
42061     break;
42062   }
42063   case X86ISD::PCMPGT:
42064     // icmp sgt(0, R) == ashr(R, BitWidth-1).
42065     // iff we only need the sign bit then we can use R directly.
42066     if (OriginalDemandedBits.isSignMask() &&
42067         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
42068       return TLO.CombineTo(Op, Op.getOperand(1));
42069     break;
42070   case X86ISD::MOVMSK: {
42071     SDValue Src = Op.getOperand(0);
42072     MVT SrcVT = Src.getSimpleValueType();
42073     unsigned SrcBits = SrcVT.getScalarSizeInBits();
42074     unsigned NumElts = SrcVT.getVectorNumElements();
42075 
42076     // If we don't need the sign bits at all just return zero.
42077     if (OriginalDemandedBits.countr_zero() >= NumElts)
42078       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
42079 
42080     // See if we only demand bits from the lower 128-bit vector.
42081     if (SrcVT.is256BitVector() &&
42082         OriginalDemandedBits.getActiveBits() <= (NumElts / 2)) {
42083       SDValue NewSrc = extract128BitVector(Src, 0, TLO.DAG, SDLoc(Src));
42084       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
42085     }
42086 
42087     // Only demand the vector elements of the sign bits we need.
42088     APInt KnownUndef, KnownZero;
42089     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
42090     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
42091                                    TLO, Depth + 1))
42092       return true;
42093 
42094     Known.Zero = KnownZero.zext(BitWidth);
42095     Known.Zero.setHighBits(BitWidth - NumElts);
42096 
42097     // MOVMSK only uses the MSB from each vector element.
42098     KnownBits KnownSrc;
42099     APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
42100     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
42101                              Depth + 1))
42102       return true;
42103 
42104     if (KnownSrc.One[SrcBits - 1])
42105       Known.One.setLowBits(NumElts);
42106     else if (KnownSrc.Zero[SrcBits - 1])
42107       Known.Zero.setLowBits(NumElts);
42108 
42109     // Attempt to avoid multi-use os if we don't need anything from it.
42110     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
42111             Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
42112       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
42113     return false;
42114   }
42115   case X86ISD::TESTP: {
42116     SDValue Op0 = Op.getOperand(0);
42117     SDValue Op1 = Op.getOperand(1);
42118     MVT OpVT = Op0.getSimpleValueType();
42119     assert((OpVT.getVectorElementType() == MVT::f32 ||
42120             OpVT.getVectorElementType() == MVT::f64) &&
42121            "Illegal vector type for X86ISD::TESTP");
42122 
42123     // TESTPS/TESTPD only demands the sign bits of ALL the elements.
42124     KnownBits KnownSrc;
42125     APInt SignMask = APInt::getSignMask(OpVT.getScalarSizeInBits());
42126     bool AssumeSingleUse = (Op0 == Op1) && Op->isOnlyUserOf(Op0.getNode());
42127     return SimplifyDemandedBits(Op0, SignMask, KnownSrc, TLO, Depth + 1,
42128                                 AssumeSingleUse) ||
42129            SimplifyDemandedBits(Op1, SignMask, KnownSrc, TLO, Depth + 1,
42130                                 AssumeSingleUse);
42131   }
42132   case X86ISD::BEXTR:
42133   case X86ISD::BEXTRI: {
42134     SDValue Op0 = Op.getOperand(0);
42135     SDValue Op1 = Op.getOperand(1);
42136 
42137     // Only bottom 16-bits of the control bits are required.
42138     if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
42139       // NOTE: SimplifyDemandedBits won't do this for constants.
42140       uint64_t Val1 = Cst1->getZExtValue();
42141       uint64_t MaskedVal1 = Val1 & 0xFFFF;
42142       if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
42143         SDLoc DL(Op);
42144         return TLO.CombineTo(
42145             Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
42146                                 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
42147       }
42148 
42149       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
42150       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
42151 
42152       // If the length is 0, the result is 0.
42153       if (Length == 0) {
42154         Known.setAllZero();
42155         return false;
42156       }
42157 
42158       if ((Shift + Length) <= BitWidth) {
42159         APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
42160         if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
42161           return true;
42162 
42163         Known = Known.extractBits(Length, Shift);
42164         Known = Known.zextOrTrunc(BitWidth);
42165         return false;
42166       }
42167     } else {
42168       assert(Opc == X86ISD::BEXTR && "Unexpected opcode!");
42169       KnownBits Known1;
42170       APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
42171       if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
42172         return true;
42173 
42174       // If the length is 0, replace with 0.
42175       KnownBits LengthBits = Known1.extractBits(8, 8);
42176       if (LengthBits.isZero())
42177         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
42178     }
42179 
42180     break;
42181   }
42182   case X86ISD::PDEP: {
42183     SDValue Op0 = Op.getOperand(0);
42184     SDValue Op1 = Op.getOperand(1);
42185 
42186     unsigned DemandedBitsLZ = OriginalDemandedBits.countl_zero();
42187     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
42188 
42189     // If the demanded bits has leading zeroes, we don't demand those from the
42190     // mask.
42191     if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
42192       return true;
42193 
42194     // The number of possible 1s in the mask determines the number of LSBs of
42195     // operand 0 used. Undemanded bits from the mask don't matter so filter
42196     // them before counting.
42197     KnownBits Known2;
42198     uint64_t Count = (~Known.Zero & LoMask).popcount();
42199     APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
42200     if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
42201       return true;
42202 
42203     // Zeroes are retained from the mask, but not ones.
42204     Known.One.clearAllBits();
42205     // The result will have at least as many trailing zeros as the non-mask
42206     // operand since bits can only map to the same or higher bit position.
42207     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
42208     return false;
42209   }
42210   }
42211 
42212   return TargetLowering::SimplifyDemandedBitsForTargetNode(
42213       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
42214 }
42215 
SimplifyMultipleUseDemandedBitsForTargetNode(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,SelectionDAG & DAG,unsigned Depth) const42216 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
42217     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
42218     SelectionDAG &DAG, unsigned Depth) const {
42219   int NumElts = DemandedElts.getBitWidth();
42220   unsigned Opc = Op.getOpcode();
42221   EVT VT = Op.getValueType();
42222 
42223   switch (Opc) {
42224   case X86ISD::PINSRB:
42225   case X86ISD::PINSRW: {
42226     // If we don't demand the inserted element, return the base vector.
42227     SDValue Vec = Op.getOperand(0);
42228     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
42229     MVT VecVT = Vec.getSimpleValueType();
42230     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
42231         !DemandedElts[CIdx->getZExtValue()])
42232       return Vec;
42233     break;
42234   }
42235   case X86ISD::VSHLI: {
42236     // If we are only demanding sign bits then we can use the shift source
42237     // directly.
42238     SDValue Op0 = Op.getOperand(0);
42239     unsigned ShAmt = Op.getConstantOperandVal(1);
42240     unsigned BitWidth = DemandedBits.getBitWidth();
42241     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
42242     unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
42243     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
42244       return Op0;
42245     break;
42246   }
42247   case X86ISD::VSRAI:
42248     // iff we only need the sign bit then we can use the source directly.
42249     // TODO: generalize where we only demand extended signbits.
42250     if (DemandedBits.isSignMask())
42251       return Op.getOperand(0);
42252     break;
42253   case X86ISD::PCMPGT:
42254     // icmp sgt(0, R) == ashr(R, BitWidth-1).
42255     // iff we only need the sign bit then we can use R directly.
42256     if (DemandedBits.isSignMask() &&
42257         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
42258       return Op.getOperand(1);
42259     break;
42260   case X86ISD::BLENDV: {
42261     // BLENDV: Cond (MSB) ? LHS : RHS
42262     SDValue Cond = Op.getOperand(0);
42263     SDValue LHS = Op.getOperand(1);
42264     SDValue RHS = Op.getOperand(2);
42265 
42266     KnownBits CondKnown = DAG.computeKnownBits(Cond, DemandedElts, Depth + 1);
42267     if (CondKnown.isNegative())
42268       return LHS;
42269     if (CondKnown.isNonNegative())
42270       return RHS;
42271     break;
42272   }
42273   case X86ISD::ANDNP: {
42274     // ANDNP = (~LHS & RHS);
42275     SDValue LHS = Op.getOperand(0);
42276     SDValue RHS = Op.getOperand(1);
42277 
42278     KnownBits LHSKnown = DAG.computeKnownBits(LHS, DemandedElts, Depth + 1);
42279     KnownBits RHSKnown = DAG.computeKnownBits(RHS, DemandedElts, Depth + 1);
42280 
42281     // If all of the demanded bits are known 0 on LHS and known 0 on RHS, then
42282     // the (inverted) LHS bits cannot contribute to the result of the 'andn' in
42283     // this context, so return RHS.
42284     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.Zero))
42285       return RHS;
42286     break;
42287   }
42288   }
42289 
42290   APInt ShuffleUndef, ShuffleZero;
42291   SmallVector<int, 16> ShuffleMask;
42292   SmallVector<SDValue, 2> ShuffleOps;
42293   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
42294                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
42295     // If all the demanded elts are from one operand and are inline,
42296     // then we can use the operand directly.
42297     int NumOps = ShuffleOps.size();
42298     if (ShuffleMask.size() == (unsigned)NumElts &&
42299         llvm::all_of(ShuffleOps, [VT](SDValue V) {
42300           return VT.getSizeInBits() == V.getValueSizeInBits();
42301         })) {
42302 
42303       if (DemandedElts.isSubsetOf(ShuffleUndef))
42304         return DAG.getUNDEF(VT);
42305       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
42306         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
42307 
42308       // Bitmask that indicates which ops have only been accessed 'inline'.
42309       APInt IdentityOp = APInt::getAllOnes(NumOps);
42310       for (int i = 0; i != NumElts; ++i) {
42311         int M = ShuffleMask[i];
42312         if (!DemandedElts[i] || ShuffleUndef[i])
42313           continue;
42314         int OpIdx = M / NumElts;
42315         int EltIdx = M % NumElts;
42316         if (M < 0 || EltIdx != i) {
42317           IdentityOp.clearAllBits();
42318           break;
42319         }
42320         IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
42321         if (IdentityOp == 0)
42322           break;
42323       }
42324       assert((IdentityOp == 0 || IdentityOp.popcount() == 1) &&
42325              "Multiple identity shuffles detected");
42326 
42327       if (IdentityOp != 0)
42328         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countr_zero()]);
42329     }
42330   }
42331 
42332   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
42333       Op, DemandedBits, DemandedElts, DAG, Depth);
42334 }
42335 
isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op,const APInt & DemandedElts,const SelectionDAG & DAG,bool PoisonOnly,unsigned Depth) const42336 bool X86TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
42337     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
42338     bool PoisonOnly, unsigned Depth) const {
42339   unsigned EltsBits = Op.getScalarValueSizeInBits();
42340   unsigned NumElts = DemandedElts.getBitWidth();
42341 
42342   // TODO: Add more target shuffles.
42343   switch (Op.getOpcode()) {
42344   case X86ISD::PSHUFD:
42345   case X86ISD::VPERMILPI: {
42346     SmallVector<int, 8> Mask;
42347     DecodePSHUFMask(NumElts, EltsBits, Op.getConstantOperandVal(1), Mask);
42348 
42349     APInt DemandedSrcElts = APInt::getZero(NumElts);
42350     for (unsigned I = 0; I != NumElts; ++I)
42351       if (DemandedElts[I])
42352         DemandedSrcElts.setBit(Mask[I]);
42353 
42354     return DAG.isGuaranteedNotToBeUndefOrPoison(
42355         Op.getOperand(0), DemandedSrcElts, PoisonOnly, Depth + 1);
42356   }
42357   }
42358   return TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
42359       Op, DemandedElts, DAG, PoisonOnly, Depth);
42360 }
42361 
canCreateUndefOrPoisonForTargetNode(SDValue Op,const APInt & DemandedElts,const SelectionDAG & DAG,bool PoisonOnly,bool ConsiderFlags,unsigned Depth) const42362 bool X86TargetLowering::canCreateUndefOrPoisonForTargetNode(
42363     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
42364     bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const {
42365 
42366   // TODO: Add more target shuffles.
42367   switch (Op.getOpcode()) {
42368   case X86ISD::PSHUFD:
42369   case X86ISD::VPERMILPI:
42370     return false;
42371   }
42372   return TargetLowering::canCreateUndefOrPoisonForTargetNode(
42373       Op, DemandedElts, DAG, PoisonOnly, ConsiderFlags, Depth);
42374 }
42375 
isSplatValueForTargetNode(SDValue Op,const APInt & DemandedElts,APInt & UndefElts,const SelectionDAG & DAG,unsigned Depth) const42376 bool X86TargetLowering::isSplatValueForTargetNode(SDValue Op,
42377                                                   const APInt &DemandedElts,
42378                                                   APInt &UndefElts,
42379                                                   const SelectionDAG &DAG,
42380                                                   unsigned Depth) const {
42381   unsigned NumElts = DemandedElts.getBitWidth();
42382   unsigned Opc = Op.getOpcode();
42383 
42384   switch (Opc) {
42385   case X86ISD::VBROADCAST:
42386   case X86ISD::VBROADCAST_LOAD:
42387     UndefElts = APInt::getZero(NumElts);
42388     return true;
42389   }
42390 
42391   return TargetLowering::isSplatValueForTargetNode(Op, DemandedElts, UndefElts,
42392                                                    DAG, Depth);
42393 }
42394 
42395 // Helper to peek through bitops/trunc/setcc to determine size of source vector.
42396 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
checkBitcastSrcVectorSize(SDValue Src,unsigned Size,bool AllowTruncate)42397 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size,
42398                                       bool AllowTruncate) {
42399   switch (Src.getOpcode()) {
42400   case ISD::TRUNCATE:
42401     if (!AllowTruncate)
42402       return false;
42403     [[fallthrough]];
42404   case ISD::SETCC:
42405     return Src.getOperand(0).getValueSizeInBits() == Size;
42406   case ISD::AND:
42407   case ISD::XOR:
42408   case ISD::OR:
42409     return checkBitcastSrcVectorSize(Src.getOperand(0), Size, AllowTruncate) &&
42410            checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate);
42411   case ISD::SELECT:
42412   case ISD::VSELECT:
42413     return Src.getOperand(0).getScalarValueSizeInBits() == 1 &&
42414            checkBitcastSrcVectorSize(Src.getOperand(1), Size, AllowTruncate) &&
42415            checkBitcastSrcVectorSize(Src.getOperand(2), Size, AllowTruncate);
42416   case ISD::BUILD_VECTOR:
42417     return ISD::isBuildVectorAllZeros(Src.getNode()) ||
42418            ISD::isBuildVectorAllOnes(Src.getNode());
42419   }
42420   return false;
42421 }
42422 
42423 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
getAltBitOpcode(unsigned Opcode)42424 static unsigned getAltBitOpcode(unsigned Opcode) {
42425   switch(Opcode) {
42426   case ISD::AND: return X86ISD::FAND;
42427   case ISD::OR: return X86ISD::FOR;
42428   case ISD::XOR: return X86ISD::FXOR;
42429   case X86ISD::ANDNP: return X86ISD::FANDN;
42430   }
42431   llvm_unreachable("Unknown bitwise opcode");
42432 }
42433 
42434 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
adjustBitcastSrcVectorSSE1(SelectionDAG & DAG,SDValue Src,const SDLoc & DL)42435 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
42436                                           const SDLoc &DL) {
42437   EVT SrcVT = Src.getValueType();
42438   if (SrcVT != MVT::v4i1)
42439     return SDValue();
42440 
42441   switch (Src.getOpcode()) {
42442   case ISD::SETCC:
42443     if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
42444         ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
42445         cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
42446       SDValue Op0 = Src.getOperand(0);
42447       if (ISD::isNormalLoad(Op0.getNode()))
42448         return DAG.getBitcast(MVT::v4f32, Op0);
42449       if (Op0.getOpcode() == ISD::BITCAST &&
42450           Op0.getOperand(0).getValueType() == MVT::v4f32)
42451         return Op0.getOperand(0);
42452     }
42453     break;
42454   case ISD::AND:
42455   case ISD::XOR:
42456   case ISD::OR: {
42457     SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
42458     SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
42459     if (Op0 && Op1)
42460       return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
42461                          Op1);
42462     break;
42463   }
42464   }
42465   return SDValue();
42466 }
42467 
42468 // Helper to push sign extension of vXi1 SETCC result through bitops.
signExtendBitcastSrcVector(SelectionDAG & DAG,EVT SExtVT,SDValue Src,const SDLoc & DL)42469 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
42470                                           SDValue Src, const SDLoc &DL) {
42471   switch (Src.getOpcode()) {
42472   case ISD::SETCC:
42473   case ISD::TRUNCATE:
42474   case ISD::BUILD_VECTOR:
42475     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
42476   case ISD::AND:
42477   case ISD::XOR:
42478   case ISD::OR:
42479     return DAG.getNode(
42480         Src.getOpcode(), DL, SExtVT,
42481         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
42482         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
42483   case ISD::SELECT:
42484   case ISD::VSELECT:
42485     return DAG.getSelect(
42486         DL, SExtVT, Src.getOperand(0),
42487         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL),
42488         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(2), DL));
42489   }
42490   llvm_unreachable("Unexpected node type for vXi1 sign extension");
42491 }
42492 
42493 // Try to match patterns such as
42494 // (i16 bitcast (v16i1 x))
42495 // ->
42496 // (i16 movmsk (16i8 sext (v16i1 x)))
42497 // before the illegal vector is scalarized on subtargets that don't have legal
42498 // vxi1 types.
combineBitcastvxi1(SelectionDAG & DAG,EVT VT,SDValue Src,const SDLoc & DL,const X86Subtarget & Subtarget)42499 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
42500                                   const SDLoc &DL,
42501                                   const X86Subtarget &Subtarget) {
42502   EVT SrcVT = Src.getValueType();
42503   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
42504     return SDValue();
42505 
42506   // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
42507   // legalization destroys the v4i32 type.
42508   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
42509     if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
42510       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
42511                       DAG.getBitcast(MVT::v4f32, V));
42512       return DAG.getZExtOrTrunc(V, DL, VT);
42513     }
42514   }
42515 
42516   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
42517   // movmskb even with avx512. This will be better than truncating to vXi1 and
42518   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
42519   // vpcmpeqb/vpcmpgtb.
42520   bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
42521                       (Src.getOperand(0).getValueType() == MVT::v16i8 ||
42522                        Src.getOperand(0).getValueType() == MVT::v32i8 ||
42523                        Src.getOperand(0).getValueType() == MVT::v64i8);
42524 
42525   // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
42526   // directly with vpmovmskb/vmovmskps/vmovmskpd.
42527   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
42528       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
42529       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
42530     EVT CmpVT = Src.getOperand(0).getValueType();
42531     EVT EltVT = CmpVT.getVectorElementType();
42532     if (CmpVT.getSizeInBits() <= 256 &&
42533         (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
42534       PreferMovMsk = true;
42535   }
42536 
42537   // With AVX512 vxi1 types are legal and we prefer using k-regs.
42538   // MOVMSK is supported in SSE2 or later.
42539   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
42540     return SDValue();
42541 
42542   // If the upper ops of a concatenation are undef, then try to bitcast the
42543   // lower op and extend.
42544   SmallVector<SDValue, 4> SubSrcOps;
42545   if (collectConcatOps(Src.getNode(), SubSrcOps, DAG) &&
42546       SubSrcOps.size() >= 2) {
42547     SDValue LowerOp = SubSrcOps[0];
42548     ArrayRef<SDValue> UpperOps(std::next(SubSrcOps.begin()), SubSrcOps.end());
42549     if (LowerOp.getOpcode() == ISD::SETCC &&
42550         all_of(UpperOps, [](SDValue Op) { return Op.isUndef(); })) {
42551       EVT SubVT = VT.getIntegerVT(
42552           *DAG.getContext(), LowerOp.getValueType().getVectorMinNumElements());
42553       if (SDValue V = combineBitcastvxi1(DAG, SubVT, LowerOp, DL, Subtarget)) {
42554         EVT IntVT = VT.getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
42555         return DAG.getBitcast(VT, DAG.getNode(ISD::ANY_EXTEND, DL, IntVT, V));
42556       }
42557     }
42558   }
42559 
42560   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
42561   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
42562   // v8i16 and v16i16.
42563   // For these two cases, we can shuffle the upper element bytes to a
42564   // consecutive sequence at the start of the vector and treat the results as
42565   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
42566   // for v16i16 this is not the case, because the shuffle is expensive, so we
42567   // avoid sign-extending to this type entirely.
42568   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
42569   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
42570   MVT SExtVT;
42571   bool PropagateSExt = false;
42572   switch (SrcVT.getSimpleVT().SimpleTy) {
42573   default:
42574     return SDValue();
42575   case MVT::v2i1:
42576     SExtVT = MVT::v2i64;
42577     break;
42578   case MVT::v4i1:
42579     SExtVT = MVT::v4i32;
42580     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
42581     // sign-extend to a 256-bit operation to avoid truncation.
42582     if (Subtarget.hasAVX() &&
42583         checkBitcastSrcVectorSize(Src, 256, Subtarget.hasAVX2())) {
42584       SExtVT = MVT::v4i64;
42585       PropagateSExt = true;
42586     }
42587     break;
42588   case MVT::v8i1:
42589     SExtVT = MVT::v8i16;
42590     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
42591     // sign-extend to a 256-bit operation to match the compare.
42592     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
42593     // 256-bit because the shuffle is cheaper than sign extending the result of
42594     // the compare.
42595     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256, true) ||
42596                                checkBitcastSrcVectorSize(Src, 512, true))) {
42597       SExtVT = MVT::v8i32;
42598       PropagateSExt = true;
42599     }
42600     break;
42601   case MVT::v16i1:
42602     SExtVT = MVT::v16i8;
42603     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
42604     // it is not profitable to sign-extend to 256-bit because this will
42605     // require an extra cross-lane shuffle which is more expensive than
42606     // truncating the result of the compare to 128-bits.
42607     break;
42608   case MVT::v32i1:
42609     SExtVT = MVT::v32i8;
42610     break;
42611   case MVT::v64i1:
42612     // If we have AVX512F, but not AVX512BW and the input is truncated from
42613     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
42614     if (Subtarget.hasAVX512()) {
42615       if (Subtarget.hasBWI())
42616         return SDValue();
42617       SExtVT = MVT::v64i8;
42618       break;
42619     }
42620     // Split if this is a <64 x i8> comparison result.
42621     if (checkBitcastSrcVectorSize(Src, 512, false)) {
42622       SExtVT = MVT::v64i8;
42623       break;
42624     }
42625     return SDValue();
42626   };
42627 
42628   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
42629                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
42630 
42631   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
42632     V = getPMOVMSKB(DL, V, DAG, Subtarget);
42633   } else {
42634     if (SExtVT == MVT::v8i16) {
42635       V = widenSubVector(V, false, Subtarget, DAG, DL, 256);
42636       V = DAG.getNode(ISD::TRUNCATE, DL, MVT::v16i8, V);
42637     }
42638     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
42639   }
42640 
42641   EVT IntVT =
42642       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
42643   V = DAG.getZExtOrTrunc(V, DL, IntVT);
42644   return DAG.getBitcast(VT, V);
42645 }
42646 
42647 // Convert a vXi1 constant build vector to the same width scalar integer.
combinevXi1ConstantToInteger(SDValue Op,SelectionDAG & DAG)42648 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
42649   EVT SrcVT = Op.getValueType();
42650   assert(SrcVT.getVectorElementType() == MVT::i1 &&
42651          "Expected a vXi1 vector");
42652   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
42653          "Expected a constant build vector");
42654 
42655   APInt Imm(SrcVT.getVectorNumElements(), 0);
42656   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
42657     SDValue In = Op.getOperand(Idx);
42658     if (!In.isUndef() && (In->getAsZExtVal() & 0x1))
42659       Imm.setBit(Idx);
42660   }
42661   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
42662   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
42663 }
42664 
combineCastedMaskArithmetic(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42665 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
42666                                            TargetLowering::DAGCombinerInfo &DCI,
42667                                            const X86Subtarget &Subtarget) {
42668   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
42669 
42670   if (!DCI.isBeforeLegalizeOps())
42671     return SDValue();
42672 
42673   // Only do this if we have k-registers.
42674   if (!Subtarget.hasAVX512())
42675     return SDValue();
42676 
42677   EVT DstVT = N->getValueType(0);
42678   SDValue Op = N->getOperand(0);
42679   EVT SrcVT = Op.getValueType();
42680 
42681   if (!Op.hasOneUse())
42682     return SDValue();
42683 
42684   // Look for logic ops.
42685   if (Op.getOpcode() != ISD::AND &&
42686       Op.getOpcode() != ISD::OR &&
42687       Op.getOpcode() != ISD::XOR)
42688     return SDValue();
42689 
42690   // Make sure we have a bitcast between mask registers and a scalar type.
42691   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
42692         DstVT.isScalarInteger()) &&
42693       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
42694         SrcVT.isScalarInteger()))
42695     return SDValue();
42696 
42697   SDValue LHS = Op.getOperand(0);
42698   SDValue RHS = Op.getOperand(1);
42699 
42700   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
42701       LHS.getOperand(0).getValueType() == DstVT)
42702     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
42703                        DAG.getBitcast(DstVT, RHS));
42704 
42705   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
42706       RHS.getOperand(0).getValueType() == DstVT)
42707     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
42708                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
42709 
42710   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
42711   // Most of these have to move a constant from the scalar domain anyway.
42712   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
42713     RHS = combinevXi1ConstantToInteger(RHS, DAG);
42714     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
42715                        DAG.getBitcast(DstVT, LHS), RHS);
42716   }
42717 
42718   return SDValue();
42719 }
42720 
createMMXBuildVector(BuildVectorSDNode * BV,SelectionDAG & DAG,const X86Subtarget & Subtarget)42721 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
42722                                     const X86Subtarget &Subtarget) {
42723   SDLoc DL(BV);
42724   unsigned NumElts = BV->getNumOperands();
42725   SDValue Splat = BV->getSplatValue();
42726 
42727   // Build MMX element from integer GPR or SSE float values.
42728   auto CreateMMXElement = [&](SDValue V) {
42729     if (V.isUndef())
42730       return DAG.getUNDEF(MVT::x86mmx);
42731     if (V.getValueType().isFloatingPoint()) {
42732       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
42733         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
42734         V = DAG.getBitcast(MVT::v2i64, V);
42735         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
42736       }
42737       V = DAG.getBitcast(MVT::i32, V);
42738     } else {
42739       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
42740     }
42741     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
42742   };
42743 
42744   // Convert build vector ops to MMX data in the bottom elements.
42745   SmallVector<SDValue, 8> Ops;
42746 
42747   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42748 
42749   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
42750   if (Splat) {
42751     if (Splat.isUndef())
42752       return DAG.getUNDEF(MVT::x86mmx);
42753 
42754     Splat = CreateMMXElement(Splat);
42755 
42756     if (Subtarget.hasSSE1()) {
42757       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
42758       if (NumElts == 8)
42759         Splat = DAG.getNode(
42760             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
42761             DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
42762                                   TLI.getPointerTy(DAG.getDataLayout())),
42763             Splat, Splat);
42764 
42765       // Use PSHUFW to repeat 16-bit elements.
42766       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
42767       return DAG.getNode(
42768           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
42769           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
42770                                 TLI.getPointerTy(DAG.getDataLayout())),
42771           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
42772     }
42773     Ops.append(NumElts, Splat);
42774   } else {
42775     for (unsigned i = 0; i != NumElts; ++i)
42776       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
42777   }
42778 
42779   // Use tree of PUNPCKLs to build up general MMX vector.
42780   while (Ops.size() > 1) {
42781     unsigned NumOps = Ops.size();
42782     unsigned IntrinOp =
42783         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
42784                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
42785                                     : Intrinsic::x86_mmx_punpcklbw));
42786     SDValue Intrin = DAG.getTargetConstant(
42787         IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
42788     for (unsigned i = 0; i != NumOps; i += 2)
42789       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
42790                                Ops[i], Ops[i + 1]);
42791     Ops.resize(NumOps / 2);
42792   }
42793 
42794   return Ops[0];
42795 }
42796 
42797 // Recursive function that attempts to find if a bool vector node was originally
42798 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
42799 // integer. If so, replace the scalar ops with bool vector equivalents back down
42800 // the chain.
combineBitcastToBoolVector(EVT VT,SDValue V,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)42801 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
42802                                           SelectionDAG &DAG,
42803                                           const X86Subtarget &Subtarget) {
42804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42805   unsigned Opc = V.getOpcode();
42806   switch (Opc) {
42807   case ISD::BITCAST: {
42808     // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
42809     SDValue Src = V.getOperand(0);
42810     EVT SrcVT = Src.getValueType();
42811     if (SrcVT.isVector() || SrcVT.isFloatingPoint())
42812       return DAG.getBitcast(VT, Src);
42813     break;
42814   }
42815   case ISD::TRUNCATE: {
42816     // If we find a suitable source, a truncated scalar becomes a subvector.
42817     SDValue Src = V.getOperand(0);
42818     EVT NewSrcVT =
42819         EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
42820     if (TLI.isTypeLegal(NewSrcVT))
42821       if (SDValue N0 =
42822               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
42823         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
42824                            DAG.getIntPtrConstant(0, DL));
42825     break;
42826   }
42827   case ISD::ANY_EXTEND:
42828   case ISD::ZERO_EXTEND: {
42829     // If we find a suitable source, an extended scalar becomes a subvector.
42830     SDValue Src = V.getOperand(0);
42831     EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
42832                                     Src.getScalarValueSizeInBits());
42833     if (TLI.isTypeLegal(NewSrcVT))
42834       if (SDValue N0 =
42835               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
42836         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
42837                            Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
42838                                                   : DAG.getConstant(0, DL, VT),
42839                            N0, DAG.getIntPtrConstant(0, DL));
42840     break;
42841   }
42842   case ISD::OR: {
42843     // If we find suitable sources, we can just move an OR to the vector domain.
42844     SDValue Src0 = V.getOperand(0);
42845     SDValue Src1 = V.getOperand(1);
42846     if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
42847       if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
42848         return DAG.getNode(Opc, DL, VT, N0, N1);
42849     break;
42850   }
42851   case ISD::SHL: {
42852     // If we find a suitable source, a SHL becomes a KSHIFTL.
42853     SDValue Src0 = V.getOperand(0);
42854     if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
42855         ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
42856       break;
42857 
42858     if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
42859       if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
42860         return DAG.getNode(
42861             X86ISD::KSHIFTL, DL, VT, N0,
42862             DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
42863     break;
42864   }
42865   }
42866   return SDValue();
42867 }
42868 
combineBitcast(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42869 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
42870                               TargetLowering::DAGCombinerInfo &DCI,
42871                               const X86Subtarget &Subtarget) {
42872   SDValue N0 = N->getOperand(0);
42873   EVT VT = N->getValueType(0);
42874   EVT SrcVT = N0.getValueType();
42875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42876 
42877   // Try to match patterns such as
42878   // (i16 bitcast (v16i1 x))
42879   // ->
42880   // (i16 movmsk (16i8 sext (v16i1 x)))
42881   // before the setcc result is scalarized on subtargets that don't have legal
42882   // vxi1 types.
42883   if (DCI.isBeforeLegalize()) {
42884     SDLoc dl(N);
42885     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
42886       return V;
42887 
42888     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
42889     // type, widen both sides to avoid a trip through memory.
42890     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
42891         Subtarget.hasAVX512()) {
42892       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
42893       N0 = DAG.getBitcast(MVT::v8i1, N0);
42894       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
42895                          DAG.getIntPtrConstant(0, dl));
42896     }
42897 
42898     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
42899     // type, widen both sides to avoid a trip through memory.
42900     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
42901         Subtarget.hasAVX512()) {
42902       // Use zeros for the widening if we already have some zeroes. This can
42903       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
42904       // stream of this.
42905       // FIXME: It might make sense to detect a concat_vectors with a mix of
42906       // zeroes and undef and turn it into insert_subvector for i1 vectors as
42907       // a separate combine. What we can't do is canonicalize the operands of
42908       // such a concat or we'll get into a loop with SimplifyDemandedBits.
42909       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
42910         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
42911         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
42912           SrcVT = LastOp.getValueType();
42913           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
42914           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
42915           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
42916           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
42917           N0 = DAG.getBitcast(MVT::i8, N0);
42918           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
42919         }
42920       }
42921 
42922       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
42923       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
42924       Ops[0] = N0;
42925       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
42926       N0 = DAG.getBitcast(MVT::i8, N0);
42927       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
42928     }
42929   } else {
42930     // If we're bitcasting from iX to vXi1, see if the integer originally
42931     // began as a vXi1 and whether we can remove the bitcast entirely.
42932     if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
42933         SrcVT.isScalarInteger() && TLI.isTypeLegal(VT)) {
42934       if (SDValue V =
42935               combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
42936         return V;
42937     }
42938   }
42939 
42940   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
42941   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
42942   // due to insert_subvector legalization on KNL. By promoting the copy to i16
42943   // we can help with known bits propagation from the vXi1 domain to the
42944   // scalar domain.
42945   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
42946       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42947       N0.getOperand(0).getValueType() == MVT::v16i1 &&
42948       isNullConstant(N0.getOperand(1)))
42949     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
42950                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
42951 
42952   // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
42953   // and the vbroadcast_load are both integer or both fp. In some cases this
42954   // will remove the bitcast entirely.
42955   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
42956        VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
42957     auto *BCast = cast<MemIntrinsicSDNode>(N0);
42958     unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
42959     unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
42960     // Don't swap i8/i16 since don't have fp types that size.
42961     if (MemSize >= 32) {
42962       MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
42963                                        : MVT::getIntegerVT(MemSize);
42964       MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
42965                                         : MVT::getIntegerVT(SrcVTSize);
42966       LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
42967 
42968       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
42969       SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
42970       SDValue ResNode =
42971           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
42972                                   MemVT, BCast->getMemOperand());
42973       DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
42974       return DAG.getBitcast(VT, ResNode);
42975     }
42976   }
42977 
42978   // Since MMX types are special and don't usually play with other vector types,
42979   // it's better to handle them early to be sure we emit efficient code by
42980   // avoiding store-load conversions.
42981   if (VT == MVT::x86mmx) {
42982     // Detect MMX constant vectors.
42983     APInt UndefElts;
42984     SmallVector<APInt, 1> EltBits;
42985     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
42986       SDLoc DL(N0);
42987       // Handle zero-extension of i32 with MOVD.
42988       if (EltBits[0].countl_zero() >= 32)
42989         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
42990                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
42991       // Else, bitcast to a double.
42992       // TODO - investigate supporting sext 32-bit immediates on x86_64.
42993       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
42994       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
42995     }
42996 
42997     // Detect bitcasts to x86mmx low word.
42998     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
42999         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
43000         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
43001       bool LowUndef = true, AllUndefOrZero = true;
43002       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
43003         SDValue Op = N0.getOperand(i);
43004         LowUndef &= Op.isUndef() || (i >= e/2);
43005         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
43006       }
43007       if (AllUndefOrZero) {
43008         SDValue N00 = N0.getOperand(0);
43009         SDLoc dl(N00);
43010         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
43011                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
43012         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
43013       }
43014     }
43015 
43016     // Detect bitcasts of 64-bit build vectors and convert to a
43017     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
43018     // lowest element.
43019     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
43020         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
43021          SrcVT == MVT::v8i8))
43022       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
43023 
43024     // Detect bitcasts between element or subvector extraction to x86mmx.
43025     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
43026          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
43027         isNullConstant(N0.getOperand(1))) {
43028       SDValue N00 = N0.getOperand(0);
43029       if (N00.getValueType().is128BitVector())
43030         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
43031                            DAG.getBitcast(MVT::v2i64, N00));
43032     }
43033 
43034     // Detect bitcasts from FP_TO_SINT to x86mmx.
43035     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
43036       SDLoc DL(N0);
43037       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
43038                                 DAG.getUNDEF(MVT::v2i32));
43039       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
43040                          DAG.getBitcast(MVT::v2i64, Res));
43041     }
43042   }
43043 
43044   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
43045   // most of these to scalar anyway.
43046   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
43047       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
43048       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
43049     return combinevXi1ConstantToInteger(N0, DAG);
43050   }
43051 
43052   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
43053       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
43054       isa<ConstantSDNode>(N0)) {
43055     auto *C = cast<ConstantSDNode>(N0);
43056     if (C->isAllOnes())
43057       return DAG.getConstant(1, SDLoc(N0), VT);
43058     if (C->isZero())
43059       return DAG.getConstant(0, SDLoc(N0), VT);
43060   }
43061 
43062   // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
43063   // Turn it into a sign bit compare that produces a k-register. This avoids
43064   // a trip through a GPR.
43065   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
43066       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
43067       isPowerOf2_32(VT.getVectorNumElements())) {
43068     unsigned NumElts = VT.getVectorNumElements();
43069     SDValue Src = N0;
43070 
43071     // Peek through truncate.
43072     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
43073       Src = N0.getOperand(0);
43074 
43075     if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
43076       SDValue MovmskIn = Src.getOperand(0);
43077       MVT MovmskVT = MovmskIn.getSimpleValueType();
43078       unsigned MovMskElts = MovmskVT.getVectorNumElements();
43079 
43080       // We allow extra bits of the movmsk to be used since they are known zero.
43081       // We can't convert a VPMOVMSKB without avx512bw.
43082       if (MovMskElts <= NumElts &&
43083           (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
43084         EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
43085         MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
43086         SDLoc dl(N);
43087         MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
43088         SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
43089                                    DAG.getConstant(0, dl, IntVT), ISD::SETLT);
43090         if (EVT(CmpVT) == VT)
43091           return Cmp;
43092 
43093         // Pad with zeroes up to original VT to replace the zeroes that were
43094         // being used from the MOVMSK.
43095         unsigned NumConcats = NumElts / MovMskElts;
43096         SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
43097         Ops[0] = Cmp;
43098         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
43099       }
43100     }
43101   }
43102 
43103   // Try to remove bitcasts from input and output of mask arithmetic to
43104   // remove GPR<->K-register crossings.
43105   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
43106     return V;
43107 
43108   // Convert a bitcasted integer logic operation that has one bitcasted
43109   // floating-point operand into a floating-point logic operation. This may
43110   // create a load of a constant, but that is cheaper than materializing the
43111   // constant in an integer register and transferring it to an SSE register or
43112   // transferring the SSE operand to integer register and back.
43113   unsigned FPOpcode;
43114   switch (N0.getOpcode()) {
43115     case ISD::AND: FPOpcode = X86ISD::FAND; break;
43116     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
43117     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
43118     default: return SDValue();
43119   }
43120 
43121   // Check if we have a bitcast from another integer type as well.
43122   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
43123         (Subtarget.hasSSE2() && VT == MVT::f64) ||
43124         (Subtarget.hasFP16() && VT == MVT::f16) ||
43125         (Subtarget.hasSSE2() && VT.isInteger() && VT.isVector() &&
43126          TLI.isTypeLegal(VT))))
43127     return SDValue();
43128 
43129   SDValue LogicOp0 = N0.getOperand(0);
43130   SDValue LogicOp1 = N0.getOperand(1);
43131   SDLoc DL0(N0);
43132 
43133   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
43134   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
43135       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).hasOneUse() &&
43136       LogicOp0.getOperand(0).getValueType() == VT &&
43137       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
43138     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
43139     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
43140     return DAG.getNode(Opcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
43141   }
43142   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
43143   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
43144       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).hasOneUse() &&
43145       LogicOp1.getOperand(0).getValueType() == VT &&
43146       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
43147     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
43148     unsigned Opcode = VT.isFloatingPoint() ? FPOpcode : N0.getOpcode();
43149     return DAG.getNode(Opcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
43150   }
43151 
43152   return SDValue();
43153 }
43154 
43155 // (mul (zext a), (sext, b))
detectExtMul(SelectionDAG & DAG,const SDValue & Mul,SDValue & Op0,SDValue & Op1)43156 static bool detectExtMul(SelectionDAG &DAG, const SDValue &Mul, SDValue &Op0,
43157                          SDValue &Op1) {
43158   Op0 = Mul.getOperand(0);
43159   Op1 = Mul.getOperand(1);
43160 
43161   // The operand1 should be signed extend
43162   if (Op0.getOpcode() == ISD::SIGN_EXTEND)
43163     std::swap(Op0, Op1);
43164 
43165   auto IsFreeTruncation = [](SDValue &Op) -> bool {
43166     if ((Op.getOpcode() == ISD::ZERO_EXTEND ||
43167          Op.getOpcode() == ISD::SIGN_EXTEND) &&
43168         Op.getOperand(0).getScalarValueSizeInBits() <= 8)
43169       return true;
43170 
43171     auto *BV = dyn_cast<BuildVectorSDNode>(Op);
43172     return (BV && BV->isConstant());
43173   };
43174 
43175   // (dpbusd (zext a), (sext, b)). Since the first operand should be unsigned
43176   // value, we need to check Op0 is zero extended value. Op1 should be signed
43177   // value, so we just check the signed bits.
43178   if ((IsFreeTruncation(Op0) &&
43179        DAG.computeKnownBits(Op0).countMaxActiveBits() <= 8) &&
43180       (IsFreeTruncation(Op1) && DAG.ComputeMaxSignificantBits(Op1) <= 8))
43181     return true;
43182 
43183   return false;
43184 }
43185 
43186 // Given a ABS node, detect the following pattern:
43187 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
43188 // This is useful as it is the input into a SAD pattern.
detectZextAbsDiff(const SDValue & Abs,SDValue & Op0,SDValue & Op1)43189 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
43190   SDValue AbsOp1 = Abs->getOperand(0);
43191   if (AbsOp1.getOpcode() != ISD::SUB)
43192     return false;
43193 
43194   Op0 = AbsOp1.getOperand(0);
43195   Op1 = AbsOp1.getOperand(1);
43196 
43197   // Check if the operands of the sub are zero-extended from vectors of i8.
43198   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
43199       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
43200       Op1.getOpcode() != ISD::ZERO_EXTEND ||
43201       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
43202     return false;
43203 
43204   return true;
43205 }
43206 
createVPDPBUSD(SelectionDAG & DAG,SDValue LHS,SDValue RHS,unsigned & LogBias,const SDLoc & DL,const X86Subtarget & Subtarget)43207 static SDValue createVPDPBUSD(SelectionDAG &DAG, SDValue LHS, SDValue RHS,
43208                               unsigned &LogBias, const SDLoc &DL,
43209                               const X86Subtarget &Subtarget) {
43210   // Extend or truncate to MVT::i8 first.
43211   MVT Vi8VT =
43212       MVT::getVectorVT(MVT::i8, LHS.getValueType().getVectorElementCount());
43213   LHS = DAG.getZExtOrTrunc(LHS, DL, Vi8VT);
43214   RHS = DAG.getSExtOrTrunc(RHS, DL, Vi8VT);
43215 
43216   // VPDPBUSD(<16 x i32>C, <16 x i8>A, <16 x i8>B). For each dst element
43217   // C[0] = C[0] + A[0]B[0] + A[1]B[1] + A[2]B[2] + A[3]B[3].
43218   // The src A, B element type is i8, but the dst C element type is i32.
43219   // When we calculate the reduce stage, we use src vector type vXi8 for it
43220   // so we need logbias 2 to avoid extra 2 stages.
43221   LogBias = 2;
43222 
43223   unsigned RegSize = std::max(128u, (unsigned)Vi8VT.getSizeInBits());
43224   if (Subtarget.hasVNNI() && !Subtarget.hasVLX())
43225     RegSize = std::max(512u, RegSize);
43226 
43227   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
43228   // fill in the missing vector elements with 0.
43229   unsigned NumConcat = RegSize / Vi8VT.getSizeInBits();
43230   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, Vi8VT));
43231   Ops[0] = LHS;
43232   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
43233   SDValue DpOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
43234   Ops[0] = RHS;
43235   SDValue DpOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
43236 
43237   // Actually build the DotProduct, split as 256/512 bits for
43238   // AVXVNNI/AVX512VNNI.
43239   auto DpBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43240                        ArrayRef<SDValue> Ops) {
43241     MVT VT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
43242     return DAG.getNode(X86ISD::VPDPBUSD, DL, VT, Ops);
43243   };
43244   MVT DpVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
43245   SDValue Zero = DAG.getConstant(0, DL, DpVT);
43246 
43247   return SplitOpsAndApply(DAG, Subtarget, DL, DpVT, {Zero, DpOp0, DpOp1},
43248                           DpBuilder, false);
43249 }
43250 
43251 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
43252 // to these zexts.
createPSADBW(SelectionDAG & DAG,const SDValue & Zext0,const SDValue & Zext1,const SDLoc & DL,const X86Subtarget & Subtarget)43253 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
43254                             const SDValue &Zext1, const SDLoc &DL,
43255                             const X86Subtarget &Subtarget) {
43256   // Find the appropriate width for the PSADBW.
43257   EVT InVT = Zext0.getOperand(0).getValueType();
43258   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
43259 
43260   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
43261   // fill in the missing vector elements with 0.
43262   unsigned NumConcat = RegSize / InVT.getSizeInBits();
43263   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
43264   Ops[0] = Zext0.getOperand(0);
43265   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
43266   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
43267   Ops[0] = Zext1.getOperand(0);
43268   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
43269 
43270   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
43271   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43272                           ArrayRef<SDValue> Ops) {
43273     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
43274     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
43275   };
43276   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
43277   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
43278                           PSADBWBuilder);
43279 }
43280 
43281 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
43282 // PHMINPOSUW.
combineMinMaxReduction(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)43283 static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
43284                                       const X86Subtarget &Subtarget) {
43285   // Bail without SSE41.
43286   if (!Subtarget.hasSSE41())
43287     return SDValue();
43288 
43289   EVT ExtractVT = Extract->getValueType(0);
43290   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
43291     return SDValue();
43292 
43293   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
43294   ISD::NodeType BinOp;
43295   SDValue Src = DAG.matchBinOpReduction(
43296       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
43297   if (!Src)
43298     return SDValue();
43299 
43300   EVT SrcVT = Src.getValueType();
43301   EVT SrcSVT = SrcVT.getScalarType();
43302   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
43303     return SDValue();
43304 
43305   SDLoc DL(Extract);
43306   SDValue MinPos = Src;
43307 
43308   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
43309   while (SrcVT.getSizeInBits() > 128) {
43310     SDValue Lo, Hi;
43311     std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
43312     SrcVT = Lo.getValueType();
43313     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
43314   }
43315   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
43316           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
43317          "Unexpected value type");
43318 
43319   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
43320   // to flip the value accordingly.
43321   SDValue Mask;
43322   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
43323   if (BinOp == ISD::SMAX)
43324     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
43325   else if (BinOp == ISD::SMIN)
43326     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
43327   else if (BinOp == ISD::UMAX)
43328     Mask = DAG.getAllOnesConstant(DL, SrcVT);
43329 
43330   if (Mask)
43331     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
43332 
43333   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
43334   // shuffling each upper element down and insert zeros. This means that the
43335   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
43336   // ready for the PHMINPOS.
43337   if (ExtractVT == MVT::i8) {
43338     SDValue Upper = DAG.getVectorShuffle(
43339         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
43340         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
43341     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
43342   }
43343 
43344   // Perform the PHMINPOS on a v8i16 vector,
43345   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
43346   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
43347   MinPos = DAG.getBitcast(SrcVT, MinPos);
43348 
43349   if (Mask)
43350     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
43351 
43352   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
43353                      DAG.getIntPtrConstant(0, DL));
43354 }
43355 
43356 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
combinePredicateReduction(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)43357 static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
43358                                          const X86Subtarget &Subtarget) {
43359   // Bail without SSE2.
43360   if (!Subtarget.hasSSE2())
43361     return SDValue();
43362 
43363   EVT ExtractVT = Extract->getValueType(0);
43364   unsigned BitWidth = ExtractVT.getSizeInBits();
43365   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
43366       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
43367     return SDValue();
43368 
43369   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
43370   ISD::NodeType BinOp;
43371   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
43372   if (!Match && ExtractVT == MVT::i1)
43373     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
43374   if (!Match)
43375     return SDValue();
43376 
43377   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
43378   // which we can't support here for now.
43379   if (Match.getScalarValueSizeInBits() != BitWidth)
43380     return SDValue();
43381 
43382   SDValue Movmsk;
43383   SDLoc DL(Extract);
43384   EVT MatchVT = Match.getValueType();
43385   unsigned NumElts = MatchVT.getVectorNumElements();
43386   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
43387   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43388   LLVMContext &Ctx = *DAG.getContext();
43389 
43390   if (ExtractVT == MVT::i1) {
43391     // Special case for (pre-legalization) vXi1 reductions.
43392     if (NumElts > 64 || !isPowerOf2_32(NumElts))
43393       return SDValue();
43394     if (Match.getOpcode() == ISD::SETCC) {
43395       ISD::CondCode CC = cast<CondCodeSDNode>(Match.getOperand(2))->get();
43396       if ((BinOp == ISD::AND && CC == ISD::CondCode::SETEQ) ||
43397           (BinOp == ISD::OR && CC == ISD::CondCode::SETNE)) {
43398         // For all_of(setcc(x,y,eq)) - use (iX)x == (iX)y.
43399         // For any_of(setcc(x,y,ne)) - use (iX)x != (iX)y.
43400         X86::CondCode X86CC;
43401         SDValue LHS = DAG.getFreeze(Match.getOperand(0));
43402         SDValue RHS = DAG.getFreeze(Match.getOperand(1));
43403         APInt Mask = APInt::getAllOnes(LHS.getScalarValueSizeInBits());
43404         if (SDValue V = LowerVectorAllEqual(DL, LHS, RHS, CC, Mask, Subtarget,
43405                                             DAG, X86CC))
43406           return DAG.getNode(ISD::TRUNCATE, DL, ExtractVT,
43407                              getSETCC(X86CC, V, DL, DAG));
43408       }
43409     }
43410     if (TLI.isTypeLegal(MatchVT)) {
43411       // If this is a legal AVX512 predicate type then we can just bitcast.
43412       EVT MovmskVT = EVT::getIntegerVT(Ctx, NumElts);
43413       Movmsk = DAG.getBitcast(MovmskVT, Match);
43414     } else {
43415       // Use combineBitcastvxi1 to create the MOVMSK.
43416       while (NumElts > MaxElts) {
43417         SDValue Lo, Hi;
43418         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
43419         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
43420         NumElts /= 2;
43421       }
43422       EVT MovmskVT = EVT::getIntegerVT(Ctx, NumElts);
43423       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
43424     }
43425     if (!Movmsk)
43426       return SDValue();
43427     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
43428   } else {
43429     // FIXME: Better handling of k-registers or 512-bit vectors?
43430     unsigned MatchSizeInBits = Match.getValueSizeInBits();
43431     if (!(MatchSizeInBits == 128 ||
43432           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
43433       return SDValue();
43434 
43435     // Make sure this isn't a vector of 1 element. The perf win from using
43436     // MOVMSK diminishes with less elements in the reduction, but it is
43437     // generally better to get the comparison over to the GPRs as soon as
43438     // possible to reduce the number of vector ops.
43439     if (Match.getValueType().getVectorNumElements() < 2)
43440       return SDValue();
43441 
43442     // Check that we are extracting a reduction of all sign bits.
43443     if (DAG.ComputeNumSignBits(Match) != BitWidth)
43444       return SDValue();
43445 
43446     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
43447       SDValue Lo, Hi;
43448       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
43449       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
43450       MatchSizeInBits = Match.getValueSizeInBits();
43451     }
43452 
43453     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
43454     MVT MaskSrcVT;
43455     if (64 == BitWidth || 32 == BitWidth)
43456       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
43457                                    MatchSizeInBits / BitWidth);
43458     else
43459       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
43460 
43461     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
43462     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
43463     NumElts = MaskSrcVT.getVectorNumElements();
43464   }
43465   assert((NumElts <= 32 || NumElts == 64) &&
43466          "Not expecting more than 64 elements");
43467 
43468   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
43469   if (BinOp == ISD::XOR) {
43470     // parity -> (PARITY(MOVMSK X))
43471     SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
43472     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
43473   }
43474 
43475   SDValue CmpC;
43476   ISD::CondCode CondCode;
43477   if (BinOp == ISD::OR) {
43478     // any_of -> MOVMSK != 0
43479     CmpC = DAG.getConstant(0, DL, CmpVT);
43480     CondCode = ISD::CondCode::SETNE;
43481   } else {
43482     // all_of -> MOVMSK == ((1 << NumElts) - 1)
43483     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
43484                            DL, CmpVT);
43485     CondCode = ISD::CondCode::SETEQ;
43486   }
43487 
43488   // The setcc produces an i8 of 0/1, so extend that to the result width and
43489   // negate to get the final 0/-1 mask value.
43490   EVT SetccVT = TLI.getSetCCResultType(DAG.getDataLayout(), Ctx, CmpVT);
43491   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
43492   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
43493   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
43494   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
43495 }
43496 
combineVPDPBUSDPattern(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)43497 static SDValue combineVPDPBUSDPattern(SDNode *Extract, SelectionDAG &DAG,
43498                                       const X86Subtarget &Subtarget) {
43499   if (!Subtarget.hasVNNI() && !Subtarget.hasAVXVNNI())
43500     return SDValue();
43501 
43502   EVT ExtractVT = Extract->getValueType(0);
43503   // Verify the type we're extracting is i32, as the output element type of
43504   // vpdpbusd is i32.
43505   if (ExtractVT != MVT::i32)
43506     return SDValue();
43507 
43508   EVT VT = Extract->getOperand(0).getValueType();
43509   if (!isPowerOf2_32(VT.getVectorNumElements()))
43510     return SDValue();
43511 
43512   // Match shuffle + add pyramid.
43513   ISD::NodeType BinOp;
43514   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
43515 
43516   // We can't combine to vpdpbusd for zext, because each of the 4 multiplies
43517   // done by vpdpbusd compute a signed 16-bit product that will be sign extended
43518   // before adding into the accumulator.
43519   // TODO:
43520   // We also need to verify that the multiply has at least 2x the number of bits
43521   // of the input. We shouldn't match
43522   // (sign_extend (mul (vXi9 (zext (vXi8 X))), (vXi9 (zext (vXi8 Y)))).
43523   // if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND))
43524   //   Root = Root.getOperand(0);
43525 
43526   // If there was a match, we want Root to be a mul.
43527   if (!Root || Root.getOpcode() != ISD::MUL)
43528     return SDValue();
43529 
43530   // Check whether we have an extend and mul pattern
43531   SDValue LHS, RHS;
43532   if (!detectExtMul(DAG, Root, LHS, RHS))
43533     return SDValue();
43534 
43535   // Create the dot product instruction.
43536   SDLoc DL(Extract);
43537   unsigned StageBias;
43538   SDValue DP = createVPDPBUSD(DAG, LHS, RHS, StageBias, DL, Subtarget);
43539 
43540   // If the original vector was wider than 4 elements, sum over the results
43541   // in the DP vector.
43542   unsigned Stages = Log2_32(VT.getVectorNumElements());
43543   EVT DpVT = DP.getValueType();
43544 
43545   if (Stages > StageBias) {
43546     unsigned DpElems = DpVT.getVectorNumElements();
43547 
43548     for (unsigned i = Stages - StageBias; i > 0; --i) {
43549       SmallVector<int, 16> Mask(DpElems, -1);
43550       for (unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
43551         Mask[j] = MaskEnd + j;
43552 
43553       SDValue Shuffle =
43554           DAG.getVectorShuffle(DpVT, DL, DP, DAG.getUNDEF(DpVT), Mask);
43555       DP = DAG.getNode(ISD::ADD, DL, DpVT, DP, Shuffle);
43556     }
43557   }
43558 
43559   // Return the lowest ExtractSizeInBits bits.
43560   EVT ResVT =
43561       EVT::getVectorVT(*DAG.getContext(), ExtractVT,
43562                        DpVT.getSizeInBits() / ExtractVT.getSizeInBits());
43563   DP = DAG.getBitcast(ResVT, DP);
43564   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, DP,
43565                      Extract->getOperand(1));
43566 }
43567 
combineBasicSADPattern(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)43568 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
43569                                       const X86Subtarget &Subtarget) {
43570   // PSADBW is only supported on SSE2 and up.
43571   if (!Subtarget.hasSSE2())
43572     return SDValue();
43573 
43574   EVT ExtractVT = Extract->getValueType(0);
43575   // Verify the type we're extracting is either i32 or i64.
43576   // FIXME: Could support other types, but this is what we have coverage for.
43577   if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
43578     return SDValue();
43579 
43580   EVT VT = Extract->getOperand(0).getValueType();
43581   if (!isPowerOf2_32(VT.getVectorNumElements()))
43582     return SDValue();
43583 
43584   // Match shuffle + add pyramid.
43585   ISD::NodeType BinOp;
43586   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
43587 
43588   // The operand is expected to be zero extended from i8
43589   // (verified in detectZextAbsDiff).
43590   // In order to convert to i64 and above, additional any/zero/sign
43591   // extend is expected.
43592   // The zero extend from 32 bit has no mathematical effect on the result.
43593   // Also the sign extend is basically zero extend
43594   // (extends the sign bit which is zero).
43595   // So it is correct to skip the sign/zero extend instruction.
43596   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
43597                Root.getOpcode() == ISD::ZERO_EXTEND ||
43598                Root.getOpcode() == ISD::ANY_EXTEND))
43599     Root = Root.getOperand(0);
43600 
43601   // If there was a match, we want Root to be a select that is the root of an
43602   // abs-diff pattern.
43603   if (!Root || Root.getOpcode() != ISD::ABS)
43604     return SDValue();
43605 
43606   // Check whether we have an abs-diff pattern feeding into the select.
43607   SDValue Zext0, Zext1;
43608   if (!detectZextAbsDiff(Root, Zext0, Zext1))
43609     return SDValue();
43610 
43611   // Create the SAD instruction.
43612   SDLoc DL(Extract);
43613   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
43614 
43615   // If the original vector was wider than 8 elements, sum over the results
43616   // in the SAD vector.
43617   unsigned Stages = Log2_32(VT.getVectorNumElements());
43618   EVT SadVT = SAD.getValueType();
43619   if (Stages > 3) {
43620     unsigned SadElems = SadVT.getVectorNumElements();
43621 
43622     for(unsigned i = Stages - 3; i > 0; --i) {
43623       SmallVector<int, 16> Mask(SadElems, -1);
43624       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
43625         Mask[j] = MaskEnd + j;
43626 
43627       SDValue Shuffle =
43628           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
43629       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
43630     }
43631   }
43632 
43633   unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
43634   // Return the lowest ExtractSizeInBits bits.
43635   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
43636                                SadVT.getSizeInBits() / ExtractSizeInBits);
43637   SAD = DAG.getBitcast(ResVT, SAD);
43638   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
43639                      Extract->getOperand(1));
43640 }
43641 
43642 // Attempt to peek through a target shuffle and extract the scalar from the
43643 // source.
combineExtractWithShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43644 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
43645                                          TargetLowering::DAGCombinerInfo &DCI,
43646                                          const X86Subtarget &Subtarget) {
43647   if (DCI.isBeforeLegalizeOps())
43648     return SDValue();
43649 
43650   SDLoc dl(N);
43651   SDValue Src = N->getOperand(0);
43652   SDValue Idx = N->getOperand(1);
43653 
43654   EVT VT = N->getValueType(0);
43655   EVT SrcVT = Src.getValueType();
43656   EVT SrcSVT = SrcVT.getVectorElementType();
43657   unsigned SrcEltBits = SrcSVT.getSizeInBits();
43658   unsigned NumSrcElts = SrcVT.getVectorNumElements();
43659 
43660   // Don't attempt this for boolean mask vectors or unknown extraction indices.
43661   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
43662     return SDValue();
43663 
43664   const APInt &IdxC = N->getConstantOperandAPInt(1);
43665   if (IdxC.uge(NumSrcElts))
43666     return SDValue();
43667 
43668   SDValue SrcBC = peekThroughBitcasts(Src);
43669 
43670   // Handle extract(bitcast(broadcast(scalar_value))).
43671   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
43672     SDValue SrcOp = SrcBC.getOperand(0);
43673     EVT SrcOpVT = SrcOp.getValueType();
43674     if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
43675         (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
43676       unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
43677       unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
43678       // TODO support non-zero offsets.
43679       if (Offset == 0) {
43680         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
43681         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
43682         return SrcOp;
43683       }
43684     }
43685   }
43686 
43687   // If we're extracting a single element from a broadcast load and there are
43688   // no other users, just create a single load.
43689   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
43690     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
43691     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
43692     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
43693         VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
43694       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
43695                                  MemIntr->getBasePtr(),
43696                                  MemIntr->getPointerInfo(),
43697                                  MemIntr->getOriginalAlign(),
43698                                  MemIntr->getMemOperand()->getFlags());
43699       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
43700       return Load;
43701     }
43702   }
43703 
43704   // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
43705   // TODO: Move to DAGCombine?
43706   if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
43707       SrcBC.getValueType().isInteger() &&
43708       (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
43709       SrcBC.getScalarValueSizeInBits() ==
43710           SrcBC.getOperand(0).getValueSizeInBits()) {
43711     unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
43712     if (IdxC.ult(Scale)) {
43713       unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
43714       SDValue Scl = SrcBC.getOperand(0);
43715       EVT SclVT = Scl.getValueType();
43716       if (Offset) {
43717         Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
43718                           DAG.getShiftAmountConstant(Offset, SclVT, dl));
43719       }
43720       Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
43721       Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
43722       return Scl;
43723     }
43724   }
43725 
43726   // Handle extract(truncate(x)) for 0'th index.
43727   // TODO: Treat this as a faux shuffle?
43728   // TODO: When can we use this for general indices?
43729   if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
43730       (SrcVT.getSizeInBits() % 128) == 0) {
43731     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
43732     MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
43733     return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
43734                        Idx);
43735   }
43736 
43737   // We can only legally extract other elements from 128-bit vectors and in
43738   // certain circumstances, depending on SSE-level.
43739   // TODO: Investigate float/double extraction if it will be just stored.
43740   auto GetLegalExtract = [&Subtarget, &DAG, &dl](SDValue Vec, EVT VecVT,
43741                                                  unsigned Idx) {
43742     EVT VecSVT = VecVT.getScalarType();
43743     if ((VecVT.is256BitVector() || VecVT.is512BitVector()) &&
43744         (VecSVT == MVT::i8 || VecSVT == MVT::i16 || VecSVT == MVT::i32 ||
43745          VecSVT == MVT::i64)) {
43746       unsigned EltSizeInBits = VecSVT.getSizeInBits();
43747       unsigned NumEltsPerLane = 128 / EltSizeInBits;
43748       unsigned LaneOffset = (Idx & ~(NumEltsPerLane - 1)) * EltSizeInBits;
43749       unsigned LaneIdx = LaneOffset / Vec.getScalarValueSizeInBits();
43750       VecVT = EVT::getVectorVT(*DAG.getContext(), VecSVT, NumEltsPerLane);
43751       Vec = extract128BitVector(Vec, LaneIdx, DAG, dl);
43752       Idx &= (NumEltsPerLane - 1);
43753     }
43754     if ((VecVT == MVT::v4i32 || VecVT == MVT::v2i64) &&
43755         ((Idx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
43756       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VecVT.getScalarType(),
43757                          DAG.getBitcast(VecVT, Vec),
43758                          DAG.getIntPtrConstant(Idx, dl));
43759     }
43760     if ((VecVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
43761         (VecVT == MVT::v16i8 && Subtarget.hasSSE41())) {
43762       unsigned OpCode = (VecVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
43763       return DAG.getNode(OpCode, dl, MVT::i32, DAG.getBitcast(VecVT, Vec),
43764                          DAG.getTargetConstant(Idx, dl, MVT::i8));
43765     }
43766     return SDValue();
43767   };
43768 
43769   // Resolve the target shuffle inputs and mask.
43770   SmallVector<int, 16> Mask;
43771   SmallVector<SDValue, 2> Ops;
43772   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
43773     return SDValue();
43774 
43775   // Shuffle inputs must be the same size as the result.
43776   if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
43777         return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
43778       }))
43779     return SDValue();
43780 
43781   // Attempt to narrow/widen the shuffle mask to the correct size.
43782   if (Mask.size() != NumSrcElts) {
43783     if ((NumSrcElts % Mask.size()) == 0) {
43784       SmallVector<int, 16> ScaledMask;
43785       int Scale = NumSrcElts / Mask.size();
43786       narrowShuffleMaskElts(Scale, Mask, ScaledMask);
43787       Mask = std::move(ScaledMask);
43788     } else if ((Mask.size() % NumSrcElts) == 0) {
43789       // Simplify Mask based on demanded element.
43790       int ExtractIdx = (int)IdxC.getZExtValue();
43791       int Scale = Mask.size() / NumSrcElts;
43792       int Lo = Scale * ExtractIdx;
43793       int Hi = Scale * (ExtractIdx + 1);
43794       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
43795         if (i < Lo || Hi <= i)
43796           Mask[i] = SM_SentinelUndef;
43797 
43798       SmallVector<int, 16> WidenedMask;
43799       while (Mask.size() > NumSrcElts &&
43800              canWidenShuffleElements(Mask, WidenedMask))
43801         Mask = std::move(WidenedMask);
43802     }
43803   }
43804 
43805   // If narrowing/widening failed, see if we can extract+zero-extend.
43806   int ExtractIdx;
43807   EVT ExtractVT;
43808   if (Mask.size() == NumSrcElts) {
43809     ExtractIdx = Mask[IdxC.getZExtValue()];
43810     ExtractVT = SrcVT;
43811   } else {
43812     unsigned Scale = Mask.size() / NumSrcElts;
43813     if ((Mask.size() % NumSrcElts) != 0 || SrcVT.isFloatingPoint())
43814       return SDValue();
43815     unsigned ScaledIdx = Scale * IdxC.getZExtValue();
43816     if (!isUndefOrZeroInRange(Mask, ScaledIdx + 1, Scale - 1))
43817       return SDValue();
43818     ExtractIdx = Mask[ScaledIdx];
43819     EVT ExtractSVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltBits / Scale);
43820     ExtractVT = EVT::getVectorVT(*DAG.getContext(), ExtractSVT, Mask.size());
43821     assert(SrcVT.getSizeInBits() == ExtractVT.getSizeInBits() &&
43822            "Failed to widen vector type");
43823   }
43824 
43825   // If the shuffle source element is undef/zero then we can just accept it.
43826   if (ExtractIdx == SM_SentinelUndef)
43827     return DAG.getUNDEF(VT);
43828 
43829   if (ExtractIdx == SM_SentinelZero)
43830     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
43831                                 : DAG.getConstant(0, dl, VT);
43832 
43833   SDValue SrcOp = Ops[ExtractIdx / Mask.size()];
43834   ExtractIdx = ExtractIdx % Mask.size();
43835   if (SDValue V = GetLegalExtract(SrcOp, ExtractVT, ExtractIdx))
43836     return DAG.getZExtOrTrunc(V, dl, VT);
43837 
43838   return SDValue();
43839 }
43840 
43841 /// Extracting a scalar FP value from vector element 0 is free, so extract each
43842 /// operand first, then perform the math as a scalar op.
scalarizeExtEltFP(SDNode * ExtElt,SelectionDAG & DAG,const X86Subtarget & Subtarget)43843 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG,
43844                                  const X86Subtarget &Subtarget) {
43845   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
43846   SDValue Vec = ExtElt->getOperand(0);
43847   SDValue Index = ExtElt->getOperand(1);
43848   EVT VT = ExtElt->getValueType(0);
43849   EVT VecVT = Vec.getValueType();
43850 
43851   // TODO: If this is a unary/expensive/expand op, allow extraction from a
43852   // non-zero element because the shuffle+scalar op will be cheaper?
43853   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
43854     return SDValue();
43855 
43856   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
43857   // extract, the condition code), so deal with those as a special-case.
43858   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
43859     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
43860     if (OpVT != MVT::f32 && OpVT != MVT::f64)
43861       return SDValue();
43862 
43863     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
43864     SDLoc DL(ExtElt);
43865     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
43866                                Vec.getOperand(0), Index);
43867     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
43868                                Vec.getOperand(1), Index);
43869     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
43870   }
43871 
43872   if (!(VT == MVT::f16 && Subtarget.hasFP16()) && VT != MVT::f32 &&
43873       VT != MVT::f64)
43874     return SDValue();
43875 
43876   // Vector FP selects don't fit the pattern of FP math ops (because the
43877   // condition has a different type and we have to change the opcode), so deal
43878   // with those here.
43879   // FIXME: This is restricted to pre type legalization by ensuring the setcc
43880   // has i1 elements. If we loosen this we need to convert vector bool to a
43881   // scalar bool.
43882   if (Vec.getOpcode() == ISD::VSELECT &&
43883       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
43884       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
43885       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
43886     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
43887     SDLoc DL(ExtElt);
43888     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
43889                                Vec.getOperand(0).getValueType().getScalarType(),
43890                                Vec.getOperand(0), Index);
43891     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
43892                                Vec.getOperand(1), Index);
43893     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
43894                                Vec.getOperand(2), Index);
43895     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
43896   }
43897 
43898   // TODO: This switch could include FNEG and the x86-specific FP logic ops
43899   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
43900   // missed load folding and fma+fneg combining.
43901   switch (Vec.getOpcode()) {
43902   case ISD::FMA: // Begin 3 operands
43903   case ISD::FMAD:
43904   case ISD::FADD: // Begin 2 operands
43905   case ISD::FSUB:
43906   case ISD::FMUL:
43907   case ISD::FDIV:
43908   case ISD::FREM:
43909   case ISD::FCOPYSIGN:
43910   case ISD::FMINNUM:
43911   case ISD::FMAXNUM:
43912   case ISD::FMINNUM_IEEE:
43913   case ISD::FMAXNUM_IEEE:
43914   case ISD::FMAXIMUM:
43915   case ISD::FMINIMUM:
43916   case X86ISD::FMAX:
43917   case X86ISD::FMIN:
43918   case ISD::FABS: // Begin 1 operand
43919   case ISD::FSQRT:
43920   case ISD::FRINT:
43921   case ISD::FCEIL:
43922   case ISD::FTRUNC:
43923   case ISD::FNEARBYINT:
43924   case ISD::FROUNDEVEN:
43925   case ISD::FROUND:
43926   case ISD::FFLOOR:
43927   case X86ISD::FRCP:
43928   case X86ISD::FRSQRT: {
43929     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
43930     SDLoc DL(ExtElt);
43931     SmallVector<SDValue, 4> ExtOps;
43932     for (SDValue Op : Vec->ops())
43933       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
43934     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
43935   }
43936   default:
43937     return SDValue();
43938   }
43939   llvm_unreachable("All opcodes should return within switch");
43940 }
43941 
43942 /// Try to convert a vector reduction sequence composed of binops and shuffles
43943 /// into horizontal ops.
combineArithReduction(SDNode * ExtElt,SelectionDAG & DAG,const X86Subtarget & Subtarget)43944 static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
43945                                      const X86Subtarget &Subtarget) {
43946   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
43947 
43948   // We need at least SSE2 to anything here.
43949   if (!Subtarget.hasSSE2())
43950     return SDValue();
43951 
43952   ISD::NodeType Opc;
43953   SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
43954                                         {ISD::ADD, ISD::MUL, ISD::FADD}, true);
43955   if (!Rdx)
43956     return SDValue();
43957 
43958   SDValue Index = ExtElt->getOperand(1);
43959   assert(isNullConstant(Index) &&
43960          "Reduction doesn't end in an extract from index 0");
43961 
43962   EVT VT = ExtElt->getValueType(0);
43963   EVT VecVT = Rdx.getValueType();
43964   if (VecVT.getScalarType() != VT)
43965     return SDValue();
43966 
43967   SDLoc DL(ExtElt);
43968   unsigned NumElts = VecVT.getVectorNumElements();
43969   unsigned EltSizeInBits = VecVT.getScalarSizeInBits();
43970 
43971   // Extend v4i8/v8i8 vector to v16i8, with undef upper 64-bits.
43972   auto WidenToV16I8 = [&](SDValue V, bool ZeroExtend) {
43973     if (V.getValueType() == MVT::v4i8) {
43974       if (ZeroExtend && Subtarget.hasSSE41()) {
43975         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
43976                         DAG.getConstant(0, DL, MVT::v4i32),
43977                         DAG.getBitcast(MVT::i32, V),
43978                         DAG.getIntPtrConstant(0, DL));
43979         return DAG.getBitcast(MVT::v16i8, V);
43980       }
43981       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, V,
43982                       ZeroExtend ? DAG.getConstant(0, DL, MVT::v4i8)
43983                                  : DAG.getUNDEF(MVT::v4i8));
43984     }
43985     return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V,
43986                        DAG.getUNDEF(MVT::v8i8));
43987   };
43988 
43989   // vXi8 mul reduction - promote to vXi16 mul reduction.
43990   if (Opc == ISD::MUL) {
43991     if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
43992       return SDValue();
43993     if (VecVT.getSizeInBits() >= 128) {
43994       EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
43995       SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
43996       SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
43997       Lo = DAG.getBitcast(WideVT, Lo);
43998       Hi = DAG.getBitcast(WideVT, Hi);
43999       Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
44000       while (Rdx.getValueSizeInBits() > 128) {
44001         std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
44002         Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
44003       }
44004     } else {
44005       Rdx = WidenToV16I8(Rdx, false);
44006       Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
44007       Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
44008     }
44009     if (NumElts >= 8)
44010       Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
44011                         DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
44012                                              {4, 5, 6, 7, -1, -1, -1, -1}));
44013     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
44014                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
44015                                            {2, 3, -1, -1, -1, -1, -1, -1}));
44016     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
44017                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
44018                                            {1, -1, -1, -1, -1, -1, -1, -1}));
44019     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
44020     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
44021   }
44022 
44023   // vXi8 add reduction - sub 128-bit vector.
44024   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
44025     Rdx = WidenToV16I8(Rdx, true);
44026     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
44027                       DAG.getConstant(0, DL, MVT::v16i8));
44028     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
44029     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
44030   }
44031 
44032   // Must be a >=128-bit vector with pow2 elements.
44033   if ((VecVT.getSizeInBits() % 128) != 0 || !isPowerOf2_32(NumElts))
44034     return SDValue();
44035 
44036   // vXi8 add reduction - sum lo/hi halves then use PSADBW.
44037   if (VT == MVT::i8) {
44038     while (Rdx.getValueSizeInBits() > 128) {
44039       SDValue Lo, Hi;
44040       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
44041       VecVT = Lo.getValueType();
44042       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
44043     }
44044     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
44045 
44046     SDValue Hi = DAG.getVectorShuffle(
44047         MVT::v16i8, DL, Rdx, Rdx,
44048         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
44049     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
44050     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
44051                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
44052     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
44053     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
44054   }
44055 
44056   // See if we can use vXi8 PSADBW add reduction for larger zext types.
44057   // If the source vector values are 0-255, then we can use PSADBW to
44058   // sum+zext v8i8 subvectors to vXi64, then perform the reduction.
44059   // TODO: See if its worth avoiding vXi16/i32 truncations?
44060   if (Opc == ISD::ADD && NumElts >= 4 && EltSizeInBits >= 16 &&
44061       DAG.computeKnownBits(Rdx).getMaxValue().ule(255) &&
44062       (EltSizeInBits == 16 || Rdx.getOpcode() == ISD::ZERO_EXTEND ||
44063        Subtarget.hasAVX512())) {
44064     if (Rdx.getValueType() == MVT::v8i16) {
44065       Rdx = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Rdx,
44066                         DAG.getUNDEF(MVT::v8i16));
44067     } else {
44068       EVT ByteVT = VecVT.changeVectorElementType(MVT::i8);
44069       Rdx = DAG.getNode(ISD::TRUNCATE, DL, ByteVT, Rdx);
44070       if (ByteVT.getSizeInBits() < 128)
44071         Rdx = WidenToV16I8(Rdx, true);
44072     }
44073 
44074     // Build the PSADBW, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
44075     auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44076                             ArrayRef<SDValue> Ops) {
44077       MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
44078       SDValue Zero = DAG.getConstant(0, DL, Ops[0].getValueType());
44079       return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops[0], Zero);
44080     };
44081     MVT SadVT = MVT::getVectorVT(MVT::i64, Rdx.getValueSizeInBits() / 64);
44082     Rdx = SplitOpsAndApply(DAG, Subtarget, DL, SadVT, {Rdx}, PSADBWBuilder);
44083 
44084     // TODO: We could truncate to vXi16/vXi32 before performing the reduction.
44085     while (Rdx.getValueSizeInBits() > 128) {
44086       SDValue Lo, Hi;
44087       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
44088       VecVT = Lo.getValueType();
44089       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
44090     }
44091     assert(Rdx.getValueType() == MVT::v2i64 && "v2i64 reduction expected");
44092 
44093     if (NumElts > 8) {
44094       SDValue RdxHi = DAG.getVectorShuffle(MVT::v2i64, DL, Rdx, Rdx, {1, -1});
44095       Rdx = DAG.getNode(ISD::ADD, DL, MVT::v2i64, Rdx, RdxHi);
44096     }
44097 
44098     VecVT = MVT::getVectorVT(VT.getSimpleVT(), 128 / VT.getSizeInBits());
44099     Rdx = DAG.getBitcast(VecVT, Rdx);
44100     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
44101   }
44102 
44103   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
44104   if (!shouldUseHorizontalOp(true, DAG, Subtarget))
44105     return SDValue();
44106 
44107   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
44108 
44109   // 256-bit horizontal instructions operate on 128-bit chunks rather than
44110   // across the whole vector, so we need an extract + hop preliminary stage.
44111   // This is the only step where the operands of the hop are not the same value.
44112   // TODO: We could extend this to handle 512-bit or even longer vectors.
44113   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
44114       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
44115     unsigned NumElts = VecVT.getVectorNumElements();
44116     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
44117     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
44118     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
44119     VecVT = Rdx.getValueType();
44120   }
44121   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
44122       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
44123     return SDValue();
44124 
44125   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
44126   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
44127   for (unsigned i = 0; i != ReductionSteps; ++i)
44128     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
44129 
44130   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
44131 }
44132 
44133 /// Detect vector gather/scatter index generation and convert it from being a
44134 /// bunch of shuffles and extracts into a somewhat faster sequence.
44135 /// For i686, the best sequence is apparently storing the value and loading
44136 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
combineExtractVectorElt(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44137 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
44138                                        TargetLowering::DAGCombinerInfo &DCI,
44139                                        const X86Subtarget &Subtarget) {
44140   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
44141     return NewOp;
44142 
44143   SDValue InputVector = N->getOperand(0);
44144   SDValue EltIdx = N->getOperand(1);
44145   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
44146 
44147   EVT SrcVT = InputVector.getValueType();
44148   EVT VT = N->getValueType(0);
44149   SDLoc dl(InputVector);
44150   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
44151   unsigned NumSrcElts = SrcVT.getVectorNumElements();
44152   unsigned NumEltBits = VT.getScalarSizeInBits();
44153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44154 
44155   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
44156     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
44157 
44158   // Integer Constant Folding.
44159   if (CIdx && VT.isInteger()) {
44160     APInt UndefVecElts;
44161     SmallVector<APInt, 16> EltBits;
44162     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
44163     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
44164                                       EltBits, true, false)) {
44165       uint64_t Idx = CIdx->getZExtValue();
44166       if (UndefVecElts[Idx])
44167         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
44168       return DAG.getConstant(EltBits[Idx].zext(NumEltBits), dl, VT);
44169     }
44170 
44171     // Convert extract_element(bitcast(<X x i1>) -> bitcast(extract_subvector()).
44172     // Improves lowering of bool masks on rust which splits them into byte array.
44173     if (InputVector.getOpcode() == ISD::BITCAST && (NumEltBits % 8) == 0) {
44174       SDValue Src = peekThroughBitcasts(InputVector);
44175       if (Src.getValueType().getScalarType() == MVT::i1 &&
44176           TLI.isTypeLegal(Src.getValueType())) {
44177         MVT SubVT = MVT::getVectorVT(MVT::i1, NumEltBits);
44178         SDValue Sub = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Src,
44179             DAG.getIntPtrConstant(CIdx->getZExtValue() * NumEltBits, dl));
44180         return DAG.getBitcast(VT, Sub);
44181       }
44182     }
44183   }
44184 
44185   if (IsPextr) {
44186     if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumEltBits),
44187                                  DCI))
44188       return SDValue(N, 0);
44189 
44190     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
44191     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
44192          InputVector.getOpcode() == X86ISD::PINSRW) &&
44193         InputVector.getOperand(2) == EltIdx) {
44194       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
44195              "Vector type mismatch");
44196       SDValue Scl = InputVector.getOperand(1);
44197       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
44198       return DAG.getZExtOrTrunc(Scl, dl, VT);
44199     }
44200 
44201     // TODO - Remove this once we can handle the implicit zero-extension of
44202     // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
44203     // combineBasicSADPattern.
44204     return SDValue();
44205   }
44206 
44207   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
44208   if (VT == MVT::i64 && SrcVT == MVT::v1i64 &&
44209       InputVector.getOpcode() == ISD::BITCAST &&
44210       InputVector.getOperand(0).getValueType() == MVT::x86mmx &&
44211       isNullConstant(EltIdx) && InputVector.hasOneUse())
44212     return DAG.getBitcast(VT, InputVector);
44213 
44214   // Detect mmx to i32 conversion through a v2i32 elt extract.
44215   if (VT == MVT::i32 && SrcVT == MVT::v2i32 &&
44216       InputVector.getOpcode() == ISD::BITCAST &&
44217       InputVector.getOperand(0).getValueType() == MVT::x86mmx &&
44218       isNullConstant(EltIdx) && InputVector.hasOneUse())
44219     return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32,
44220                        InputVector.getOperand(0));
44221 
44222   // Check whether this extract is the root of a sum of absolute differences
44223   // pattern. This has to be done here because we really want it to happen
44224   // pre-legalization,
44225   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
44226     return SAD;
44227 
44228   if (SDValue VPDPBUSD = combineVPDPBUSDPattern(N, DAG, Subtarget))
44229     return VPDPBUSD;
44230 
44231   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
44232   if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
44233     return Cmp;
44234 
44235   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
44236   if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
44237     return MinMax;
44238 
44239   // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
44240   if (SDValue V = combineArithReduction(N, DAG, Subtarget))
44241     return V;
44242 
44243   if (SDValue V = scalarizeExtEltFP(N, DAG, Subtarget))
44244     return V;
44245 
44246   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
44247   // and then testing the relevant element.
44248   //
44249   // Note that we only combine extracts on the *same* result number, i.e.
44250   //   t0 = merge_values a0, a1, a2, a3
44251   //   i1 = extract_vector_elt t0, Constant:i64<2>
44252   //   i1 = extract_vector_elt t0, Constant:i64<3>
44253   // but not
44254   //   i1 = extract_vector_elt t0:1, Constant:i64<2>
44255   // since the latter would need its own MOVMSK.
44256   if (SrcVT.getScalarType() == MVT::i1) {
44257     bool IsVar = !CIdx;
44258     SmallVector<SDNode *, 16> BoolExtracts;
44259     unsigned ResNo = InputVector.getResNo();
44260     auto IsBoolExtract = [&BoolExtracts, &ResNo, &IsVar](SDNode *Use) {
44261       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
44262           Use->getOperand(0).getResNo() == ResNo &&
44263           Use->getValueType(0) == MVT::i1) {
44264         BoolExtracts.push_back(Use);
44265         IsVar |= !isa<ConstantSDNode>(Use->getOperand(1));
44266         return true;
44267       }
44268       return false;
44269     };
44270     // TODO: Can we drop the oneuse check for constant extracts?
44271     if (all_of(InputVector->uses(), IsBoolExtract) &&
44272         (IsVar || BoolExtracts.size() > 1)) {
44273       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
44274       if (SDValue BC =
44275               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
44276         for (SDNode *Use : BoolExtracts) {
44277           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
44278           // Mask = 1 << MaskIdx
44279           SDValue MaskIdx = DAG.getZExtOrTrunc(Use->getOperand(1), dl, MVT::i8);
44280           SDValue MaskBit = DAG.getConstant(1, dl, BCVT);
44281           SDValue Mask = DAG.getNode(ISD::SHL, dl, BCVT, MaskBit, MaskIdx);
44282           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
44283           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
44284           DCI.CombineTo(Use, Res);
44285         }
44286         return SDValue(N, 0);
44287       }
44288     }
44289   }
44290 
44291   // If this extract is from a loaded vector value and will be used as an
44292   // integer, that requires a potentially expensive XMM -> GPR transfer.
44293   // Additionally, if we can convert to a scalar integer load, that will likely
44294   // be folded into a subsequent integer op.
44295   // Note: Unlike the related fold for this in DAGCombiner, this is not limited
44296   //       to a single-use of the loaded vector. For the reasons above, we
44297   //       expect this to be profitable even if it creates an extra load.
44298   bool LikelyUsedAsVector = any_of(N->uses(), [](SDNode *Use) {
44299     return Use->getOpcode() == ISD::STORE ||
44300            Use->getOpcode() == ISD::INSERT_VECTOR_ELT ||
44301            Use->getOpcode() == ISD::SCALAR_TO_VECTOR;
44302   });
44303   auto *LoadVec = dyn_cast<LoadSDNode>(InputVector);
44304   if (LoadVec && CIdx && ISD::isNormalLoad(LoadVec) && VT.isInteger() &&
44305       SrcVT.getVectorElementType() == VT && DCI.isAfterLegalizeDAG() &&
44306       !LikelyUsedAsVector && LoadVec->isSimple()) {
44307     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44308     SDValue NewPtr =
44309         TLI.getVectorElementPointer(DAG, LoadVec->getBasePtr(), SrcVT, EltIdx);
44310     unsigned PtrOff = VT.getSizeInBits() * CIdx->getZExtValue() / 8;
44311     MachinePointerInfo MPI = LoadVec->getPointerInfo().getWithOffset(PtrOff);
44312     Align Alignment = commonAlignment(LoadVec->getAlign(), PtrOff);
44313     SDValue Load =
44314         DAG.getLoad(VT, dl, LoadVec->getChain(), NewPtr, MPI, Alignment,
44315                     LoadVec->getMemOperand()->getFlags(), LoadVec->getAAInfo());
44316     DAG.makeEquivalentMemoryOrdering(LoadVec, Load);
44317     return Load;
44318   }
44319 
44320   return SDValue();
44321 }
44322 
44323 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
44324 // This is more or less the reverse of combineBitcastvxi1.
combineToExtendBoolVectorInReg(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue N0,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44325 static SDValue combineToExtendBoolVectorInReg(
44326     unsigned Opcode, const SDLoc &DL, EVT VT, SDValue N0, SelectionDAG &DAG,
44327     TargetLowering::DAGCombinerInfo &DCI, const X86Subtarget &Subtarget) {
44328   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
44329       Opcode != ISD::ANY_EXTEND)
44330     return SDValue();
44331   if (!DCI.isBeforeLegalizeOps())
44332     return SDValue();
44333   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
44334     return SDValue();
44335 
44336   EVT SVT = VT.getScalarType();
44337   EVT InSVT = N0.getValueType().getScalarType();
44338   unsigned EltSizeInBits = SVT.getSizeInBits();
44339 
44340   // Input type must be extending a bool vector (bit-casted from a scalar
44341   // integer) to legal integer types.
44342   if (!VT.isVector())
44343     return SDValue();
44344   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
44345     return SDValue();
44346   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
44347     return SDValue();
44348 
44349   SDValue N00 = N0.getOperand(0);
44350   EVT SclVT = N00.getValueType();
44351   if (!SclVT.isScalarInteger())
44352     return SDValue();
44353 
44354   SDValue Vec;
44355   SmallVector<int> ShuffleMask;
44356   unsigned NumElts = VT.getVectorNumElements();
44357   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
44358 
44359   // Broadcast the scalar integer to the vector elements.
44360   if (NumElts > EltSizeInBits) {
44361     // If the scalar integer is greater than the vector element size, then we
44362     // must split it down into sub-sections for broadcasting. For example:
44363     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
44364     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
44365     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
44366     unsigned Scale = NumElts / EltSizeInBits;
44367     EVT BroadcastVT = EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
44368     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
44369     Vec = DAG.getBitcast(VT, Vec);
44370 
44371     for (unsigned i = 0; i != Scale; ++i)
44372       ShuffleMask.append(EltSizeInBits, i);
44373     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
44374   } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
44375              (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
44376     // If we have register broadcast instructions, use the scalar size as the
44377     // element type for the shuffle. Then cast to the wider element type. The
44378     // widened bits won't be used, and this might allow the use of a broadcast
44379     // load.
44380     assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
44381     unsigned Scale = EltSizeInBits / NumElts;
44382     EVT BroadcastVT =
44383         EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
44384     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
44385     ShuffleMask.append(NumElts * Scale, 0);
44386     Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
44387     Vec = DAG.getBitcast(VT, Vec);
44388   } else {
44389     // For smaller scalar integers, we can simply any-extend it to the vector
44390     // element size (we don't care about the upper bits) and broadcast it to all
44391     // elements.
44392     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
44393     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
44394     ShuffleMask.append(NumElts, 0);
44395     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
44396   }
44397 
44398   // Now, mask the relevant bit in each element.
44399   SmallVector<SDValue, 32> Bits;
44400   for (unsigned i = 0; i != NumElts; ++i) {
44401     int BitIdx = (i % EltSizeInBits);
44402     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
44403     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
44404   }
44405   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
44406   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
44407 
44408   // Compare against the bitmask and extend the result.
44409   EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
44410   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
44411   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
44412 
44413   // For SEXT, this is now done, otherwise shift the result down for
44414   // zero-extension.
44415   if (Opcode == ISD::SIGN_EXTEND)
44416     return Vec;
44417   return DAG.getNode(ISD::SRL, DL, VT, Vec,
44418                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
44419 }
44420 
44421 /// If a vector select has an operand that is -1 or 0, try to simplify the
44422 /// select to a bitwise logic operation.
44423 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
44424 static SDValue
combineVSelectWithAllOnesOrZeros(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44425 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
44426                                  TargetLowering::DAGCombinerInfo &DCI,
44427                                  const X86Subtarget &Subtarget) {
44428   SDValue Cond = N->getOperand(0);
44429   SDValue LHS = N->getOperand(1);
44430   SDValue RHS = N->getOperand(2);
44431   EVT VT = LHS.getValueType();
44432   EVT CondVT = Cond.getValueType();
44433   SDLoc DL(N);
44434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44435 
44436   if (N->getOpcode() != ISD::VSELECT)
44437     return SDValue();
44438 
44439   assert(CondVT.isVector() && "Vector select expects a vector selector!");
44440 
44441   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
44442   // TODO: Can we assert that both operands are not zeros (because that should
44443   //       get simplified at node creation time)?
44444   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
44445   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
44446 
44447   // If both inputs are 0/undef, create a complete zero vector.
44448   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
44449   if (TValIsAllZeros && FValIsAllZeros) {
44450     if (VT.isFloatingPoint())
44451       return DAG.getConstantFP(0.0, DL, VT);
44452     return DAG.getConstant(0, DL, VT);
44453   }
44454 
44455   // To use the condition operand as a bitwise mask, it must have elements that
44456   // are the same size as the select elements. Ie, the condition operand must
44457   // have already been promoted from the IR select condition type <N x i1>.
44458   // Don't check if the types themselves are equal because that excludes
44459   // vector floating-point selects.
44460   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
44461     return SDValue();
44462 
44463   // Try to invert the condition if true value is not all 1s and false value is
44464   // not all 0s. Only do this if the condition has one use.
44465   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
44466   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
44467       // Check if the selector will be produced by CMPP*/PCMP*.
44468       Cond.getOpcode() == ISD::SETCC &&
44469       // Check if SETCC has already been promoted.
44470       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
44471           CondVT) {
44472     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
44473 
44474     if (TValIsAllZeros || FValIsAllOnes) {
44475       SDValue CC = Cond.getOperand(2);
44476       ISD::CondCode NewCC = ISD::getSetCCInverse(
44477           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
44478       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
44479                           NewCC);
44480       std::swap(LHS, RHS);
44481       TValIsAllOnes = FValIsAllOnes;
44482       FValIsAllZeros = TValIsAllZeros;
44483     }
44484   }
44485 
44486   // Cond value must be 'sign splat' to be converted to a logical op.
44487   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
44488     return SDValue();
44489 
44490   // vselect Cond, 111..., 000... -> Cond
44491   if (TValIsAllOnes && FValIsAllZeros)
44492     return DAG.getBitcast(VT, Cond);
44493 
44494   if (!TLI.isTypeLegal(CondVT))
44495     return SDValue();
44496 
44497   // vselect Cond, 111..., X -> or Cond, X
44498   if (TValIsAllOnes) {
44499     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
44500     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
44501     return DAG.getBitcast(VT, Or);
44502   }
44503 
44504   // vselect Cond, X, 000... -> and Cond, X
44505   if (FValIsAllZeros) {
44506     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
44507     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
44508     return DAG.getBitcast(VT, And);
44509   }
44510 
44511   // vselect Cond, 000..., X -> andn Cond, X
44512   if (TValIsAllZeros) {
44513     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
44514     SDValue AndN;
44515     // The canonical form differs for i1 vectors - x86andnp is not used
44516     if (CondVT.getScalarType() == MVT::i1)
44517       AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
44518                          CastRHS);
44519     else
44520       AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
44521     return DAG.getBitcast(VT, AndN);
44522   }
44523 
44524   return SDValue();
44525 }
44526 
44527 /// If both arms of a vector select are concatenated vectors, split the select,
44528 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
44529 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
44530 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
narrowVectorSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44531 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
44532                                   const X86Subtarget &Subtarget) {
44533   unsigned Opcode = N->getOpcode();
44534   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
44535     return SDValue();
44536 
44537   // TODO: Split 512-bit vectors too?
44538   EVT VT = N->getValueType(0);
44539   if (!VT.is256BitVector())
44540     return SDValue();
44541 
44542   // TODO: Split as long as any 2 of the 3 operands are concatenated?
44543   SDValue Cond = N->getOperand(0);
44544   SDValue TVal = N->getOperand(1);
44545   SDValue FVal = N->getOperand(2);
44546   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
44547       !isFreeToSplitVector(TVal.getNode(), DAG) ||
44548       !isFreeToSplitVector(FVal.getNode(), DAG))
44549     return SDValue();
44550 
44551   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
44552                             ArrayRef<SDValue> Ops) {
44553     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
44554   };
44555   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
44556                           makeBlend, /*CheckBWI*/ false);
44557 }
44558 
combineSelectOfTwoConstants(SDNode * N,SelectionDAG & DAG)44559 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
44560   SDValue Cond = N->getOperand(0);
44561   SDValue LHS = N->getOperand(1);
44562   SDValue RHS = N->getOperand(2);
44563   SDLoc DL(N);
44564 
44565   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
44566   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
44567   if (!TrueC || !FalseC)
44568     return SDValue();
44569 
44570   // Don't do this for crazy integer types.
44571   EVT VT = N->getValueType(0);
44572   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
44573     return SDValue();
44574 
44575   // We're going to use the condition bit in math or logic ops. We could allow
44576   // this with a wider condition value (post-legalization it becomes an i8),
44577   // but if nothing is creating selects that late, it doesn't matter.
44578   if (Cond.getValueType() != MVT::i1)
44579     return SDValue();
44580 
44581   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
44582   // 3, 5, or 9 with i32/i64, so those get transformed too.
44583   // TODO: For constants that overflow or do not differ by power-of-2 or small
44584   // multiplier, convert to 'and' + 'add'.
44585   const APInt &TrueVal = TrueC->getAPIntValue();
44586   const APInt &FalseVal = FalseC->getAPIntValue();
44587 
44588   // We have a more efficient lowering for "(X == 0) ? Y : -1" using SBB.
44589   if ((TrueVal.isAllOnes() || FalseVal.isAllOnes()) &&
44590       Cond.getOpcode() == ISD::SETCC && isNullConstant(Cond.getOperand(1))) {
44591     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
44592     if (CC == ISD::SETEQ || CC == ISD::SETNE)
44593       return SDValue();
44594   }
44595 
44596   bool OV;
44597   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
44598   if (OV)
44599     return SDValue();
44600 
44601   APInt AbsDiff = Diff.abs();
44602   if (AbsDiff.isPowerOf2() ||
44603       ((VT == MVT::i32 || VT == MVT::i64) &&
44604        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
44605 
44606     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
44607     // of the condition can usually be folded into a compare predicate, but even
44608     // without that, the sequence should be cheaper than a CMOV alternative.
44609     if (TrueVal.slt(FalseVal)) {
44610       Cond = DAG.getNOT(DL, Cond, MVT::i1);
44611       std::swap(TrueC, FalseC);
44612     }
44613 
44614     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
44615     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
44616 
44617     // Multiply condition by the difference if non-one.
44618     if (!AbsDiff.isOne())
44619       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
44620 
44621     // Add the base if non-zero.
44622     if (!FalseC->isZero())
44623       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
44624 
44625     return R;
44626   }
44627 
44628   return SDValue();
44629 }
44630 
44631 /// If this is a *dynamic* select (non-constant condition) and we can match
44632 /// this node with one of the variable blend instructions, restructure the
44633 /// condition so that blends can use the high (sign) bit of each element.
44634 /// This function will also call SimplifyDemandedBits on already created
44635 /// BLENDV to perform additional simplifications.
combineVSelectToBLENDV(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44636 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
44637                                       TargetLowering::DAGCombinerInfo &DCI,
44638                                       const X86Subtarget &Subtarget) {
44639   SDValue Cond = N->getOperand(0);
44640   if ((N->getOpcode() != ISD::VSELECT &&
44641        N->getOpcode() != X86ISD::BLENDV) ||
44642       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
44643     return SDValue();
44644 
44645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44646   unsigned BitWidth = Cond.getScalarValueSizeInBits();
44647   EVT VT = N->getValueType(0);
44648 
44649   // We can only handle the cases where VSELECT is directly legal on the
44650   // subtarget. We custom lower VSELECT nodes with constant conditions and
44651   // this makes it hard to see whether a dynamic VSELECT will correctly
44652   // lower, so we both check the operation's status and explicitly handle the
44653   // cases where a *dynamic* blend will fail even though a constant-condition
44654   // blend could be custom lowered.
44655   // FIXME: We should find a better way to handle this class of problems.
44656   // Potentially, we should combine constant-condition vselect nodes
44657   // pre-legalization into shuffles and not mark as many types as custom
44658   // lowered.
44659   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
44660     return SDValue();
44661   // FIXME: We don't support i16-element blends currently. We could and
44662   // should support them by making *all* the bits in the condition be set
44663   // rather than just the high bit and using an i8-element blend.
44664   if (VT.getVectorElementType() == MVT::i16)
44665     return SDValue();
44666   // Dynamic blending was only available from SSE4.1 onward.
44667   if (VT.is128BitVector() && !Subtarget.hasSSE41())
44668     return SDValue();
44669   // Byte blends are only available in AVX2
44670   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
44671     return SDValue();
44672   // There are no 512-bit blend instructions that use sign bits.
44673   if (VT.is512BitVector())
44674     return SDValue();
44675 
44676   // Don't optimize before the condition has been transformed to a legal type
44677   // and don't ever optimize vector selects that map to AVX512 mask-registers.
44678   if (BitWidth < 8 || BitWidth > 64)
44679     return SDValue();
44680 
44681   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
44682     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
44683          UI != UE; ++UI)
44684       if ((UI->getOpcode() != ISD::VSELECT &&
44685            UI->getOpcode() != X86ISD::BLENDV) ||
44686           UI.getOperandNo() != 0)
44687         return false;
44688 
44689     return true;
44690   };
44691 
44692   APInt DemandedBits(APInt::getSignMask(BitWidth));
44693 
44694   if (OnlyUsedAsSelectCond(Cond)) {
44695     KnownBits Known;
44696     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
44697                                           !DCI.isBeforeLegalizeOps());
44698     if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
44699       return SDValue();
44700 
44701     // If we changed the computation somewhere in the DAG, this change will
44702     // affect all users of Cond. Update all the nodes so that we do not use
44703     // the generic VSELECT anymore. Otherwise, we may perform wrong
44704     // optimizations as we messed with the actual expectation for the vector
44705     // boolean values.
44706     for (SDNode *U : Cond->uses()) {
44707       if (U->getOpcode() == X86ISD::BLENDV)
44708         continue;
44709 
44710       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
44711                                Cond, U->getOperand(1), U->getOperand(2));
44712       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
44713       DCI.AddToWorklist(U);
44714     }
44715     DCI.CommitTargetLoweringOpt(TLO);
44716     return SDValue(N, 0);
44717   }
44718 
44719   // Otherwise we can still at least try to simplify multiple use bits.
44720   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
44721       return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
44722                          N->getOperand(1), N->getOperand(2));
44723 
44724   return SDValue();
44725 }
44726 
44727 // Try to match:
44728 //   (or (and (M, (sub 0, X)), (pandn M, X)))
44729 // which is a special case of:
44730 //   (select M, (sub 0, X), X)
44731 // Per:
44732 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
44733 // We know that, if fNegate is 0 or 1:
44734 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
44735 //
44736 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
44737 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
44738 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
44739 // This lets us transform our vselect to:
44740 //   (add (xor X, M), (and M, 1))
44741 // And further to:
44742 //   (sub (xor X, M), M)
combineLogicBlendIntoConditionalNegate(EVT VT,SDValue Mask,SDValue X,SDValue Y,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)44743 static SDValue combineLogicBlendIntoConditionalNegate(
44744     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
44745     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
44746   EVT MaskVT = Mask.getValueType();
44747   assert(MaskVT.isInteger() &&
44748          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
44749          "Mask must be zero/all-bits");
44750 
44751   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
44752     return SDValue();
44753   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
44754     return SDValue();
44755 
44756   auto IsNegV = [](SDNode *N, SDValue V) {
44757     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
44758            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
44759   };
44760 
44761   SDValue V;
44762   if (IsNegV(Y.getNode(), X))
44763     V = X;
44764   else if (IsNegV(X.getNode(), Y))
44765     V = Y;
44766   else
44767     return SDValue();
44768 
44769   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
44770   SDValue SubOp2 = Mask;
44771 
44772   // If the negate was on the false side of the select, then
44773   // the operands of the SUB need to be swapped. PR 27251.
44774   // This is because the pattern being matched above is
44775   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
44776   // but if the pattern matched was
44777   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
44778   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
44779   // pattern also needs to be a negation of the replacement pattern above.
44780   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
44781   // sub accomplishes the negation of the replacement pattern.
44782   if (V == Y)
44783     std::swap(SubOp1, SubOp2);
44784 
44785   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
44786   return DAG.getBitcast(VT, Res);
44787 }
44788 
commuteSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44789 static SDValue commuteSelect(SDNode *N, SelectionDAG &DAG,
44790                                   const X86Subtarget &Subtarget) {
44791   if (!Subtarget.hasAVX512())
44792     return SDValue();
44793   if (N->getOpcode() != ISD::VSELECT)
44794     return SDValue();
44795 
44796   SDLoc DL(N);
44797   SDValue Cond = N->getOperand(0);
44798   SDValue LHS = N->getOperand(1);
44799   SDValue RHS = N->getOperand(2);
44800 
44801   if (canCombineAsMaskOperation(LHS, Subtarget))
44802     return SDValue();
44803 
44804   if (!canCombineAsMaskOperation(RHS, Subtarget))
44805     return SDValue();
44806 
44807   if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
44808     return SDValue();
44809 
44810   // Commute LHS and RHS to create opportunity to select mask instruction.
44811   // (vselect M, L, R) -> (vselect ~M, R, L)
44812   ISD::CondCode NewCC =
44813       ISD::getSetCCInverse(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
44814                            Cond.getOperand(0).getValueType());
44815   Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(), Cond.getOperand(0),
44816 		                        Cond.getOperand(1), NewCC);
44817   return DAG.getSelect(DL, LHS.getValueType(), Cond, RHS, LHS);
44818 }
44819 
44820 /// Do target-specific dag combines on SELECT and VSELECT nodes.
combineSelect(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44821 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
44822                              TargetLowering::DAGCombinerInfo &DCI,
44823                              const X86Subtarget &Subtarget) {
44824   SDLoc DL(N);
44825   SDValue Cond = N->getOperand(0);
44826   SDValue LHS = N->getOperand(1);
44827   SDValue RHS = N->getOperand(2);
44828 
44829   // Try simplification again because we use this function to optimize
44830   // BLENDV nodes that are not handled by the generic combiner.
44831   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
44832     return V;
44833 
44834   // When avx512 is available the lhs operand of select instruction can be
44835   // folded with mask instruction, while the rhs operand can't. Commute the
44836   // lhs and rhs of the select instruction to create the opportunity of
44837   // folding.
44838   if (SDValue V = commuteSelect(N, DAG, Subtarget))
44839     return V;
44840 
44841   EVT VT = LHS.getValueType();
44842   EVT CondVT = Cond.getValueType();
44843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44844   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
44845 
44846   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
44847   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
44848   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
44849   if (CondVT.isVector() && CondVT.isInteger() &&
44850       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
44851       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
44852       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
44853     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
44854                                                            DL, DAG, Subtarget))
44855       return V;
44856 
44857   // Convert vselects with constant condition into shuffles.
44858   if (CondConstantVector && DCI.isBeforeLegalizeOps() &&
44859       (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::BLENDV)) {
44860     SmallVector<int, 64> Mask;
44861     if (createShuffleMaskFromVSELECT(Mask, Cond,
44862                                      N->getOpcode() == X86ISD::BLENDV))
44863       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
44864   }
44865 
44866   // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
44867   // by forcing the unselected elements to zero.
44868   // TODO: Can we handle more shuffles with this?
44869   if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
44870       LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
44871       LHS.hasOneUse() && RHS.hasOneUse()) {
44872     MVT SimpleVT = VT.getSimpleVT();
44873     SmallVector<SDValue, 1> LHSOps, RHSOps;
44874     SmallVector<int, 64> LHSMask, RHSMask, CondMask;
44875     if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
44876         getTargetShuffleMask(LHS.getNode(), SimpleVT, true, LHSOps, LHSMask) &&
44877         getTargetShuffleMask(RHS.getNode(), SimpleVT, true, RHSOps, RHSMask)) {
44878       int NumElts = VT.getVectorNumElements();
44879       for (int i = 0; i != NumElts; ++i) {
44880         // getConstVector sets negative shuffle mask values as undef, so ensure
44881         // we hardcode SM_SentinelZero values to zero (0x80).
44882         if (CondMask[i] < NumElts) {
44883           LHSMask[i] = isUndefOrZero(LHSMask[i]) ? 0x80 : LHSMask[i];
44884           RHSMask[i] = 0x80;
44885         } else {
44886           LHSMask[i] = 0x80;
44887           RHSMask[i] = isUndefOrZero(RHSMask[i]) ? 0x80 : RHSMask[i];
44888         }
44889       }
44890       LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
44891                         getConstVector(LHSMask, SimpleVT, DAG, DL, true));
44892       RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
44893                         getConstVector(RHSMask, SimpleVT, DAG, DL, true));
44894       return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
44895     }
44896   }
44897 
44898   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
44899   // instructions match the semantics of the common C idiom x<y?x:y but not
44900   // x<=y?x:y, because of how they handle negative zero (which can be
44901   // ignored in unsafe-math mode).
44902   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
44903   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
44904       VT != MVT::f80 && VT != MVT::f128 && !isSoftF16(VT, Subtarget) &&
44905       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
44906       (Subtarget.hasSSE2() ||
44907        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
44908     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
44909 
44910     unsigned Opcode = 0;
44911     // Check for x CC y ? x : y.
44912     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
44913         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
44914       switch (CC) {
44915       default: break;
44916       case ISD::SETULT:
44917         // Converting this to a min would handle NaNs incorrectly, and swapping
44918         // the operands would cause it to handle comparisons between positive
44919         // and negative zero incorrectly.
44920         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
44921           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44922               !(DAG.isKnownNeverZeroFloat(LHS) ||
44923                 DAG.isKnownNeverZeroFloat(RHS)))
44924             break;
44925           std::swap(LHS, RHS);
44926         }
44927         Opcode = X86ISD::FMIN;
44928         break;
44929       case ISD::SETOLE:
44930         // Converting this to a min would handle comparisons between positive
44931         // and negative zero incorrectly.
44932         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44933             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
44934           break;
44935         Opcode = X86ISD::FMIN;
44936         break;
44937       case ISD::SETULE:
44938         // Converting this to a min would handle both negative zeros and NaNs
44939         // incorrectly, but we can swap the operands to fix both.
44940         std::swap(LHS, RHS);
44941         [[fallthrough]];
44942       case ISD::SETOLT:
44943       case ISD::SETLT:
44944       case ISD::SETLE:
44945         Opcode = X86ISD::FMIN;
44946         break;
44947 
44948       case ISD::SETOGE:
44949         // Converting this to a max would handle comparisons between positive
44950         // and negative zero incorrectly.
44951         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44952             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
44953           break;
44954         Opcode = X86ISD::FMAX;
44955         break;
44956       case ISD::SETUGT:
44957         // Converting this to a max would handle NaNs incorrectly, and swapping
44958         // the operands would cause it to handle comparisons between positive
44959         // and negative zero incorrectly.
44960         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
44961           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44962               !(DAG.isKnownNeverZeroFloat(LHS) ||
44963                 DAG.isKnownNeverZeroFloat(RHS)))
44964             break;
44965           std::swap(LHS, RHS);
44966         }
44967         Opcode = X86ISD::FMAX;
44968         break;
44969       case ISD::SETUGE:
44970         // Converting this to a max would handle both negative zeros and NaNs
44971         // incorrectly, but we can swap the operands to fix both.
44972         std::swap(LHS, RHS);
44973         [[fallthrough]];
44974       case ISD::SETOGT:
44975       case ISD::SETGT:
44976       case ISD::SETGE:
44977         Opcode = X86ISD::FMAX;
44978         break;
44979       }
44980     // Check for x CC y ? y : x -- a min/max with reversed arms.
44981     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
44982                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
44983       switch (CC) {
44984       default: break;
44985       case ISD::SETOGE:
44986         // Converting this to a min would handle comparisons between positive
44987         // and negative zero incorrectly, and swapping the operands would
44988         // cause it to handle NaNs incorrectly.
44989         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
44990             !(DAG.isKnownNeverZeroFloat(LHS) ||
44991               DAG.isKnownNeverZeroFloat(RHS))) {
44992           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
44993             break;
44994           std::swap(LHS, RHS);
44995         }
44996         Opcode = X86ISD::FMIN;
44997         break;
44998       case ISD::SETUGT:
44999         // Converting this to a min would handle NaNs incorrectly.
45000         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
45001           break;
45002         Opcode = X86ISD::FMIN;
45003         break;
45004       case ISD::SETUGE:
45005         // Converting this to a min would handle both negative zeros and NaNs
45006         // incorrectly, but we can swap the operands to fix both.
45007         std::swap(LHS, RHS);
45008         [[fallthrough]];
45009       case ISD::SETOGT:
45010       case ISD::SETGT:
45011       case ISD::SETGE:
45012         Opcode = X86ISD::FMIN;
45013         break;
45014 
45015       case ISD::SETULT:
45016         // Converting this to a max would handle NaNs incorrectly.
45017         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
45018           break;
45019         Opcode = X86ISD::FMAX;
45020         break;
45021       case ISD::SETOLE:
45022         // Converting this to a max would handle comparisons between positive
45023         // and negative zero incorrectly, and swapping the operands would
45024         // cause it to handle NaNs incorrectly.
45025         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
45026             !DAG.isKnownNeverZeroFloat(LHS) &&
45027             !DAG.isKnownNeverZeroFloat(RHS)) {
45028           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
45029             break;
45030           std::swap(LHS, RHS);
45031         }
45032         Opcode = X86ISD::FMAX;
45033         break;
45034       case ISD::SETULE:
45035         // Converting this to a max would handle both negative zeros and NaNs
45036         // incorrectly, but we can swap the operands to fix both.
45037         std::swap(LHS, RHS);
45038         [[fallthrough]];
45039       case ISD::SETOLT:
45040       case ISD::SETLT:
45041       case ISD::SETLE:
45042         Opcode = X86ISD::FMAX;
45043         break;
45044       }
45045     }
45046 
45047     if (Opcode)
45048       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
45049   }
45050 
45051   // Some mask scalar intrinsics rely on checking if only one bit is set
45052   // and implement it in C code like this:
45053   // A[0] = (U & 1) ? A[0] : W[0];
45054   // This creates some redundant instructions that break pattern matching.
45055   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
45056   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
45057       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
45058     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
45059     SDValue AndNode = Cond.getOperand(0);
45060     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
45061         isNullConstant(Cond.getOperand(1)) &&
45062         isOneConstant(AndNode.getOperand(1))) {
45063       // LHS and RHS swapped due to
45064       // setcc outputting 1 when AND resulted in 0 and vice versa.
45065       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
45066       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
45067     }
45068   }
45069 
45070   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
45071   // lowering on KNL. In this case we convert it to
45072   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
45073   // The same situation all vectors of i8 and i16 without BWI.
45074   // Make sure we extend these even before type legalization gets a chance to
45075   // split wide vectors.
45076   // Since SKX these selects have a proper lowering.
45077   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
45078       CondVT.getVectorElementType() == MVT::i1 &&
45079       (VT.getVectorElementType() == MVT::i8 ||
45080        VT.getVectorElementType() == MVT::i16)) {
45081     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
45082     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
45083   }
45084 
45085   // AVX512 - Extend select with zero to merge with target shuffle.
45086   // select(mask, extract_subvector(shuffle(x)), zero) -->
45087   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
45088   // TODO - support non target shuffles as well.
45089   if (Subtarget.hasAVX512() && CondVT.isVector() &&
45090       CondVT.getVectorElementType() == MVT::i1) {
45091     auto SelectableOp = [&TLI](SDValue Op) {
45092       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
45093              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
45094              isNullConstant(Op.getOperand(1)) &&
45095              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
45096              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
45097     };
45098 
45099     bool SelectableLHS = SelectableOp(LHS);
45100     bool SelectableRHS = SelectableOp(RHS);
45101     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
45102     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
45103 
45104     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
45105       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
45106                                 : RHS.getOperand(0).getValueType();
45107       EVT SrcCondVT = SrcVT.changeVectorElementType(MVT::i1);
45108       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
45109                             VT.getSizeInBits());
45110       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
45111                             VT.getSizeInBits());
45112       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
45113                          DAG.getUNDEF(SrcCondVT), Cond,
45114                          DAG.getIntPtrConstant(0, DL));
45115       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
45116       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
45117     }
45118   }
45119 
45120   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
45121     return V;
45122 
45123   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
45124       Cond.hasOneUse()) {
45125     EVT CondVT = Cond.getValueType();
45126     SDValue Cond0 = Cond.getOperand(0);
45127     SDValue Cond1 = Cond.getOperand(1);
45128     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
45129 
45130     // Canonicalize min/max:
45131     // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
45132     // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
45133     // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
45134     // the need for an extra compare against zero. e.g.
45135     // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
45136     // subl   %esi, %edi
45137     // testl  %edi, %edi
45138     // movl   $0, %eax
45139     // cmovgl %edi, %eax
45140     // =>
45141     // xorl   %eax, %eax
45142     // subl   %esi, $edi
45143     // cmovsl %eax, %edi
45144     //
45145     // We can also canonicalize
45146     //  (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
45147     //  (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
45148     // This allows the use of a test instruction for the compare.
45149     if (LHS == Cond0 && RHS == Cond1) {
45150       if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
45151           (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
45152         ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
45153         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
45154         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
45155       }
45156       if (CC == ISD::SETUGT && isOneConstant(RHS)) {
45157         ISD::CondCode NewCC = ISD::SETUGE;
45158         Cond = DAG.getSetCC(SDLoc(Cond), CondVT, Cond0, Cond1, NewCC);
45159         return DAG.getSelect(DL, VT, Cond, LHS, RHS);
45160       }
45161     }
45162 
45163     // Similar to DAGCombine's select(or(CC0,CC1),X,Y) fold but for legal types.
45164     // fold eq + gt/lt nested selects into ge/le selects
45165     // select (cmpeq Cond0, Cond1), LHS, (select (cmpugt Cond0, Cond1), LHS, Y)
45166     // --> (select (cmpuge Cond0, Cond1), LHS, Y)
45167     // select (cmpslt Cond0, Cond1), LHS, (select (cmpeq Cond0, Cond1), LHS, Y)
45168     // --> (select (cmpsle Cond0, Cond1), LHS, Y)
45169     // .. etc ..
45170     if (RHS.getOpcode() == ISD::SELECT && RHS.getOperand(1) == LHS &&
45171         RHS.getOperand(0).getOpcode() == ISD::SETCC) {
45172       SDValue InnerSetCC = RHS.getOperand(0);
45173       ISD::CondCode InnerCC =
45174           cast<CondCodeSDNode>(InnerSetCC.getOperand(2))->get();
45175       if ((CC == ISD::SETEQ || InnerCC == ISD::SETEQ) &&
45176           Cond0 == InnerSetCC.getOperand(0) &&
45177           Cond1 == InnerSetCC.getOperand(1)) {
45178         ISD::CondCode NewCC;
45179         switch (CC == ISD::SETEQ ? InnerCC : CC) {
45180         case ISD::SETGT:  NewCC = ISD::SETGE; break;
45181         case ISD::SETLT:  NewCC = ISD::SETLE; break;
45182         case ISD::SETUGT: NewCC = ISD::SETUGE; break;
45183         case ISD::SETULT: NewCC = ISD::SETULE; break;
45184         default: NewCC = ISD::SETCC_INVALID; break;
45185         }
45186         if (NewCC != ISD::SETCC_INVALID) {
45187           Cond = DAG.getSetCC(DL, CondVT, Cond0, Cond1, NewCC);
45188           return DAG.getSelect(DL, VT, Cond, LHS, RHS.getOperand(2));
45189         }
45190       }
45191     }
45192   }
45193 
45194   // Check if the first operand is all zeros and Cond type is vXi1.
45195   // If this an avx512 target we can improve the use of zero masking by
45196   // swapping the operands and inverting the condition.
45197   if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
45198       Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
45199       ISD::isBuildVectorAllZeros(LHS.getNode()) &&
45200       !ISD::isBuildVectorAllZeros(RHS.getNode())) {
45201     // Invert the cond to not(cond) : xor(op,allones)=not(op)
45202     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
45203     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
45204     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
45205   }
45206 
45207   // Attempt to convert a (vXi1 bitcast(iX Cond)) selection mask before it might
45208   // get split by legalization.
45209   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::BITCAST &&
45210       CondVT.getVectorElementType() == MVT::i1 &&
45211       TLI.isTypeLegal(VT.getScalarType())) {
45212     EVT ExtCondVT = VT.changeVectorElementTypeToInteger();
45213     if (SDValue ExtCond = combineToExtendBoolVectorInReg(
45214             ISD::SIGN_EXTEND, DL, ExtCondVT, Cond, DAG, DCI, Subtarget)) {
45215       ExtCond = DAG.getNode(ISD::TRUNCATE, DL, CondVT, ExtCond);
45216       return DAG.getSelect(DL, VT, ExtCond, LHS, RHS);
45217     }
45218   }
45219 
45220   // Early exit check
45221   if (!TLI.isTypeLegal(VT) || isSoftF16(VT, Subtarget))
45222     return SDValue();
45223 
45224   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
45225     return V;
45226 
45227   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
45228     return V;
45229 
45230   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
45231     return V;
45232 
45233   // select(~Cond, X, Y) -> select(Cond, Y, X)
45234   if (CondVT.getScalarType() != MVT::i1) {
45235     if (SDValue CondNot = IsNOT(Cond, DAG))
45236       return DAG.getNode(N->getOpcode(), DL, VT,
45237                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
45238 
45239     // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the
45240     // signbit.
45241     if (Cond.getOpcode() == X86ISD::PCMPGT &&
45242         ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode()) &&
45243         Cond.hasOneUse()) {
45244       Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
45245                          DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
45246       return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
45247     }
45248   }
45249 
45250   // Try to optimize vXi1 selects if both operands are either all constants or
45251   // bitcasts from scalar integer type. In that case we can convert the operands
45252   // to integer and use an integer select which will be converted to a CMOV.
45253   // We need to take a little bit of care to avoid creating an i64 type after
45254   // type legalization.
45255   if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
45256       VT.getVectorElementType() == MVT::i1 &&
45257       (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
45258     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
45259     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(IntVT)) {
45260       bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
45261       bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
45262 
45263       if ((LHSIsConst || (LHS.getOpcode() == ISD::BITCAST &&
45264                           LHS.getOperand(0).getValueType() == IntVT)) &&
45265           (RHSIsConst || (RHS.getOpcode() == ISD::BITCAST &&
45266                           RHS.getOperand(0).getValueType() == IntVT))) {
45267         if (LHSIsConst)
45268           LHS = combinevXi1ConstantToInteger(LHS, DAG);
45269         else
45270           LHS = LHS.getOperand(0);
45271 
45272         if (RHSIsConst)
45273           RHS = combinevXi1ConstantToInteger(RHS, DAG);
45274         else
45275           RHS = RHS.getOperand(0);
45276 
45277         SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
45278         return DAG.getBitcast(VT, Select);
45279       }
45280     }
45281   }
45282 
45283   // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
45284   // single bits, then invert the predicate and swap the select operands.
45285   // This can lower using a vector shift bit-hack rather than mask and compare.
45286   if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
45287       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
45288       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
45289       Cond.getOperand(0).getOpcode() == ISD::AND &&
45290       isNullOrNullSplat(Cond.getOperand(1)) &&
45291       cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
45292       Cond.getOperand(0).getValueType() == VT) {
45293     // The 'and' mask must be composed of power-of-2 constants.
45294     SDValue And = Cond.getOperand(0);
45295     auto *C = isConstOrConstSplat(And.getOperand(1));
45296     if (C && C->getAPIntValue().isPowerOf2()) {
45297       // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
45298       SDValue NotCond =
45299           DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
45300       return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
45301     }
45302 
45303     // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
45304     // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
45305     // 16-bit lacks a proper blendv.
45306     unsigned EltBitWidth = VT.getScalarSizeInBits();
45307     bool CanShiftBlend =
45308         TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
45309                                 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
45310                                 (Subtarget.hasXOP()));
45311     if (CanShiftBlend &&
45312         ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
45313           return C->getAPIntValue().isPowerOf2();
45314         })) {
45315       // Create a left-shift constant to get the mask bits over to the sign-bit.
45316       SDValue Mask = And.getOperand(1);
45317       SmallVector<int, 32> ShlVals;
45318       for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
45319         auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
45320         ShlVals.push_back(EltBitWidth - 1 -
45321                           MaskVal->getAPIntValue().exactLogBase2());
45322       }
45323       // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
45324       SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
45325       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
45326       SDValue NewCond =
45327           DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
45328       return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
45329     }
45330   }
45331 
45332   return SDValue();
45333 }
45334 
45335 /// Combine:
45336 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
45337 /// to:
45338 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
45339 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
45340 /// Note that this is only legal for some op/cc combinations.
combineSetCCAtomicArith(SDValue Cmp,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)45341 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
45342                                        SelectionDAG &DAG,
45343                                        const X86Subtarget &Subtarget) {
45344   // This combine only operates on CMP-like nodes.
45345   if (!(Cmp.getOpcode() == X86ISD::CMP ||
45346         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
45347     return SDValue();
45348 
45349   // Can't replace the cmp if it has more uses than the one we're looking at.
45350   // FIXME: We would like to be able to handle this, but would need to make sure
45351   // all uses were updated.
45352   if (!Cmp.hasOneUse())
45353     return SDValue();
45354 
45355   // This only applies to variations of the common case:
45356   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
45357   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
45358   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
45359   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
45360   // Using the proper condcodes (see below), overflow is checked for.
45361 
45362   // FIXME: We can generalize both constraints:
45363   // - XOR/OR/AND (if they were made to survive AtomicExpand)
45364   // - LHS != 1
45365   // if the result is compared.
45366 
45367   SDValue CmpLHS = Cmp.getOperand(0);
45368   SDValue CmpRHS = Cmp.getOperand(1);
45369   EVT CmpVT = CmpLHS.getValueType();
45370 
45371   if (!CmpLHS.hasOneUse())
45372     return SDValue();
45373 
45374   unsigned Opc = CmpLHS.getOpcode();
45375   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
45376     return SDValue();
45377 
45378   SDValue OpRHS = CmpLHS.getOperand(2);
45379   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
45380   if (!OpRHSC)
45381     return SDValue();
45382 
45383   APInt Addend = OpRHSC->getAPIntValue();
45384   if (Opc == ISD::ATOMIC_LOAD_SUB)
45385     Addend = -Addend;
45386 
45387   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
45388   if (!CmpRHSC)
45389     return SDValue();
45390 
45391   APInt Comparison = CmpRHSC->getAPIntValue();
45392   APInt NegAddend = -Addend;
45393 
45394   // See if we can adjust the CC to make the comparison match the negated
45395   // addend.
45396   if (Comparison != NegAddend) {
45397     APInt IncComparison = Comparison + 1;
45398     if (IncComparison == NegAddend) {
45399       if (CC == X86::COND_A && !Comparison.isMaxValue()) {
45400         Comparison = IncComparison;
45401         CC = X86::COND_AE;
45402       } else if (CC == X86::COND_LE && !Comparison.isMaxSignedValue()) {
45403         Comparison = IncComparison;
45404         CC = X86::COND_L;
45405       }
45406     }
45407     APInt DecComparison = Comparison - 1;
45408     if (DecComparison == NegAddend) {
45409       if (CC == X86::COND_AE && !Comparison.isMinValue()) {
45410         Comparison = DecComparison;
45411         CC = X86::COND_A;
45412       } else if (CC == X86::COND_L && !Comparison.isMinSignedValue()) {
45413         Comparison = DecComparison;
45414         CC = X86::COND_LE;
45415       }
45416     }
45417   }
45418 
45419   // If the addend is the negation of the comparison value, then we can do
45420   // a full comparison by emitting the atomic arithmetic as a locked sub.
45421   if (Comparison == NegAddend) {
45422     // The CC is fine, but we need to rewrite the LHS of the comparison as an
45423     // atomic sub.
45424     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
45425     auto AtomicSub = DAG.getAtomic(
45426         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpVT,
45427         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
45428         /*RHS*/ DAG.getConstant(NegAddend, SDLoc(CmpRHS), CmpVT),
45429         AN->getMemOperand());
45430     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
45431     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
45432     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
45433     return LockOp;
45434   }
45435 
45436   // We can handle comparisons with zero in a number of cases by manipulating
45437   // the CC used.
45438   if (!Comparison.isZero())
45439     return SDValue();
45440 
45441   if (CC == X86::COND_S && Addend == 1)
45442     CC = X86::COND_LE;
45443   else if (CC == X86::COND_NS && Addend == 1)
45444     CC = X86::COND_G;
45445   else if (CC == X86::COND_G && Addend == -1)
45446     CC = X86::COND_GE;
45447   else if (CC == X86::COND_LE && Addend == -1)
45448     CC = X86::COND_L;
45449   else
45450     return SDValue();
45451 
45452   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
45453   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0), DAG.getUNDEF(CmpVT));
45454   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
45455   return LockOp;
45456 }
45457 
45458 // Check whether a boolean test is testing a boolean value generated by
45459 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
45460 // code.
45461 //
45462 // Simplify the following patterns:
45463 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
45464 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
45465 // to (Op EFLAGS Cond)
45466 //
45467 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
45468 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
45469 // to (Op EFLAGS !Cond)
45470 //
45471 // where Op could be BRCOND or CMOV.
45472 //
checkBoolTestSetCCCombine(SDValue Cmp,X86::CondCode & CC)45473 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
45474   // This combine only operates on CMP-like nodes.
45475   if (!(Cmp.getOpcode() == X86ISD::CMP ||
45476         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
45477     return SDValue();
45478 
45479   // Quit if not used as a boolean value.
45480   if (CC != X86::COND_E && CC != X86::COND_NE)
45481     return SDValue();
45482 
45483   // Check CMP operands. One of them should be 0 or 1 and the other should be
45484   // an SetCC or extended from it.
45485   SDValue Op1 = Cmp.getOperand(0);
45486   SDValue Op2 = Cmp.getOperand(1);
45487 
45488   SDValue SetCC;
45489   const ConstantSDNode* C = nullptr;
45490   bool needOppositeCond = (CC == X86::COND_E);
45491   bool checkAgainstTrue = false; // Is it a comparison against 1?
45492 
45493   if ((C = dyn_cast<ConstantSDNode>(Op1)))
45494     SetCC = Op2;
45495   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
45496     SetCC = Op1;
45497   else // Quit if all operands are not constants.
45498     return SDValue();
45499 
45500   if (C->getZExtValue() == 1) {
45501     needOppositeCond = !needOppositeCond;
45502     checkAgainstTrue = true;
45503   } else if (C->getZExtValue() != 0)
45504     // Quit if the constant is neither 0 or 1.
45505     return SDValue();
45506 
45507   bool truncatedToBoolWithAnd = false;
45508   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
45509   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
45510          SetCC.getOpcode() == ISD::TRUNCATE ||
45511          SetCC.getOpcode() == ISD::AND) {
45512     if (SetCC.getOpcode() == ISD::AND) {
45513       int OpIdx = -1;
45514       if (isOneConstant(SetCC.getOperand(0)))
45515         OpIdx = 1;
45516       if (isOneConstant(SetCC.getOperand(1)))
45517         OpIdx = 0;
45518       if (OpIdx < 0)
45519         break;
45520       SetCC = SetCC.getOperand(OpIdx);
45521       truncatedToBoolWithAnd = true;
45522     } else
45523       SetCC = SetCC.getOperand(0);
45524   }
45525 
45526   switch (SetCC.getOpcode()) {
45527   case X86ISD::SETCC_CARRY:
45528     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
45529     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
45530     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
45531     // truncated to i1 using 'and'.
45532     if (checkAgainstTrue && !truncatedToBoolWithAnd)
45533       break;
45534     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
45535            "Invalid use of SETCC_CARRY!");
45536     [[fallthrough]];
45537   case X86ISD::SETCC:
45538     // Set the condition code or opposite one if necessary.
45539     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
45540     if (needOppositeCond)
45541       CC = X86::GetOppositeBranchCondition(CC);
45542     return SetCC.getOperand(1);
45543   case X86ISD::CMOV: {
45544     // Check whether false/true value has canonical one, i.e. 0 or 1.
45545     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
45546     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
45547     // Quit if true value is not a constant.
45548     if (!TVal)
45549       return SDValue();
45550     // Quit if false value is not a constant.
45551     if (!FVal) {
45552       SDValue Op = SetCC.getOperand(0);
45553       // Skip 'zext' or 'trunc' node.
45554       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
45555           Op.getOpcode() == ISD::TRUNCATE)
45556         Op = Op.getOperand(0);
45557       // A special case for rdrand/rdseed, where 0 is set if false cond is
45558       // found.
45559       if ((Op.getOpcode() != X86ISD::RDRAND &&
45560            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
45561         return SDValue();
45562     }
45563     // Quit if false value is not the constant 0 or 1.
45564     bool FValIsFalse = true;
45565     if (FVal && FVal->getZExtValue() != 0) {
45566       if (FVal->getZExtValue() != 1)
45567         return SDValue();
45568       // If FVal is 1, opposite cond is needed.
45569       needOppositeCond = !needOppositeCond;
45570       FValIsFalse = false;
45571     }
45572     // Quit if TVal is not the constant opposite of FVal.
45573     if (FValIsFalse && TVal->getZExtValue() != 1)
45574       return SDValue();
45575     if (!FValIsFalse && TVal->getZExtValue() != 0)
45576       return SDValue();
45577     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
45578     if (needOppositeCond)
45579       CC = X86::GetOppositeBranchCondition(CC);
45580     return SetCC.getOperand(3);
45581   }
45582   }
45583 
45584   return SDValue();
45585 }
45586 
45587 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
45588 /// Match:
45589 ///   (X86or (X86setcc) (X86setcc))
45590 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
checkBoolTestAndOrSetCCCombine(SDValue Cond,X86::CondCode & CC0,X86::CondCode & CC1,SDValue & Flags,bool & isAnd)45591 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
45592                                            X86::CondCode &CC1, SDValue &Flags,
45593                                            bool &isAnd) {
45594   if (Cond->getOpcode() == X86ISD::CMP) {
45595     if (!isNullConstant(Cond->getOperand(1)))
45596       return false;
45597 
45598     Cond = Cond->getOperand(0);
45599   }
45600 
45601   isAnd = false;
45602 
45603   SDValue SetCC0, SetCC1;
45604   switch (Cond->getOpcode()) {
45605   default: return false;
45606   case ISD::AND:
45607   case X86ISD::AND:
45608     isAnd = true;
45609     [[fallthrough]];
45610   case ISD::OR:
45611   case X86ISD::OR:
45612     SetCC0 = Cond->getOperand(0);
45613     SetCC1 = Cond->getOperand(1);
45614     break;
45615   };
45616 
45617   // Make sure we have SETCC nodes, using the same flags value.
45618   if (SetCC0.getOpcode() != X86ISD::SETCC ||
45619       SetCC1.getOpcode() != X86ISD::SETCC ||
45620       SetCC0->getOperand(1) != SetCC1->getOperand(1))
45621     return false;
45622 
45623   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
45624   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
45625   Flags = SetCC0->getOperand(1);
45626   return true;
45627 }
45628 
45629 // When legalizing carry, we create carries via add X, -1
45630 // If that comes from an actual carry, via setcc, we use the
45631 // carry directly.
combineCarryThroughADD(SDValue EFLAGS,SelectionDAG & DAG)45632 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
45633   if (EFLAGS.getOpcode() == X86ISD::ADD) {
45634     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
45635       bool FoundAndLSB = false;
45636       SDValue Carry = EFLAGS.getOperand(0);
45637       while (Carry.getOpcode() == ISD::TRUNCATE ||
45638              Carry.getOpcode() == ISD::ZERO_EXTEND ||
45639              (Carry.getOpcode() == ISD::AND &&
45640               isOneConstant(Carry.getOperand(1)))) {
45641         FoundAndLSB |= Carry.getOpcode() == ISD::AND;
45642         Carry = Carry.getOperand(0);
45643       }
45644       if (Carry.getOpcode() == X86ISD::SETCC ||
45645           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
45646         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
45647         uint64_t CarryCC = Carry.getConstantOperandVal(0);
45648         SDValue CarryOp1 = Carry.getOperand(1);
45649         if (CarryCC == X86::COND_B)
45650           return CarryOp1;
45651         if (CarryCC == X86::COND_A) {
45652           // Try to convert COND_A into COND_B in an attempt to facilitate
45653           // materializing "setb reg".
45654           //
45655           // Do not flip "e > c", where "c" is a constant, because Cmp
45656           // instruction cannot take an immediate as its first operand.
45657           //
45658           if (CarryOp1.getOpcode() == X86ISD::SUB &&
45659               CarryOp1.getNode()->hasOneUse() &&
45660               CarryOp1.getValueType().isInteger() &&
45661               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
45662             SDValue SubCommute =
45663                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
45664                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
45665             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
45666           }
45667         }
45668         // If this is a check of the z flag of an add with 1, switch to the
45669         // C flag.
45670         if (CarryCC == X86::COND_E &&
45671             CarryOp1.getOpcode() == X86ISD::ADD &&
45672             isOneConstant(CarryOp1.getOperand(1)))
45673           return CarryOp1;
45674       } else if (FoundAndLSB) {
45675         SDLoc DL(Carry);
45676         SDValue BitNo = DAG.getConstant(0, DL, Carry.getValueType());
45677         if (Carry.getOpcode() == ISD::SRL) {
45678           BitNo = Carry.getOperand(1);
45679           Carry = Carry.getOperand(0);
45680         }
45681         return getBT(Carry, BitNo, DL, DAG);
45682       }
45683     }
45684   }
45685 
45686   return SDValue();
45687 }
45688 
45689 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
45690 /// to avoid the inversion.
combinePTESTCC(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)45691 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
45692                               SelectionDAG &DAG,
45693                               const X86Subtarget &Subtarget) {
45694   // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
45695   if (EFLAGS.getOpcode() != X86ISD::PTEST &&
45696       EFLAGS.getOpcode() != X86ISD::TESTP)
45697     return SDValue();
45698 
45699   // PTEST/TESTP sets EFLAGS as:
45700   // TESTZ: ZF = (Op0 & Op1) == 0
45701   // TESTC: CF = (~Op0 & Op1) == 0
45702   // TESTNZC: ZF == 0 && CF == 0
45703   MVT VT = EFLAGS.getSimpleValueType();
45704   SDValue Op0 = EFLAGS.getOperand(0);
45705   SDValue Op1 = EFLAGS.getOperand(1);
45706   MVT OpVT = Op0.getSimpleValueType();
45707 
45708   // TEST*(~X,Y) == TEST*(X,Y)
45709   if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
45710     X86::CondCode InvCC;
45711     switch (CC) {
45712     case X86::COND_B:
45713       // testc -> testz.
45714       InvCC = X86::COND_E;
45715       break;
45716     case X86::COND_AE:
45717       // !testc -> !testz.
45718       InvCC = X86::COND_NE;
45719       break;
45720     case X86::COND_E:
45721       // testz -> testc.
45722       InvCC = X86::COND_B;
45723       break;
45724     case X86::COND_NE:
45725       // !testz -> !testc.
45726       InvCC = X86::COND_AE;
45727       break;
45728     case X86::COND_A:
45729     case X86::COND_BE:
45730       // testnzc -> testnzc (no change).
45731       InvCC = CC;
45732       break;
45733     default:
45734       InvCC = X86::COND_INVALID;
45735       break;
45736     }
45737 
45738     if (InvCC != X86::COND_INVALID) {
45739       CC = InvCC;
45740       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45741                          DAG.getBitcast(OpVT, NotOp0), Op1);
45742     }
45743   }
45744 
45745   if (CC == X86::COND_B || CC == X86::COND_AE) {
45746     // TESTC(X,~X) == TESTC(X,-1)
45747     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
45748       if (peekThroughBitcasts(NotOp1) == peekThroughBitcasts(Op0)) {
45749         SDLoc DL(EFLAGS);
45750         return DAG.getNode(
45751             EFLAGS.getOpcode(), DL, VT, DAG.getBitcast(OpVT, NotOp1),
45752             DAG.getBitcast(OpVT,
45753                            DAG.getAllOnesConstant(DL, NotOp1.getValueType())));
45754       }
45755     }
45756   }
45757 
45758   if (CC == X86::COND_E || CC == X86::COND_NE) {
45759     // TESTZ(X,~Y) == TESTC(Y,X)
45760     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
45761       CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
45762       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45763                          DAG.getBitcast(OpVT, NotOp1), Op0);
45764     }
45765 
45766     if (Op0 == Op1) {
45767       SDValue BC = peekThroughBitcasts(Op0);
45768       EVT BCVT = BC.getValueType();
45769 
45770       // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
45771       if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
45772         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45773                            DAG.getBitcast(OpVT, BC.getOperand(0)),
45774                            DAG.getBitcast(OpVT, BC.getOperand(1)));
45775       }
45776 
45777       // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
45778       if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
45779         CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
45780         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45781                            DAG.getBitcast(OpVT, BC.getOperand(0)),
45782                            DAG.getBitcast(OpVT, BC.getOperand(1)));
45783       }
45784 
45785       // If every element is an all-sign value, see if we can use TESTP/MOVMSK
45786       // to more efficiently extract the sign bits and compare that.
45787       // TODO: Handle TESTC with comparison inversion.
45788       // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
45789       // TESTP/MOVMSK combines to make sure its never worse than PTEST?
45790       if (BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT)) {
45791         unsigned EltBits = BCVT.getScalarSizeInBits();
45792         if (DAG.ComputeNumSignBits(BC) == EltBits) {
45793           assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
45794           APInt SignMask = APInt::getSignMask(EltBits);
45795           const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45796           if (SDValue Res =
45797                   TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
45798             // For vXi16 cases we need to use pmovmksb and extract every other
45799             // sign bit.
45800             SDLoc DL(EFLAGS);
45801             if ((EltBits == 32 || EltBits == 64) && Subtarget.hasAVX()) {
45802               MVT FloatSVT = MVT::getFloatingPointVT(EltBits);
45803               MVT FloatVT =
45804                   MVT::getVectorVT(FloatSVT, OpVT.getSizeInBits() / EltBits);
45805               Res = DAG.getBitcast(FloatVT, Res);
45806               return DAG.getNode(X86ISD::TESTP, SDLoc(EFLAGS), VT, Res, Res);
45807             } else if (EltBits == 16) {
45808               MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
45809               Res = DAG.getBitcast(MovmskVT, Res);
45810               Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
45811               Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
45812                                 DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
45813             } else {
45814               Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
45815             }
45816             return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
45817                                DAG.getConstant(0, DL, MVT::i32));
45818           }
45819         }
45820       }
45821     }
45822 
45823     // TESTZ(-1,X) == TESTZ(X,X)
45824     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
45825       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
45826 
45827     // TESTZ(X,-1) == TESTZ(X,X)
45828     if (ISD::isBuildVectorAllOnes(Op1.getNode()))
45829       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
45830 
45831     // TESTZ(OR(LO(X),HI(X)),OR(LO(Y),HI(Y))) -> TESTZ(X,Y)
45832     // TODO: Add COND_NE handling?
45833     if (CC == X86::COND_E && OpVT.is128BitVector() && Subtarget.hasAVX()) {
45834       SDValue Src0 = peekThroughBitcasts(Op0);
45835       SDValue Src1 = peekThroughBitcasts(Op1);
45836       if (Src0.getOpcode() == ISD::OR && Src1.getOpcode() == ISD::OR) {
45837         Src0 = getSplitVectorSrc(peekThroughBitcasts(Src0.getOperand(0)),
45838                                  peekThroughBitcasts(Src0.getOperand(1)), true);
45839         Src1 = getSplitVectorSrc(peekThroughBitcasts(Src1.getOperand(0)),
45840                                  peekThroughBitcasts(Src1.getOperand(1)), true);
45841         if (Src0 && Src1) {
45842           MVT OpVT2 = OpVT.getDoubleNumVectorElementsVT();
45843           return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
45844                              DAG.getBitcast(OpVT2, Src0),
45845                              DAG.getBitcast(OpVT2, Src1));
45846         }
45847       }
45848     }
45849   }
45850 
45851   return SDValue();
45852 }
45853 
45854 // Attempt to simplify the MOVMSK input based on the comparison type.
combineSetCCMOVMSK(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)45855 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
45856                                   SelectionDAG &DAG,
45857                                   const X86Subtarget &Subtarget) {
45858   // Handle eq/ne against zero (any_of).
45859   // Handle eq/ne against -1 (all_of).
45860   if (!(CC == X86::COND_E || CC == X86::COND_NE))
45861     return SDValue();
45862   if (EFLAGS.getValueType() != MVT::i32)
45863     return SDValue();
45864   unsigned CmpOpcode = EFLAGS.getOpcode();
45865   if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
45866     return SDValue();
45867   auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
45868   if (!CmpConstant)
45869     return SDValue();
45870   const APInt &CmpVal = CmpConstant->getAPIntValue();
45871 
45872   SDValue CmpOp = EFLAGS.getOperand(0);
45873   unsigned CmpBits = CmpOp.getValueSizeInBits();
45874   assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
45875 
45876   // Peek through any truncate.
45877   if (CmpOp.getOpcode() == ISD::TRUNCATE)
45878     CmpOp = CmpOp.getOperand(0);
45879 
45880   // Bail if we don't find a MOVMSK.
45881   if (CmpOp.getOpcode() != X86ISD::MOVMSK)
45882     return SDValue();
45883 
45884   SDValue Vec = CmpOp.getOperand(0);
45885   MVT VecVT = Vec.getSimpleValueType();
45886   assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
45887          "Unexpected MOVMSK operand");
45888   unsigned NumElts = VecVT.getVectorNumElements();
45889   unsigned NumEltBits = VecVT.getScalarSizeInBits();
45890 
45891   bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isZero();
45892   bool IsAllOf = (CmpOpcode == X86ISD::SUB || CmpOpcode == X86ISD::CMP) &&
45893                  NumElts <= CmpBits && CmpVal.isMask(NumElts);
45894   if (!IsAnyOf && !IsAllOf)
45895     return SDValue();
45896 
45897   // TODO: Check more combining cases for me.
45898   // Here we check the cmp use number to decide do combining or not.
45899   // Currently we only get 2 tests about combining "MOVMSK(CONCAT(..))"
45900   // and "MOVMSK(PCMPEQ(..))" are fit to use this constraint.
45901   bool IsOneUse = CmpOp.getNode()->hasOneUse();
45902 
45903   // See if we can peek through to a vector with a wider element type, if the
45904   // signbits extend down to all the sub-elements as well.
45905   // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
45906   // potential SimplifyDemandedBits/Elts cases.
45907   // If we looked through a truncate that discard bits, we can't do this
45908   // transform.
45909   // FIXME: We could do this transform for truncates that discarded bits by
45910   // inserting an AND mask between the new MOVMSK and the CMP.
45911   if (Vec.getOpcode() == ISD::BITCAST && NumElts <= CmpBits) {
45912     SDValue BC = peekThroughBitcasts(Vec);
45913     MVT BCVT = BC.getSimpleValueType();
45914     unsigned BCNumElts = BCVT.getVectorNumElements();
45915     unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
45916     if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
45917         BCNumEltBits > NumEltBits &&
45918         DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
45919       SDLoc DL(EFLAGS);
45920       APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : BCNumElts);
45921       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
45922                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
45923                          DAG.getConstant(CmpMask, DL, MVT::i32));
45924     }
45925   }
45926 
45927   // MOVMSK(CONCAT(X,Y)) == 0 ->  MOVMSK(OR(X,Y)).
45928   // MOVMSK(CONCAT(X,Y)) != 0 ->  MOVMSK(OR(X,Y)).
45929   // MOVMSK(CONCAT(X,Y)) == -1 ->  MOVMSK(AND(X,Y)).
45930   // MOVMSK(CONCAT(X,Y)) != -1 ->  MOVMSK(AND(X,Y)).
45931   if (VecVT.is256BitVector() && NumElts <= CmpBits && IsOneUse) {
45932     SmallVector<SDValue> Ops;
45933     if (collectConcatOps(peekThroughBitcasts(Vec).getNode(), Ops, DAG) &&
45934         Ops.size() == 2) {
45935       SDLoc DL(EFLAGS);
45936       EVT SubVT = Ops[0].getValueType().changeTypeToInteger();
45937       APInt CmpMask = APInt::getLowBitsSet(32, IsAnyOf ? 0 : NumElts / 2);
45938       SDValue V = DAG.getNode(IsAnyOf ? ISD::OR : ISD::AND, DL, SubVT,
45939                               DAG.getBitcast(SubVT, Ops[0]),
45940                               DAG.getBitcast(SubVT, Ops[1]));
45941       V = DAG.getBitcast(VecVT.getHalfNumVectorElementsVT(), V);
45942       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
45943                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V),
45944                          DAG.getConstant(CmpMask, DL, MVT::i32));
45945     }
45946   }
45947 
45948   // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
45949   // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
45950   // MOVMSK(PCMPEQ(X,Y)) == -1 -> PTESTZ(XOR(X,Y),XOR(X,Y)).
45951   // MOVMSK(PCMPEQ(X,Y)) != -1 -> !PTESTZ(XOR(X,Y),XOR(X,Y)).
45952   if (IsAllOf && Subtarget.hasSSE41() && IsOneUse) {
45953     MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
45954     SDValue BC = peekThroughBitcasts(Vec);
45955     // Ensure MOVMSK was testing every signbit of BC.
45956     if (BC.getValueType().getVectorNumElements() <= NumElts) {
45957       if (BC.getOpcode() == X86ISD::PCMPEQ) {
45958         SDValue V = DAG.getNode(ISD::XOR, SDLoc(BC), BC.getValueType(),
45959                                 BC.getOperand(0), BC.getOperand(1));
45960         V = DAG.getBitcast(TestVT, V);
45961         return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
45962       }
45963       // Check for 256-bit split vector cases.
45964       if (BC.getOpcode() == ISD::AND &&
45965           BC.getOperand(0).getOpcode() == X86ISD::PCMPEQ &&
45966           BC.getOperand(1).getOpcode() == X86ISD::PCMPEQ) {
45967         SDValue LHS = BC.getOperand(0);
45968         SDValue RHS = BC.getOperand(1);
45969         LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), LHS.getValueType(),
45970                           LHS.getOperand(0), LHS.getOperand(1));
45971         RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), RHS.getValueType(),
45972                           RHS.getOperand(0), RHS.getOperand(1));
45973         LHS = DAG.getBitcast(TestVT, LHS);
45974         RHS = DAG.getBitcast(TestVT, RHS);
45975         SDValue V = DAG.getNode(ISD::OR, SDLoc(EFLAGS), TestVT, LHS, RHS);
45976         return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
45977       }
45978     }
45979   }
45980 
45981   // See if we can avoid a PACKSS by calling MOVMSK on the sources.
45982   // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
45983   // sign bits prior to the comparison with zero unless we know that
45984   // the vXi16 splats the sign bit down to the lower i8 half.
45985   // TODO: Handle all_of patterns.
45986   if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
45987     SDValue VecOp0 = Vec.getOperand(0);
45988     SDValue VecOp1 = Vec.getOperand(1);
45989     bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
45990     bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
45991     // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
45992     if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
45993       SDLoc DL(EFLAGS);
45994       SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
45995       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
45996       Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
45997       if (!SignExt0) {
45998         Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
45999                              DAG.getConstant(0xAAAA, DL, MVT::i16));
46000       }
46001       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
46002                          DAG.getConstant(0, DL, MVT::i16));
46003     }
46004     // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
46005     // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
46006     if (CmpBits >= 16 && Subtarget.hasInt256() &&
46007         (IsAnyOf || (SignExt0 && SignExt1))) {
46008       if (SDValue Src = getSplitVectorSrc(VecOp0, VecOp1, true)) {
46009         SDLoc DL(EFLAGS);
46010         SDValue Result = peekThroughBitcasts(Src);
46011         if (IsAllOf && Result.getOpcode() == X86ISD::PCMPEQ &&
46012             Result.getValueType().getVectorNumElements() <= NumElts) {
46013           SDValue V = DAG.getNode(ISD::XOR, DL, Result.getValueType(),
46014                                   Result.getOperand(0), Result.getOperand(1));
46015           V = DAG.getBitcast(MVT::v4i64, V);
46016           return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
46017         }
46018         Result = DAG.getBitcast(MVT::v32i8, Result);
46019         Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
46020         unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
46021         if (!SignExt0 || !SignExt1) {
46022           assert(IsAnyOf &&
46023                  "Only perform v16i16 signmasks for any_of patterns");
46024           Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
46025                                DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
46026         }
46027         return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
46028                            DAG.getConstant(CmpMask, DL, MVT::i32));
46029       }
46030     }
46031   }
46032 
46033   // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
46034   // Since we peek through a bitcast, we need to be careful if the base vector
46035   // type has smaller elements than the MOVMSK type.  In that case, even if
46036   // all the elements are demanded by the shuffle mask, only the "high"
46037   // elements which have highbits that align with highbits in the MOVMSK vec
46038   // elements are actually demanded. A simplification of spurious operations
46039   // on the "low" elements take place during other simplifications.
46040   //
46041   // For example:
46042   // MOVMSK64(BITCAST(SHUF32 X, (1,0,3,2))) even though all the elements are
46043   // demanded, because we are swapping around the result can change.
46044   //
46045   // To address this, we check that we can scale the shuffle mask to MOVMSK
46046   // element width (this will ensure "high" elements match). Its slightly overly
46047   // conservative, but fine for an edge case fold.
46048   SmallVector<int, 32> ShuffleMask, ScaledMaskUnused;
46049   SmallVector<SDValue, 2> ShuffleInputs;
46050   if (NumElts <= CmpBits &&
46051       getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
46052                              ShuffleMask, DAG) &&
46053       ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
46054       ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits() &&
46055       scaleShuffleElements(ShuffleMask, NumElts, ScaledMaskUnused)) {
46056     unsigned NumShuffleElts = ShuffleMask.size();
46057     APInt DemandedElts = APInt::getZero(NumShuffleElts);
46058     for (int M : ShuffleMask) {
46059       assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index");
46060       DemandedElts.setBit(M);
46061     }
46062     if (DemandedElts.isAllOnes()) {
46063       SDLoc DL(EFLAGS);
46064       SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
46065       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
46066       Result =
46067           DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
46068       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
46069                          EFLAGS.getOperand(1));
46070     }
46071   }
46072 
46073   // MOVMSKPS(V) !=/== 0 -> TESTPS(V,V)
46074   // MOVMSKPD(V) !=/== 0 -> TESTPD(V,V)
46075   // MOVMSKPS(V) !=/== -1 -> TESTPS(V,V)
46076   // MOVMSKPD(V) !=/== -1 -> TESTPD(V,V)
46077   // iff every element is referenced.
46078   if (NumElts <= CmpBits && Subtarget.hasAVX() &&
46079       !Subtarget.preferMovmskOverVTest() && IsOneUse &&
46080       (NumEltBits == 32 || NumEltBits == 64)) {
46081     SDLoc DL(EFLAGS);
46082     MVT FloatSVT = MVT::getFloatingPointVT(NumEltBits);
46083     MVT FloatVT = MVT::getVectorVT(FloatSVT, NumElts);
46084     MVT IntVT = FloatVT.changeVectorElementTypeToInteger();
46085     SDValue LHS = Vec;
46086     SDValue RHS = IsAnyOf ? Vec : DAG.getAllOnesConstant(DL, IntVT);
46087     CC = IsAnyOf ? CC : (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
46088     return DAG.getNode(X86ISD::TESTP, DL, MVT::i32,
46089                        DAG.getBitcast(FloatVT, LHS),
46090                        DAG.getBitcast(FloatVT, RHS));
46091   }
46092 
46093   return SDValue();
46094 }
46095 
46096 /// Optimize an EFLAGS definition used according to the condition code \p CC
46097 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
46098 /// uses of chain values.
combineSetCCEFLAGS(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)46099 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
46100                                   SelectionDAG &DAG,
46101                                   const X86Subtarget &Subtarget) {
46102   if (CC == X86::COND_B)
46103     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
46104       return Flags;
46105 
46106   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
46107     return R;
46108 
46109   if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
46110     return R;
46111 
46112   if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
46113     return R;
46114 
46115   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
46116 }
46117 
46118 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
combineCMov(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46119 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
46120                            TargetLowering::DAGCombinerInfo &DCI,
46121                            const X86Subtarget &Subtarget) {
46122   SDLoc DL(N);
46123 
46124   SDValue FalseOp = N->getOperand(0);
46125   SDValue TrueOp = N->getOperand(1);
46126   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
46127   SDValue Cond = N->getOperand(3);
46128 
46129   // cmov X, X, ?, ? --> X
46130   if (TrueOp == FalseOp)
46131     return TrueOp;
46132 
46133   // Try to simplify the EFLAGS and condition code operands.
46134   // We can't always do this as FCMOV only supports a subset of X86 cond.
46135   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
46136     if (!(FalseOp.getValueType() == MVT::f80 ||
46137           (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
46138           (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
46139         !Subtarget.canUseCMOV() || hasFPCMov(CC)) {
46140       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
46141                        Flags};
46142       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
46143     }
46144   }
46145 
46146   // If this is a select between two integer constants, try to do some
46147   // optimizations.  Note that the operands are ordered the opposite of SELECT
46148   // operands.
46149   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
46150     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
46151       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
46152       // larger than FalseC (the false value).
46153       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
46154         CC = X86::GetOppositeBranchCondition(CC);
46155         std::swap(TrueC, FalseC);
46156         std::swap(TrueOp, FalseOp);
46157       }
46158 
46159       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
46160       // This is efficient for any integer data type (including i8/i16) and
46161       // shift amount.
46162       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
46163         Cond = getSETCC(CC, Cond, DL, DAG);
46164 
46165         // Zero extend the condition if needed.
46166         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
46167 
46168         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
46169         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
46170                            DAG.getConstant(ShAmt, DL, MVT::i8));
46171         return Cond;
46172       }
46173 
46174       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
46175       // for any integer data type, including i8/i16.
46176       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
46177         Cond = getSETCC(CC, Cond, DL, DAG);
46178 
46179         // Zero extend the condition if needed.
46180         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
46181                            FalseC->getValueType(0), Cond);
46182         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
46183                            SDValue(FalseC, 0));
46184         return Cond;
46185       }
46186 
46187       // Optimize cases that will turn into an LEA instruction.  This requires
46188       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
46189       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
46190         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
46191         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
46192                "Implicit constant truncation");
46193 
46194         bool isFastMultiplier = false;
46195         if (Diff.ult(10)) {
46196           switch (Diff.getZExtValue()) {
46197           default: break;
46198           case 1:  // result = add base, cond
46199           case 2:  // result = lea base(    , cond*2)
46200           case 3:  // result = lea base(cond, cond*2)
46201           case 4:  // result = lea base(    , cond*4)
46202           case 5:  // result = lea base(cond, cond*4)
46203           case 8:  // result = lea base(    , cond*8)
46204           case 9:  // result = lea base(cond, cond*8)
46205             isFastMultiplier = true;
46206             break;
46207           }
46208         }
46209 
46210         if (isFastMultiplier) {
46211           Cond = getSETCC(CC, Cond, DL ,DAG);
46212           // Zero extend the condition if needed.
46213           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
46214                              Cond);
46215           // Scale the condition by the difference.
46216           if (Diff != 1)
46217             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
46218                                DAG.getConstant(Diff, DL, Cond.getValueType()));
46219 
46220           // Add the base if non-zero.
46221           if (FalseC->getAPIntValue() != 0)
46222             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
46223                                SDValue(FalseC, 0));
46224           return Cond;
46225         }
46226       }
46227     }
46228   }
46229 
46230   // Handle these cases:
46231   //   (select (x != c), e, c) -> select (x != c), e, x),
46232   //   (select (x == c), c, e) -> select (x == c), x, e)
46233   // where the c is an integer constant, and the "select" is the combination
46234   // of CMOV and CMP.
46235   //
46236   // The rationale for this change is that the conditional-move from a constant
46237   // needs two instructions, however, conditional-move from a register needs
46238   // only one instruction.
46239   //
46240   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
46241   //  some instruction-combining opportunities. This opt needs to be
46242   //  postponed as late as possible.
46243   //
46244   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
46245     // the DCI.xxxx conditions are provided to postpone the optimization as
46246     // late as possible.
46247 
46248     ConstantSDNode *CmpAgainst = nullptr;
46249     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
46250         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
46251         !isa<ConstantSDNode>(Cond.getOperand(0))) {
46252 
46253       if (CC == X86::COND_NE &&
46254           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
46255         CC = X86::GetOppositeBranchCondition(CC);
46256         std::swap(TrueOp, FalseOp);
46257       }
46258 
46259       if (CC == X86::COND_E &&
46260           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
46261         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
46262                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
46263         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
46264       }
46265     }
46266   }
46267 
46268   // Transform:
46269   //
46270   //   (cmov 1 T (uge T 2))
46271   //
46272   // to:
46273   //
46274   //   (adc T 0 (sub T 1))
46275   if (CC == X86::COND_AE && isOneConstant(FalseOp) &&
46276       Cond.getOpcode() == X86ISD::SUB && Cond->hasOneUse()) {
46277     SDValue Cond0 = Cond.getOperand(0);
46278     if (Cond0.getOpcode() == ISD::TRUNCATE)
46279       Cond0 = Cond0.getOperand(0);
46280     auto *Sub1C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
46281     if (Cond0 == TrueOp && Sub1C && Sub1C->getZExtValue() == 2) {
46282       EVT CondVT = Cond->getValueType(0);
46283       EVT OuterVT = N->getValueType(0);
46284       // Subtract 1 and generate a carry.
46285       SDValue NewSub =
46286           DAG.getNode(X86ISD::SUB, DL, Cond->getVTList(), Cond.getOperand(0),
46287                       DAG.getConstant(1, DL, CondVT));
46288       SDValue EFLAGS(NewSub.getNode(), 1);
46289       return DAG.getNode(X86ISD::ADC, DL, DAG.getVTList(OuterVT, MVT::i32),
46290                          TrueOp, DAG.getConstant(0, DL, OuterVT), EFLAGS);
46291     }
46292   }
46293 
46294   // Fold and/or of setcc's to double CMOV:
46295   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
46296   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
46297   //
46298   // This combine lets us generate:
46299   //   cmovcc1 (jcc1 if we don't have CMOV)
46300   //   cmovcc2 (same)
46301   // instead of:
46302   //   setcc1
46303   //   setcc2
46304   //   and/or
46305   //   cmovne (jne if we don't have CMOV)
46306   // When we can't use the CMOV instruction, it might increase branch
46307   // mispredicts.
46308   // When we can use CMOV, or when there is no mispredict, this improves
46309   // throughput and reduces register pressure.
46310   //
46311   if (CC == X86::COND_NE) {
46312     SDValue Flags;
46313     X86::CondCode CC0, CC1;
46314     bool isAndSetCC;
46315     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
46316       if (isAndSetCC) {
46317         std::swap(FalseOp, TrueOp);
46318         CC0 = X86::GetOppositeBranchCondition(CC0);
46319         CC1 = X86::GetOppositeBranchCondition(CC1);
46320       }
46321 
46322       SDValue LOps[] = {FalseOp, TrueOp,
46323                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
46324       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
46325       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
46326                        Flags};
46327       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
46328       return CMOV;
46329     }
46330   }
46331 
46332   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
46333   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
46334   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
46335   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
46336   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
46337       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
46338     SDValue Add = TrueOp;
46339     SDValue Const = FalseOp;
46340     // Canonicalize the condition code for easier matching and output.
46341     if (CC == X86::COND_E)
46342       std::swap(Add, Const);
46343 
46344     // We might have replaced the constant in the cmov with the LHS of the
46345     // compare. If so change it to the RHS of the compare.
46346     if (Const == Cond.getOperand(0))
46347       Const = Cond.getOperand(1);
46348 
46349     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
46350     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
46351         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
46352         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
46353          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
46354         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
46355       EVT VT = N->getValueType(0);
46356       // This should constant fold.
46357       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
46358       SDValue CMov =
46359           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
46360                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
46361       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
46362     }
46363   }
46364 
46365   return SDValue();
46366 }
46367 
46368 /// Different mul shrinking modes.
46369 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
46370 
canReduceVMulWidth(SDNode * N,SelectionDAG & DAG,ShrinkMode & Mode)46371 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
46372   EVT VT = N->getOperand(0).getValueType();
46373   if (VT.getScalarSizeInBits() != 32)
46374     return false;
46375 
46376   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
46377   unsigned SignBits[2] = {1, 1};
46378   bool IsPositive[2] = {false, false};
46379   for (unsigned i = 0; i < 2; i++) {
46380     SDValue Opd = N->getOperand(i);
46381 
46382     SignBits[i] = DAG.ComputeNumSignBits(Opd);
46383     IsPositive[i] = DAG.SignBitIsZero(Opd);
46384   }
46385 
46386   bool AllPositive = IsPositive[0] && IsPositive[1];
46387   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
46388   // When ranges are from -128 ~ 127, use MULS8 mode.
46389   if (MinSignBits >= 25)
46390     Mode = ShrinkMode::MULS8;
46391   // When ranges are from 0 ~ 255, use MULU8 mode.
46392   else if (AllPositive && MinSignBits >= 24)
46393     Mode = ShrinkMode::MULU8;
46394   // When ranges are from -32768 ~ 32767, use MULS16 mode.
46395   else if (MinSignBits >= 17)
46396     Mode = ShrinkMode::MULS16;
46397   // When ranges are from 0 ~ 65535, use MULU16 mode.
46398   else if (AllPositive && MinSignBits >= 16)
46399     Mode = ShrinkMode::MULU16;
46400   else
46401     return false;
46402   return true;
46403 }
46404 
46405 /// When the operands of vector mul are extended from smaller size values,
46406 /// like i8 and i16, the type of mul may be shrinked to generate more
46407 /// efficient code. Two typical patterns are handled:
46408 /// Pattern1:
46409 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
46410 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
46411 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
46412 ///     %5 = mul <N x i32> %2, %4
46413 ///
46414 /// Pattern2:
46415 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
46416 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
46417 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
46418 ///     %5 = mul <N x i32> %2, %4
46419 ///
46420 /// There are four mul shrinking modes:
46421 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
46422 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
46423 /// generate pmullw+sext32 for it (MULS8 mode).
46424 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
46425 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
46426 /// generate pmullw+zext32 for it (MULU8 mode).
46427 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
46428 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
46429 /// generate pmullw+pmulhw for it (MULS16 mode).
46430 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
46431 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
46432 /// generate pmullw+pmulhuw for it (MULU16 mode).
reduceVMULWidth(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46433 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
46434                                const X86Subtarget &Subtarget) {
46435   // Check for legality
46436   // pmullw/pmulhw are not supported by SSE.
46437   if (!Subtarget.hasSSE2())
46438     return SDValue();
46439 
46440   // Check for profitability
46441   // pmulld is supported since SSE41. It is better to use pmulld
46442   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
46443   // the expansion.
46444   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
46445   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
46446     return SDValue();
46447 
46448   ShrinkMode Mode;
46449   if (!canReduceVMulWidth(N, DAG, Mode))
46450     return SDValue();
46451 
46452   SDLoc DL(N);
46453   SDValue N0 = N->getOperand(0);
46454   SDValue N1 = N->getOperand(1);
46455   EVT VT = N->getOperand(0).getValueType();
46456   unsigned NumElts = VT.getVectorNumElements();
46457   if ((NumElts % 2) != 0)
46458     return SDValue();
46459 
46460   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
46461 
46462   // Shrink the operands of mul.
46463   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
46464   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
46465 
46466   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
46467   // lower part is needed.
46468   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
46469   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
46470     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
46471                                                    : ISD::SIGN_EXTEND,
46472                        DL, VT, MulLo);
46473 
46474   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
46475   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
46476   // the higher part is also needed.
46477   SDValue MulHi =
46478       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
46479                   ReducedVT, NewN0, NewN1);
46480 
46481   // Repack the lower part and higher part result of mul into a wider
46482   // result.
46483   // Generate shuffle functioning as punpcklwd.
46484   SmallVector<int, 16> ShuffleMask(NumElts);
46485   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
46486     ShuffleMask[2 * i] = i;
46487     ShuffleMask[2 * i + 1] = i + NumElts;
46488   }
46489   SDValue ResLo =
46490       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
46491   ResLo = DAG.getBitcast(ResVT, ResLo);
46492   // Generate shuffle functioning as punpckhwd.
46493   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
46494     ShuffleMask[2 * i] = i + NumElts / 2;
46495     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
46496   }
46497   SDValue ResHi =
46498       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
46499   ResHi = DAG.getBitcast(ResVT, ResHi);
46500   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
46501 }
46502 
combineMulSpecial(uint64_t MulAmt,SDNode * N,SelectionDAG & DAG,EVT VT,const SDLoc & DL)46503 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
46504                                  EVT VT, const SDLoc &DL) {
46505 
46506   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
46507     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46508                                  DAG.getConstant(Mult, DL, VT));
46509     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
46510                          DAG.getConstant(Shift, DL, MVT::i8));
46511     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
46512                          N->getOperand(0));
46513     return Result;
46514   };
46515 
46516   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
46517     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46518                                  DAG.getConstant(Mul1, DL, VT));
46519     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
46520                          DAG.getConstant(Mul2, DL, VT));
46521     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
46522                          N->getOperand(0));
46523     return Result;
46524   };
46525 
46526   switch (MulAmt) {
46527   default:
46528     break;
46529   case 11:
46530     // mul x, 11 => add ((shl (mul x, 5), 1), x)
46531     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
46532   case 21:
46533     // mul x, 21 => add ((shl (mul x, 5), 2), x)
46534     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
46535   case 41:
46536     // mul x, 41 => add ((shl (mul x, 5), 3), x)
46537     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
46538   case 22:
46539     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
46540     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
46541                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
46542   case 19:
46543     // mul x, 19 => add ((shl (mul x, 9), 1), x)
46544     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
46545   case 37:
46546     // mul x, 37 => add ((shl (mul x, 9), 2), x)
46547     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
46548   case 73:
46549     // mul x, 73 => add ((shl (mul x, 9), 3), x)
46550     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
46551   case 13:
46552     // mul x, 13 => add ((shl (mul x, 3), 2), x)
46553     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
46554   case 23:
46555     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
46556     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
46557   case 26:
46558     // mul x, 26 => add ((mul (mul x, 5), 5), x)
46559     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
46560   case 28:
46561     // mul x, 28 => add ((mul (mul x, 9), 3), x)
46562     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
46563   case 29:
46564     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
46565     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
46566                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
46567   }
46568 
46569   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
46570   // by a single LEA.
46571   // First check if this a sum of two power of 2s because that's easy. Then
46572   // count how many zeros are up to the first bit.
46573   // TODO: We can do this even without LEA at a cost of two shifts and an add.
46574   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
46575     unsigned ScaleShift = llvm::countr_zero(MulAmt);
46576     if (ScaleShift >= 1 && ScaleShift < 4) {
46577       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
46578       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46579                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
46580       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46581                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
46582       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
46583     }
46584   }
46585 
46586   return SDValue();
46587 }
46588 
46589 // If the upper 17 bits of either element are zero and the other element are
46590 // zero/sign bits then we can use PMADDWD, which is always at least as quick as
46591 // PMULLD, except on KNL.
combineMulToPMADDWD(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46592 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
46593                                    const X86Subtarget &Subtarget) {
46594   if (!Subtarget.hasSSE2())
46595     return SDValue();
46596 
46597   if (Subtarget.isPMADDWDSlow())
46598     return SDValue();
46599 
46600   EVT VT = N->getValueType(0);
46601 
46602   // Only support vXi32 vectors.
46603   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
46604     return SDValue();
46605 
46606   // Make sure the type is legal or can split/widen to a legal type.
46607   // With AVX512 but without BWI, we would need to split v32i16.
46608   unsigned NumElts = VT.getVectorNumElements();
46609   if (NumElts == 1 || !isPowerOf2_32(NumElts))
46610     return SDValue();
46611 
46612   // With AVX512 but without BWI, we would need to split v32i16.
46613   if (32 <= (2 * NumElts) && Subtarget.hasAVX512() && !Subtarget.hasBWI())
46614     return SDValue();
46615 
46616   SDValue N0 = N->getOperand(0);
46617   SDValue N1 = N->getOperand(1);
46618 
46619   // If we are zero/sign extending two steps without SSE4.1, its better to
46620   // reduce the vmul width instead.
46621   if (!Subtarget.hasSSE41() &&
46622       (((N0.getOpcode() == ISD::ZERO_EXTEND &&
46623          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
46624         (N1.getOpcode() == ISD::ZERO_EXTEND &&
46625          N1.getOperand(0).getScalarValueSizeInBits() <= 8)) ||
46626        ((N0.getOpcode() == ISD::SIGN_EXTEND &&
46627          N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
46628         (N1.getOpcode() == ISD::SIGN_EXTEND &&
46629          N1.getOperand(0).getScalarValueSizeInBits() <= 8))))
46630     return SDValue();
46631 
46632   // If we are sign extending a wide vector without SSE4.1, its better to reduce
46633   // the vmul width instead.
46634   if (!Subtarget.hasSSE41() &&
46635       (N0.getOpcode() == ISD::SIGN_EXTEND &&
46636        N0.getOperand(0).getValueSizeInBits() > 128) &&
46637       (N1.getOpcode() == ISD::SIGN_EXTEND &&
46638        N1.getOperand(0).getValueSizeInBits() > 128))
46639     return SDValue();
46640 
46641   // Sign bits must extend down to the lowest i16.
46642   if (DAG.ComputeMaxSignificantBits(N1) > 16 ||
46643       DAG.ComputeMaxSignificantBits(N0) > 16)
46644     return SDValue();
46645 
46646   // At least one of the elements must be zero in the upper 17 bits, or can be
46647   // safely made zero without altering the final result.
46648   auto GetZeroableOp = [&](SDValue Op) {
46649     APInt Mask17 = APInt::getHighBitsSet(32, 17);
46650     if (DAG.MaskedValueIsZero(Op, Mask17))
46651       return Op;
46652     // Mask off upper 16-bits of sign-extended constants.
46653     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()))
46654       return DAG.getNode(ISD::AND, SDLoc(N), VT, Op,
46655                          DAG.getConstant(0xFFFF, SDLoc(N), VT));
46656     if (Op.getOpcode() == ISD::SIGN_EXTEND && N->isOnlyUserOf(Op.getNode())) {
46657       SDValue Src = Op.getOperand(0);
46658       // Convert sext(vXi16) to zext(vXi16).
46659       if (Src.getScalarValueSizeInBits() == 16 && VT.getSizeInBits() <= 128)
46660         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
46661       // Convert sext(vXi8) to zext(vXi16 sext(vXi8)) on pre-SSE41 targets
46662       // which will expand the extension.
46663       if (Src.getScalarValueSizeInBits() < 16 && !Subtarget.hasSSE41()) {
46664         EVT ExtVT = VT.changeVectorElementType(MVT::i16);
46665         Src = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), ExtVT, Src);
46666         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Src);
46667       }
46668     }
46669     // Convert SIGN_EXTEND_VECTOR_INREG to ZEXT_EXTEND_VECTOR_INREG.
46670     if (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG &&
46671         N->isOnlyUserOf(Op.getNode())) {
46672       SDValue Src = Op.getOperand(0);
46673       if (Src.getScalarValueSizeInBits() == 16)
46674         return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(N), VT, Src);
46675     }
46676     // Convert VSRAI(Op, 16) to VSRLI(Op, 16).
46677     if (Op.getOpcode() == X86ISD::VSRAI && Op.getConstantOperandVal(1) == 16 &&
46678         N->isOnlyUserOf(Op.getNode())) {
46679       return DAG.getNode(X86ISD::VSRLI, SDLoc(N), VT, Op.getOperand(0),
46680                          Op.getOperand(1));
46681     }
46682     return SDValue();
46683   };
46684   SDValue ZeroN0 = GetZeroableOp(N0);
46685   SDValue ZeroN1 = GetZeroableOp(N1);
46686   if (!ZeroN0 && !ZeroN1)
46687     return SDValue();
46688   N0 = ZeroN0 ? ZeroN0 : N0;
46689   N1 = ZeroN1 ? ZeroN1 : N1;
46690 
46691   // Use SplitOpsAndApply to handle AVX splitting.
46692   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46693                            ArrayRef<SDValue> Ops) {
46694     MVT ResVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
46695     MVT OpVT = MVT::getVectorVT(MVT::i16, Ops[0].getValueSizeInBits() / 16);
46696     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
46697                        DAG.getBitcast(OpVT, Ops[0]),
46698                        DAG.getBitcast(OpVT, Ops[1]));
46699   };
46700   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {N0, N1},
46701                           PMADDWDBuilder);
46702 }
46703 
combineMulToPMULDQ(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46704 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
46705                                   const X86Subtarget &Subtarget) {
46706   if (!Subtarget.hasSSE2())
46707     return SDValue();
46708 
46709   EVT VT = N->getValueType(0);
46710 
46711   // Only support vXi64 vectors.
46712   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
46713       VT.getVectorNumElements() < 2 ||
46714       !isPowerOf2_32(VT.getVectorNumElements()))
46715     return SDValue();
46716 
46717   SDValue N0 = N->getOperand(0);
46718   SDValue N1 = N->getOperand(1);
46719 
46720   // MULDQ returns the 64-bit result of the signed multiplication of the lower
46721   // 32-bits. We can lower with this if the sign bits stretch that far.
46722   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
46723       DAG.ComputeNumSignBits(N1) > 32) {
46724     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46725                             ArrayRef<SDValue> Ops) {
46726       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
46727     };
46728     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
46729                             PMULDQBuilder, /*CheckBWI*/false);
46730   }
46731 
46732   // If the upper bits are zero we can use a single pmuludq.
46733   APInt Mask = APInt::getHighBitsSet(64, 32);
46734   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
46735     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46736                              ArrayRef<SDValue> Ops) {
46737       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
46738     };
46739     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
46740                             PMULUDQBuilder, /*CheckBWI*/false);
46741   }
46742 
46743   return SDValue();
46744 }
46745 
combineMul(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46746 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
46747                           TargetLowering::DAGCombinerInfo &DCI,
46748                           const X86Subtarget &Subtarget) {
46749   EVT VT = N->getValueType(0);
46750 
46751   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
46752     return V;
46753 
46754   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
46755     return V;
46756 
46757   if (DCI.isBeforeLegalize() && VT.isVector())
46758     return reduceVMULWidth(N, DAG, Subtarget);
46759 
46760   // Optimize a single multiply with constant into two operations in order to
46761   // implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
46762   if (!MulConstantOptimization)
46763     return SDValue();
46764 
46765   // An imul is usually smaller than the alternative sequence.
46766   if (DAG.getMachineFunction().getFunction().hasMinSize())
46767     return SDValue();
46768 
46769   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
46770     return SDValue();
46771 
46772   if (VT != MVT::i64 && VT != MVT::i32 &&
46773       (!VT.isVector() || !VT.isSimple() || !VT.isInteger()))
46774     return SDValue();
46775 
46776   ConstantSDNode *CNode = isConstOrConstSplat(
46777       N->getOperand(1), /*AllowUndefs*/ true, /*AllowTrunc*/ false);
46778   const APInt *C = nullptr;
46779   if (!CNode) {
46780     if (VT.isVector())
46781       if (auto *RawC = getTargetConstantFromNode(N->getOperand(1)))
46782         if (auto *SplatC = RawC->getSplatValue())
46783           C = &(SplatC->getUniqueInteger());
46784 
46785     if (!C || C->getBitWidth() != VT.getScalarSizeInBits())
46786       return SDValue();
46787   } else {
46788     C = &(CNode->getAPIntValue());
46789   }
46790 
46791   if (isPowerOf2_64(C->getZExtValue()))
46792     return SDValue();
46793 
46794   int64_t SignMulAmt = C->getSExtValue();
46795   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
46796   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
46797 
46798   SDLoc DL(N);
46799   SDValue NewMul = SDValue();
46800   if (VT == MVT::i64 || VT == MVT::i32) {
46801     if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
46802       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46803                            DAG.getConstant(AbsMulAmt, DL, VT));
46804       if (SignMulAmt < 0)
46805         NewMul =
46806             DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), NewMul);
46807 
46808       return NewMul;
46809     }
46810 
46811     uint64_t MulAmt1 = 0;
46812     uint64_t MulAmt2 = 0;
46813     if ((AbsMulAmt % 9) == 0) {
46814       MulAmt1 = 9;
46815       MulAmt2 = AbsMulAmt / 9;
46816     } else if ((AbsMulAmt % 5) == 0) {
46817       MulAmt1 = 5;
46818       MulAmt2 = AbsMulAmt / 5;
46819     } else if ((AbsMulAmt % 3) == 0) {
46820       MulAmt1 = 3;
46821       MulAmt2 = AbsMulAmt / 3;
46822     }
46823 
46824     // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
46825     if (MulAmt2 &&
46826         (isPowerOf2_64(MulAmt2) ||
46827          (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
46828 
46829       if (isPowerOf2_64(MulAmt2) && !(SignMulAmt >= 0 && N->hasOneUse() &&
46830                                       N->use_begin()->getOpcode() == ISD::ADD))
46831         // If second multiplifer is pow2, issue it first. We want the multiply
46832         // by 3, 5, or 9 to be folded into the addressing mode unless the lone
46833         // use is an add. Only do this for positive multiply amounts since the
46834         // negate would prevent it from being used as an address mode anyway.
46835         std::swap(MulAmt1, MulAmt2);
46836 
46837       if (isPowerOf2_64(MulAmt1))
46838         NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46839                              DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
46840       else
46841         NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
46842                              DAG.getConstant(MulAmt1, DL, VT));
46843 
46844       if (isPowerOf2_64(MulAmt2))
46845         NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
46846                              DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
46847       else
46848         NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
46849                              DAG.getConstant(MulAmt2, DL, VT));
46850 
46851       // Negate the result.
46852       if (SignMulAmt < 0)
46853         NewMul =
46854             DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), NewMul);
46855     } else if (!Subtarget.slowLEA())
46856       NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
46857   }
46858   if (!NewMul) {
46859     EVT ShiftVT = VT.isVector() ? VT : MVT::i8;
46860     assert(C->getZExtValue() != 0 &&
46861            C->getZExtValue() != maxUIntN(VT.getScalarSizeInBits()) &&
46862            "Both cases that could cause potential overflows should have "
46863            "already been handled.");
46864     if (isPowerOf2_64(AbsMulAmt - 1)) {
46865       // (mul x, 2^N + 1) => (add (shl x, N), x)
46866       NewMul = DAG.getNode(
46867           ISD::ADD, DL, VT, N->getOperand(0),
46868           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46869                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL, ShiftVT)));
46870       // To negate, subtract the number from zero
46871       if (SignMulAmt < 0)
46872         NewMul =
46873             DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), NewMul);
46874     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
46875       // (mul x, 2^N - 1) => (sub (shl x, N), x)
46876       NewMul =
46877           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46878                       DAG.getConstant(Log2_64(AbsMulAmt + 1), DL, ShiftVT));
46879       // To negate, reverse the operands of the subtract.
46880       if (SignMulAmt < 0)
46881         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
46882       else
46883         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
46884     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2) &&
46885                (!VT.isVector() || Subtarget.fastImmVectorShift())) {
46886       // (mul x, 2^N + 2) => (add (shl x, N), (add x, x))
46887       NewMul =
46888           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46889                       DAG.getConstant(Log2_64(AbsMulAmt - 2), DL, ShiftVT));
46890       NewMul = DAG.getNode(
46891           ISD::ADD, DL, VT, NewMul,
46892           DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0), N->getOperand(0)));
46893     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2) &&
46894                (!VT.isVector() || Subtarget.fastImmVectorShift())) {
46895       // (mul x, 2^N - 2) => (sub (shl x, N), (add x, x))
46896       NewMul =
46897           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46898                       DAG.getConstant(Log2_64(AbsMulAmt + 2), DL, ShiftVT));
46899       NewMul = DAG.getNode(
46900           ISD::SUB, DL, VT, NewMul,
46901           DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0), N->getOperand(0)));
46902     } else if (SignMulAmt >= 0 && VT.isVector() &&
46903                Subtarget.fastImmVectorShift()) {
46904       uint64_t AbsMulAmtLowBit = AbsMulAmt & (-AbsMulAmt);
46905       uint64_t ShiftAmt1;
46906       std::optional<unsigned> Opc;
46907       if (isPowerOf2_64(AbsMulAmt - AbsMulAmtLowBit)) {
46908         ShiftAmt1 = AbsMulAmt - AbsMulAmtLowBit;
46909         Opc = ISD::ADD;
46910       } else if (isPowerOf2_64(AbsMulAmt + AbsMulAmtLowBit)) {
46911         ShiftAmt1 = AbsMulAmt + AbsMulAmtLowBit;
46912         Opc = ISD::SUB;
46913       }
46914 
46915       if (Opc) {
46916         SDValue Shift1 =
46917             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46918                         DAG.getConstant(Log2_64(ShiftAmt1), DL, ShiftVT));
46919         SDValue Shift2 =
46920             DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
46921                         DAG.getConstant(Log2_64(AbsMulAmtLowBit), DL, ShiftVT));
46922         NewMul = DAG.getNode(*Opc, DL, VT, Shift1, Shift2);
46923       }
46924     }
46925   }
46926 
46927   return NewMul;
46928 }
46929 
46930 // Try to form a MULHU or MULHS node by looking for
46931 // (srl (mul ext, ext), 16)
46932 // TODO: This is X86 specific because we want to be able to handle wide types
46933 // before type legalization. But we can only do it if the vector will be
46934 // legalized via widening/splitting. Type legalization can't handle promotion
46935 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
46936 // combiner.
combineShiftToPMULH(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46937 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
46938                                    const X86Subtarget &Subtarget) {
46939   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
46940            "SRL or SRA node is required here!");
46941   SDLoc DL(N);
46942 
46943   if (!Subtarget.hasSSE2())
46944     return SDValue();
46945 
46946   // The operation feeding into the shift must be a multiply.
46947   SDValue ShiftOperand = N->getOperand(0);
46948   if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
46949     return SDValue();
46950 
46951   // Input type should be at least vXi32.
46952   EVT VT = N->getValueType(0);
46953   if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
46954     return SDValue();
46955 
46956   // Need a shift by 16.
46957   APInt ShiftAmt;
46958   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
46959       ShiftAmt != 16)
46960     return SDValue();
46961 
46962   SDValue LHS = ShiftOperand.getOperand(0);
46963   SDValue RHS = ShiftOperand.getOperand(1);
46964 
46965   unsigned ExtOpc = LHS.getOpcode();
46966   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
46967       RHS.getOpcode() != ExtOpc)
46968     return SDValue();
46969 
46970   // Peek through the extends.
46971   LHS = LHS.getOperand(0);
46972   RHS = RHS.getOperand(0);
46973 
46974   // Ensure the input types match.
46975   EVT MulVT = LHS.getValueType();
46976   if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
46977     return SDValue();
46978 
46979   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
46980   SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
46981 
46982   ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
46983   return DAG.getNode(ExtOpc, DL, VT, Mulh);
46984 }
46985 
combineShiftLeft(SDNode * N,SelectionDAG & DAG)46986 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
46987   SDValue N0 = N->getOperand(0);
46988   SDValue N1 = N->getOperand(1);
46989   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
46990   EVT VT = N0.getValueType();
46991 
46992   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
46993   // since the result of setcc_c is all zero's or all ones.
46994   if (VT.isInteger() && !VT.isVector() &&
46995       N1C && N0.getOpcode() == ISD::AND &&
46996       N0.getOperand(1).getOpcode() == ISD::Constant) {
46997     SDValue N00 = N0.getOperand(0);
46998     APInt Mask = N0.getConstantOperandAPInt(1);
46999     Mask <<= N1C->getAPIntValue();
47000     bool MaskOK = false;
47001     // We can handle cases concerning bit-widening nodes containing setcc_c if
47002     // we carefully interrogate the mask to make sure we are semantics
47003     // preserving.
47004     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
47005     // of the underlying setcc_c operation if the setcc_c was zero extended.
47006     // Consider the following example:
47007     //   zext(setcc_c)                 -> i32 0x0000FFFF
47008     //   c1                            -> i32 0x0000FFFF
47009     //   c2                            -> i32 0x00000001
47010     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
47011     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
47012     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
47013       MaskOK = true;
47014     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
47015                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
47016       MaskOK = true;
47017     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
47018                 N00.getOpcode() == ISD::ANY_EXTEND) &&
47019                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
47020       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
47021     }
47022     if (MaskOK && Mask != 0) {
47023       SDLoc DL(N);
47024       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
47025     }
47026   }
47027 
47028   return SDValue();
47029 }
47030 
combineShiftRightArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)47031 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
47032                                            const X86Subtarget &Subtarget) {
47033   SDValue N0 = N->getOperand(0);
47034   SDValue N1 = N->getOperand(1);
47035   EVT VT = N0.getValueType();
47036   unsigned Size = VT.getSizeInBits();
47037 
47038   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
47039     return V;
47040 
47041   // fold (SRA (SHL X, ShlConst), SraConst)
47042   // into (SHL (sext_in_reg X), ShlConst - SraConst)
47043   //   or (sext_in_reg X)
47044   //   or (SRA (sext_in_reg X), SraConst - ShlConst)
47045   // depending on relation between SraConst and ShlConst.
47046   // We only do this if (Size - ShlConst) is equal to 8, 16 or 32. That allows
47047   // us to do the sext_in_reg from corresponding bit.
47048 
47049   // sexts in X86 are MOVs. The MOVs have the same code size
47050   // as above SHIFTs (only SHIFT on 1 has lower code size).
47051   // However the MOVs have 2 advantages to a SHIFT:
47052   // 1. MOVs can write to a register that differs from source
47053   // 2. MOVs accept memory operands
47054 
47055   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
47056       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
47057       N0.getOperand(1).getOpcode() != ISD::Constant)
47058     return SDValue();
47059 
47060   SDValue N00 = N0.getOperand(0);
47061   SDValue N01 = N0.getOperand(1);
47062   APInt ShlConst = N01->getAsAPIntVal();
47063   APInt SraConst = N1->getAsAPIntVal();
47064   EVT CVT = N1.getValueType();
47065 
47066   if (CVT != N01.getValueType())
47067     return SDValue();
47068   if (SraConst.isNegative())
47069     return SDValue();
47070 
47071   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
47072     unsigned ShiftSize = SVT.getSizeInBits();
47073     // Only deal with (Size - ShlConst) being equal to 8, 16 or 32.
47074     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
47075       continue;
47076     SDLoc DL(N);
47077     SDValue NN =
47078         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
47079     if (SraConst.eq(ShlConst))
47080       return NN;
47081     if (SraConst.ult(ShlConst))
47082       return DAG.getNode(ISD::SHL, DL, VT, NN,
47083                          DAG.getConstant(ShlConst - SraConst, DL, CVT));
47084     return DAG.getNode(ISD::SRA, DL, VT, NN,
47085                        DAG.getConstant(SraConst - ShlConst, DL, CVT));
47086   }
47087   return SDValue();
47088 }
47089 
combineShiftRightLogical(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47090 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
47091                                         TargetLowering::DAGCombinerInfo &DCI,
47092                                         const X86Subtarget &Subtarget) {
47093   SDValue N0 = N->getOperand(0);
47094   SDValue N1 = N->getOperand(1);
47095   EVT VT = N0.getValueType();
47096 
47097   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
47098     return V;
47099 
47100   // Only do this on the last DAG combine as it can interfere with other
47101   // combines.
47102   if (!DCI.isAfterLegalizeDAG())
47103     return SDValue();
47104 
47105   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
47106   // TODO: This is a generic DAG combine that became an x86-only combine to
47107   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
47108   // and-not ('andn').
47109   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
47110     return SDValue();
47111 
47112   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
47113   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
47114   if (!ShiftC || !AndC)
47115     return SDValue();
47116 
47117   // If we can shrink the constant mask below 8-bits or 32-bits, then this
47118   // transform should reduce code size. It may also enable secondary transforms
47119   // from improved known-bits analysis or instruction selection.
47120   APInt MaskVal = AndC->getAPIntValue();
47121 
47122   // If this can be matched by a zero extend, don't optimize.
47123   if (MaskVal.isMask()) {
47124     unsigned TO = MaskVal.countr_one();
47125     if (TO >= 8 && isPowerOf2_32(TO))
47126       return SDValue();
47127   }
47128 
47129   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
47130   unsigned OldMaskSize = MaskVal.getSignificantBits();
47131   unsigned NewMaskSize = NewMaskVal.getSignificantBits();
47132   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
47133       (OldMaskSize > 32 && NewMaskSize <= 32)) {
47134     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
47135     SDLoc DL(N);
47136     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
47137     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
47138     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
47139   }
47140   return SDValue();
47141 }
47142 
combineHorizOpWithShuffle(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)47143 static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
47144                                          const X86Subtarget &Subtarget) {
47145   unsigned Opcode = N->getOpcode();
47146   assert(isHorizOp(Opcode) && "Unexpected hadd/hsub/pack opcode");
47147 
47148   SDLoc DL(N);
47149   EVT VT = N->getValueType(0);
47150   SDValue N0 = N->getOperand(0);
47151   SDValue N1 = N->getOperand(1);
47152   EVT SrcVT = N0.getValueType();
47153 
47154   SDValue BC0 =
47155       N->isOnlyUserOf(N0.getNode()) ? peekThroughOneUseBitcasts(N0) : N0;
47156   SDValue BC1 =
47157       N->isOnlyUserOf(N1.getNode()) ? peekThroughOneUseBitcasts(N1) : N1;
47158 
47159   // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
47160   // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
47161   // truncation trees that help us avoid lane crossing shuffles.
47162   // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
47163   // TODO: We don't handle vXf64 shuffles yet.
47164   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
47165     if (SDValue BCSrc = getSplitVectorSrc(BC0, BC1, false)) {
47166       SmallVector<SDValue> ShuffleOps;
47167       SmallVector<int> ShuffleMask, ScaledMask;
47168       SDValue Vec = peekThroughBitcasts(BCSrc);
47169       if (getTargetShuffleInputs(Vec, ShuffleOps, ShuffleMask, DAG)) {
47170         resolveTargetShuffleInputsAndMask(ShuffleOps, ShuffleMask);
47171         // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
47172         // shuffle to a v4X64 width - we can probably relax this in the future.
47173         if (!isAnyZero(ShuffleMask) && ShuffleOps.size() == 1 &&
47174             ShuffleOps[0].getValueType().is256BitVector() &&
47175             scaleShuffleElements(ShuffleMask, 4, ScaledMask)) {
47176           SDValue Lo, Hi;
47177           MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
47178           std::tie(Lo, Hi) = DAG.SplitVector(ShuffleOps[0], DL);
47179           Lo = DAG.getBitcast(SrcVT, Lo);
47180           Hi = DAG.getBitcast(SrcVT, Hi);
47181           SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
47182           Res = DAG.getBitcast(ShufVT, Res);
47183           Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ScaledMask);
47184           return DAG.getBitcast(VT, Res);
47185         }
47186       }
47187     }
47188   }
47189 
47190   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(Z,W)) -> SHUFFLE(HOP()).
47191   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
47192     // If either/both ops are a shuffle that can scale to v2x64,
47193     // then see if we can perform this as a v4x32 post shuffle.
47194     SmallVector<SDValue> Ops0, Ops1;
47195     SmallVector<int> Mask0, Mask1, ScaledMask0, ScaledMask1;
47196     bool IsShuf0 =
47197         getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
47198         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
47199         all_of(Ops0, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
47200     bool IsShuf1 =
47201         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
47202         scaleShuffleElements(Mask1, 2, ScaledMask1) &&
47203         all_of(Ops1, [](SDValue Op) { return Op.getValueSizeInBits() == 128; });
47204     if (IsShuf0 || IsShuf1) {
47205       if (!IsShuf0) {
47206         Ops0.assign({BC0});
47207         ScaledMask0.assign({0, 1});
47208       }
47209       if (!IsShuf1) {
47210         Ops1.assign({BC1});
47211         ScaledMask1.assign({0, 1});
47212       }
47213 
47214       SDValue LHS, RHS;
47215       int PostShuffle[4] = {-1, -1, -1, -1};
47216       auto FindShuffleOpAndIdx = [&](int M, int &Idx, ArrayRef<SDValue> Ops) {
47217         if (M < 0)
47218           return true;
47219         Idx = M % 2;
47220         SDValue Src = Ops[M / 2];
47221         if (!LHS || LHS == Src) {
47222           LHS = Src;
47223           return true;
47224         }
47225         if (!RHS || RHS == Src) {
47226           Idx += 2;
47227           RHS = Src;
47228           return true;
47229         }
47230         return false;
47231       };
47232       if (FindShuffleOpAndIdx(ScaledMask0[0], PostShuffle[0], Ops0) &&
47233           FindShuffleOpAndIdx(ScaledMask0[1], PostShuffle[1], Ops0) &&
47234           FindShuffleOpAndIdx(ScaledMask1[0], PostShuffle[2], Ops1) &&
47235           FindShuffleOpAndIdx(ScaledMask1[1], PostShuffle[3], Ops1)) {
47236         LHS = DAG.getBitcast(SrcVT, LHS);
47237         RHS = DAG.getBitcast(SrcVT, RHS ? RHS : LHS);
47238         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
47239         SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
47240         Res = DAG.getBitcast(ShufVT, Res);
47241         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
47242         return DAG.getBitcast(VT, Res);
47243       }
47244     }
47245   }
47246 
47247   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
47248   if (VT.is256BitVector() && Subtarget.hasInt256()) {
47249     SmallVector<int> Mask0, Mask1;
47250     SmallVector<SDValue> Ops0, Ops1;
47251     SmallVector<int, 2> ScaledMask0, ScaledMask1;
47252     if (getTargetShuffleInputs(BC0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
47253         getTargetShuffleInputs(BC1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
47254         !Ops0.empty() && !Ops1.empty() &&
47255         all_of(Ops0,
47256                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
47257         all_of(Ops1,
47258                [](SDValue Op) { return Op.getValueType().is256BitVector(); }) &&
47259         scaleShuffleElements(Mask0, 2, ScaledMask0) &&
47260         scaleShuffleElements(Mask1, 2, ScaledMask1)) {
47261       SDValue Op00 = peekThroughBitcasts(Ops0.front());
47262       SDValue Op10 = peekThroughBitcasts(Ops1.front());
47263       SDValue Op01 = peekThroughBitcasts(Ops0.back());
47264       SDValue Op11 = peekThroughBitcasts(Ops1.back());
47265       if ((Op00 == Op11) && (Op01 == Op10)) {
47266         std::swap(Op10, Op11);
47267         ShuffleVectorSDNode::commuteMask(ScaledMask1);
47268       }
47269       if ((Op00 == Op10) && (Op01 == Op11)) {
47270         const int Map[4] = {0, 2, 1, 3};
47271         SmallVector<int, 4> ShuffleMask(
47272             {Map[ScaledMask0[0]], Map[ScaledMask1[0]], Map[ScaledMask0[1]],
47273              Map[ScaledMask1[1]]});
47274         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
47275         SDValue Res = DAG.getNode(Opcode, DL, VT, DAG.getBitcast(SrcVT, Op00),
47276                                   DAG.getBitcast(SrcVT, Op01));
47277         Res = DAG.getBitcast(ShufVT, Res);
47278         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
47279         return DAG.getBitcast(VT, Res);
47280       }
47281     }
47282   }
47283 
47284   return SDValue();
47285 }
47286 
combineVectorPack(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47287 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
47288                                  TargetLowering::DAGCombinerInfo &DCI,
47289                                  const X86Subtarget &Subtarget) {
47290   unsigned Opcode = N->getOpcode();
47291   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
47292          "Unexpected pack opcode");
47293 
47294   EVT VT = N->getValueType(0);
47295   SDValue N0 = N->getOperand(0);
47296   SDValue N1 = N->getOperand(1);
47297   unsigned NumDstElts = VT.getVectorNumElements();
47298   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
47299   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
47300   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
47301          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
47302          "Unexpected PACKSS/PACKUS input type");
47303 
47304   bool IsSigned = (X86ISD::PACKSS == Opcode);
47305 
47306   // Constant Folding.
47307   APInt UndefElts0, UndefElts1;
47308   SmallVector<APInt, 32> EltBits0, EltBits1;
47309   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
47310       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
47311       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
47312       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
47313     unsigned NumLanes = VT.getSizeInBits() / 128;
47314     unsigned NumSrcElts = NumDstElts / 2;
47315     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
47316     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
47317 
47318     APInt Undefs(NumDstElts, 0);
47319     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getZero(DstBitsPerElt));
47320     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
47321       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
47322         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
47323         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
47324         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
47325 
47326         if (UndefElts[SrcIdx]) {
47327           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
47328           continue;
47329         }
47330 
47331         APInt &Val = EltBits[SrcIdx];
47332         if (IsSigned) {
47333           // PACKSS: Truncate signed value with signed saturation.
47334           // Source values less than dst minint are saturated to minint.
47335           // Source values greater than dst maxint are saturated to maxint.
47336           if (Val.isSignedIntN(DstBitsPerElt))
47337             Val = Val.trunc(DstBitsPerElt);
47338           else if (Val.isNegative())
47339             Val = APInt::getSignedMinValue(DstBitsPerElt);
47340           else
47341             Val = APInt::getSignedMaxValue(DstBitsPerElt);
47342         } else {
47343           // PACKUS: Truncate signed value with unsigned saturation.
47344           // Source values less than zero are saturated to zero.
47345           // Source values greater than dst maxuint are saturated to maxuint.
47346           if (Val.isIntN(DstBitsPerElt))
47347             Val = Val.trunc(DstBitsPerElt);
47348           else if (Val.isNegative())
47349             Val = APInt::getZero(DstBitsPerElt);
47350           else
47351             Val = APInt::getAllOnes(DstBitsPerElt);
47352         }
47353         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
47354       }
47355     }
47356 
47357     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
47358   }
47359 
47360   // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
47361   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
47362     return V;
47363 
47364   // Try to fold PACKSS(NOT(X),NOT(Y)) -> NOT(PACKSS(X,Y)).
47365   // Currently limit this to allsignbits cases only.
47366   if (IsSigned &&
47367       (N0.isUndef() || DAG.ComputeNumSignBits(N0) == SrcBitsPerElt) &&
47368       (N1.isUndef() || DAG.ComputeNumSignBits(N1) == SrcBitsPerElt)) {
47369     SDValue Not0 = N0.isUndef() ? N0 : IsNOT(N0, DAG);
47370     SDValue Not1 = N1.isUndef() ? N1 : IsNOT(N1, DAG);
47371     if (Not0 && Not1) {
47372       SDLoc DL(N);
47373       MVT SrcVT = N0.getSimpleValueType();
47374       SDValue Pack =
47375           DAG.getNode(X86ISD::PACKSS, DL, VT, DAG.getBitcast(SrcVT, Not0),
47376                       DAG.getBitcast(SrcVT, Not1));
47377       return DAG.getNOT(DL, Pack, VT);
47378     }
47379   }
47380 
47381   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
47382   // truncate to create a larger truncate.
47383   if (Subtarget.hasAVX512() &&
47384       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
47385       N0.getOperand(0).getValueType() == MVT::v8i32) {
47386     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
47387         (!IsSigned &&
47388          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
47389       if (Subtarget.hasVLX())
47390         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
47391 
47392       // Widen input to v16i32 so we can truncate that.
47393       SDLoc dl(N);
47394       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
47395                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
47396       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
47397     }
47398   }
47399 
47400   // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
47401   if (VT.is128BitVector()) {
47402     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
47403     SDValue Src0, Src1;
47404     if (N0.getOpcode() == ExtOpc &&
47405         N0.getOperand(0).getValueType().is64BitVector() &&
47406         N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
47407       Src0 = N0.getOperand(0);
47408     }
47409     if (N1.getOpcode() == ExtOpc &&
47410         N1.getOperand(0).getValueType().is64BitVector() &&
47411         N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
47412       Src1 = N1.getOperand(0);
47413     }
47414     if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
47415       assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)");
47416       Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
47417       Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
47418       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
47419     }
47420 
47421     // Try again with pack(*_extend_vector_inreg, undef).
47422     unsigned VecInRegOpc = IsSigned ? ISD::SIGN_EXTEND_VECTOR_INREG
47423                                     : ISD::ZERO_EXTEND_VECTOR_INREG;
47424     if (N0.getOpcode() == VecInRegOpc && N1.isUndef() &&
47425         N0.getOperand(0).getScalarValueSizeInBits() < DstBitsPerElt)
47426       return getEXTEND_VECTOR_INREG(ExtOpc, SDLoc(N), VT, N0.getOperand(0),
47427                                     DAG);
47428   }
47429 
47430   // Attempt to combine as shuffle.
47431   SDValue Op(N, 0);
47432   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47433     return Res;
47434 
47435   return SDValue();
47436 }
47437 
combineVectorHADDSUB(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47438 static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
47439                                     TargetLowering::DAGCombinerInfo &DCI,
47440                                     const X86Subtarget &Subtarget) {
47441   assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||
47442           X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
47443          "Unexpected horizontal add/sub opcode");
47444 
47445   if (!shouldUseHorizontalOp(true, DAG, Subtarget)) {
47446     MVT VT = N->getSimpleValueType(0);
47447     SDValue LHS = N->getOperand(0);
47448     SDValue RHS = N->getOperand(1);
47449 
47450     // HOP(HOP'(X,X),HOP'(Y,Y)) -> HOP(PERMUTE(HOP'(X,Y)),PERMUTE(HOP'(X,Y)).
47451     if (LHS != RHS && LHS.getOpcode() == N->getOpcode() &&
47452         LHS.getOpcode() == RHS.getOpcode() &&
47453         LHS.getValueType() == RHS.getValueType() &&
47454         N->isOnlyUserOf(LHS.getNode()) && N->isOnlyUserOf(RHS.getNode())) {
47455       SDValue LHS0 = LHS.getOperand(0);
47456       SDValue LHS1 = LHS.getOperand(1);
47457       SDValue RHS0 = RHS.getOperand(0);
47458       SDValue RHS1 = RHS.getOperand(1);
47459       if ((LHS0 == LHS1 || LHS0.isUndef() || LHS1.isUndef()) &&
47460           (RHS0 == RHS1 || RHS0.isUndef() || RHS1.isUndef())) {
47461         SDLoc DL(N);
47462         SDValue Res = DAG.getNode(LHS.getOpcode(), DL, LHS.getValueType(),
47463                                   LHS0.isUndef() ? LHS1 : LHS0,
47464                                   RHS0.isUndef() ? RHS1 : RHS0);
47465         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits() / 32);
47466         Res = DAG.getBitcast(ShufVT, Res);
47467         SDValue NewLHS =
47468             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
47469                         getV4X86ShuffleImm8ForMask({0, 1, 0, 1}, DL, DAG));
47470         SDValue NewRHS =
47471             DAG.getNode(X86ISD::PSHUFD, DL, ShufVT, Res,
47472                         getV4X86ShuffleImm8ForMask({2, 3, 2, 3}, DL, DAG));
47473         return DAG.getNode(N->getOpcode(), DL, VT, DAG.getBitcast(VT, NewLHS),
47474                            DAG.getBitcast(VT, NewRHS));
47475       }
47476     }
47477   }
47478 
47479   // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
47480   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
47481     return V;
47482 
47483   return SDValue();
47484 }
47485 
combineVectorShiftVar(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47486 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
47487                                      TargetLowering::DAGCombinerInfo &DCI,
47488                                      const X86Subtarget &Subtarget) {
47489   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
47490           X86ISD::VSRL == N->getOpcode()) &&
47491          "Unexpected shift opcode");
47492   EVT VT = N->getValueType(0);
47493   SDValue N0 = N->getOperand(0);
47494   SDValue N1 = N->getOperand(1);
47495 
47496   // Shift zero -> zero.
47497   if (ISD::isBuildVectorAllZeros(N0.getNode()))
47498     return DAG.getConstant(0, SDLoc(N), VT);
47499 
47500   // Detect constant shift amounts.
47501   APInt UndefElts;
47502   SmallVector<APInt, 32> EltBits;
47503   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
47504     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
47505     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
47506                                       EltBits[0].getZExtValue(), DAG);
47507   }
47508 
47509   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47510   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
47511   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
47512     return SDValue(N, 0);
47513 
47514   return SDValue();
47515 }
47516 
combineVectorShiftImm(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47517 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
47518                                      TargetLowering::DAGCombinerInfo &DCI,
47519                                      const X86Subtarget &Subtarget) {
47520   unsigned Opcode = N->getOpcode();
47521   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
47522           X86ISD::VSRLI == Opcode) &&
47523          "Unexpected shift opcode");
47524   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
47525   EVT VT = N->getValueType(0);
47526   SDValue N0 = N->getOperand(0);
47527   SDValue N1 = N->getOperand(1);
47528   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
47529   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
47530          "Unexpected value type");
47531   assert(N1.getValueType() == MVT::i8 && "Unexpected shift amount type");
47532 
47533   // (shift undef, X) -> 0
47534   if (N0.isUndef())
47535     return DAG.getConstant(0, SDLoc(N), VT);
47536 
47537   // Out of range logical bit shifts are guaranteed to be zero.
47538   // Out of range arithmetic bit shifts splat the sign bit.
47539   unsigned ShiftVal = N->getConstantOperandVal(1);
47540   if (ShiftVal >= NumBitsPerElt) {
47541     if (LogicalShift)
47542       return DAG.getConstant(0, SDLoc(N), VT);
47543     ShiftVal = NumBitsPerElt - 1;
47544   }
47545 
47546   // (shift X, 0) -> X
47547   if (!ShiftVal)
47548     return N0;
47549 
47550   // (shift 0, C) -> 0
47551   if (ISD::isBuildVectorAllZeros(N0.getNode()))
47552     // N0 is all zeros or undef. We guarantee that the bits shifted into the
47553     // result are all zeros, not undef.
47554     return DAG.getConstant(0, SDLoc(N), VT);
47555 
47556   // (VSRAI -1, C) -> -1
47557   if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
47558     // N0 is all ones or undef. We guarantee that the bits shifted into the
47559     // result are all ones, not undef.
47560     return DAG.getConstant(-1, SDLoc(N), VT);
47561 
47562   auto MergeShifts = [&](SDValue X, uint64_t Amt0, uint64_t Amt1) {
47563     unsigned NewShiftVal = Amt0 + Amt1;
47564     if (NewShiftVal >= NumBitsPerElt) {
47565       // Out of range logical bit shifts are guaranteed to be zero.
47566       // Out of range arithmetic bit shifts splat the sign bit.
47567       if (LogicalShift)
47568         return DAG.getConstant(0, SDLoc(N), VT);
47569       NewShiftVal = NumBitsPerElt - 1;
47570     }
47571     return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
47572                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
47573   };
47574 
47575   // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
47576   if (Opcode == N0.getOpcode())
47577     return MergeShifts(N0.getOperand(0), ShiftVal, N0.getConstantOperandVal(1));
47578 
47579   // (shl (add X, X), C) -> (shl X, (C + 1))
47580   if (Opcode == X86ISD::VSHLI && N0.getOpcode() == ISD::ADD &&
47581       N0.getOperand(0) == N0.getOperand(1))
47582     return MergeShifts(N0.getOperand(0), ShiftVal, 1);
47583 
47584   // We can decode 'whole byte' logical bit shifts as shuffles.
47585   if (LogicalShift && (ShiftVal % 8) == 0) {
47586     SDValue Op(N, 0);
47587     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47588       return Res;
47589   }
47590 
47591   // Attempt to detect an expanded vXi64 SIGN_EXTEND_INREG vXi1 pattern, and
47592   // convert to a splatted v2Xi32 SIGN_EXTEND_INREG pattern:
47593   // psrad(pshufd(psllq(X,63),1,1,3,3),31) ->
47594   // pshufd(psrad(pslld(X,31),31),0,0,2,2).
47595   if (Opcode == X86ISD::VSRAI && NumBitsPerElt == 32 && ShiftVal == 31 &&
47596       N0.getOpcode() == X86ISD::PSHUFD &&
47597       N0.getConstantOperandVal(1) == getV4X86ShuffleImm({1, 1, 3, 3}) &&
47598       N0->hasOneUse()) {
47599     SDValue BC = peekThroughOneUseBitcasts(N0.getOperand(0));
47600     if (BC.getOpcode() == X86ISD::VSHLI &&
47601         BC.getScalarValueSizeInBits() == 64 &&
47602         BC.getConstantOperandVal(1) == 63) {
47603       SDLoc DL(N);
47604       SDValue Src = BC.getOperand(0);
47605       Src = DAG.getBitcast(VT, Src);
47606       Src = DAG.getNode(X86ISD::PSHUFD, DL, VT, Src,
47607                         getV4X86ShuffleImm8ForMask({0, 0, 2, 2}, DL, DAG));
47608       Src = DAG.getNode(X86ISD::VSHLI, DL, VT, Src, N1);
47609       Src = DAG.getNode(X86ISD::VSRAI, DL, VT, Src, N1);
47610       return Src;
47611     }
47612   }
47613 
47614   auto TryConstantFold = [&](SDValue V) {
47615     APInt UndefElts;
47616     SmallVector<APInt, 32> EltBits;
47617     if (!getTargetConstantBitsFromNode(V, NumBitsPerElt, UndefElts, EltBits))
47618       return SDValue();
47619     assert(EltBits.size() == VT.getVectorNumElements() &&
47620            "Unexpected shift value type");
47621     // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
47622     // created an undef input due to no input bits being demanded, but user
47623     // still expects 0 in other bits.
47624     for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
47625       APInt &Elt = EltBits[i];
47626       if (UndefElts[i])
47627         Elt = 0;
47628       else if (X86ISD::VSHLI == Opcode)
47629         Elt <<= ShiftVal;
47630       else if (X86ISD::VSRAI == Opcode)
47631         Elt.ashrInPlace(ShiftVal);
47632       else
47633         Elt.lshrInPlace(ShiftVal);
47634     }
47635     // Reset undef elements since they were zeroed above.
47636     UndefElts = 0;
47637     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
47638   };
47639 
47640   // Constant Folding.
47641   if (N->isOnlyUserOf(N0.getNode())) {
47642     if (SDValue C = TryConstantFold(N0))
47643       return C;
47644 
47645     // Fold (shift (logic X, C2), C1) -> (logic (shift X, C1), (shift C2, C1))
47646     // Don't break NOT patterns.
47647     SDValue BC = peekThroughOneUseBitcasts(N0);
47648     if (ISD::isBitwiseLogicOp(BC.getOpcode()) &&
47649         BC->isOnlyUserOf(BC.getOperand(1).getNode()) &&
47650         !ISD::isBuildVectorAllOnes(BC.getOperand(1).getNode())) {
47651       if (SDValue RHS = TryConstantFold(BC.getOperand(1))) {
47652         SDLoc DL(N);
47653         SDValue LHS = DAG.getNode(Opcode, DL, VT,
47654                                   DAG.getBitcast(VT, BC.getOperand(0)), N1);
47655         return DAG.getNode(BC.getOpcode(), DL, VT, LHS, RHS);
47656       }
47657     }
47658   }
47659 
47660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47661   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBitsPerElt),
47662                                DCI))
47663     return SDValue(N, 0);
47664 
47665   return SDValue();
47666 }
47667 
combineVectorInsert(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47668 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
47669                                    TargetLowering::DAGCombinerInfo &DCI,
47670                                    const X86Subtarget &Subtarget) {
47671   EVT VT = N->getValueType(0);
47672   unsigned Opcode = N->getOpcode();
47673   assert(((Opcode == X86ISD::PINSRB && VT == MVT::v16i8) ||
47674           (Opcode == X86ISD::PINSRW && VT == MVT::v8i16) ||
47675           Opcode == ISD::INSERT_VECTOR_ELT) &&
47676          "Unexpected vector insertion");
47677 
47678   SDValue Vec = N->getOperand(0);
47679   SDValue Scl = N->getOperand(1);
47680   SDValue Idx = N->getOperand(2);
47681 
47682   // Fold insert_vector_elt(undef, elt, 0) --> scalar_to_vector(elt).
47683   if (Opcode == ISD::INSERT_VECTOR_ELT && Vec.isUndef() && isNullConstant(Idx))
47684     return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Scl);
47685 
47686   if (Opcode == X86ISD::PINSRB || Opcode == X86ISD::PINSRW) {
47687     unsigned NumBitsPerElt = VT.getScalarSizeInBits();
47688     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47689     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
47690                                  APInt::getAllOnes(NumBitsPerElt), DCI))
47691       return SDValue(N, 0);
47692   }
47693 
47694   // Attempt to combine insertion patterns to a shuffle.
47695   if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
47696     SDValue Op(N, 0);
47697     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
47698       return Res;
47699   }
47700 
47701   return SDValue();
47702 }
47703 
47704 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
47705 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
47706 /// OR -> CMPNEQSS.
combineCompareEqual(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47707 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
47708                                    TargetLowering::DAGCombinerInfo &DCI,
47709                                    const X86Subtarget &Subtarget) {
47710   unsigned opcode;
47711 
47712   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
47713   // we're requiring SSE2 for both.
47714   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
47715     SDValue N0 = N->getOperand(0);
47716     SDValue N1 = N->getOperand(1);
47717     SDValue CMP0 = N0.getOperand(1);
47718     SDValue CMP1 = N1.getOperand(1);
47719     SDLoc DL(N);
47720 
47721     // The SETCCs should both refer to the same CMP.
47722     if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
47723       return SDValue();
47724 
47725     SDValue CMP00 = CMP0->getOperand(0);
47726     SDValue CMP01 = CMP0->getOperand(1);
47727     EVT     VT    = CMP00.getValueType();
47728 
47729     if (VT == MVT::f32 || VT == MVT::f64 ||
47730         (VT == MVT::f16 && Subtarget.hasFP16())) {
47731       bool ExpectingFlags = false;
47732       // Check for any users that want flags:
47733       for (const SDNode *U : N->uses()) {
47734         if (ExpectingFlags)
47735           break;
47736 
47737         switch (U->getOpcode()) {
47738         default:
47739         case ISD::BR_CC:
47740         case ISD::BRCOND:
47741         case ISD::SELECT:
47742           ExpectingFlags = true;
47743           break;
47744         case ISD::CopyToReg:
47745         case ISD::SIGN_EXTEND:
47746         case ISD::ZERO_EXTEND:
47747         case ISD::ANY_EXTEND:
47748           break;
47749         }
47750       }
47751 
47752       if (!ExpectingFlags) {
47753         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
47754         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
47755 
47756         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
47757           X86::CondCode tmp = cc0;
47758           cc0 = cc1;
47759           cc1 = tmp;
47760         }
47761 
47762         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
47763             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
47764           // FIXME: need symbolic constants for these magic numbers.
47765           // See X86ATTInstPrinter.cpp:printSSECC().
47766           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
47767           if (Subtarget.hasAVX512()) {
47768             SDValue FSetCC =
47769                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
47770                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
47771             // Need to fill with zeros to ensure the bitcast will produce zeroes
47772             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
47773             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
47774                                       DAG.getConstant(0, DL, MVT::v16i1),
47775                                       FSetCC, DAG.getIntPtrConstant(0, DL));
47776             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
47777                                       N->getSimpleValueType(0));
47778           }
47779           SDValue OnesOrZeroesF =
47780               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
47781                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
47782 
47783           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
47784           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
47785 
47786           if (is64BitFP && !Subtarget.is64Bit()) {
47787             // On a 32-bit target, we cannot bitcast the 64-bit float to a
47788             // 64-bit integer, since that's not a legal type. Since
47789             // OnesOrZeroesF is all ones or all zeroes, we don't need all the
47790             // bits, but can do this little dance to extract the lowest 32 bits
47791             // and work with those going forward.
47792             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
47793                                            OnesOrZeroesF);
47794             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
47795             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
47796                                         Vector32, DAG.getIntPtrConstant(0, DL));
47797             IntVT = MVT::i32;
47798           }
47799 
47800           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
47801           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
47802                                       DAG.getConstant(1, DL, IntVT));
47803           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
47804                                               ANDed);
47805           return OneBitOfTruth;
47806         }
47807       }
47808     }
47809   }
47810   return SDValue();
47811 }
47812 
47813 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
combineAndNotIntoANDNP(SDNode * N,SelectionDAG & DAG)47814 static SDValue combineAndNotIntoANDNP(SDNode *N, SelectionDAG &DAG) {
47815   assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDNP");
47816 
47817   MVT VT = N->getSimpleValueType(0);
47818   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
47819     return SDValue();
47820 
47821   SDValue X, Y;
47822   SDValue N0 = N->getOperand(0);
47823   SDValue N1 = N->getOperand(1);
47824 
47825   if (SDValue Not = IsNOT(N0, DAG)) {
47826     X = Not;
47827     Y = N1;
47828   } else if (SDValue Not = IsNOT(N1, DAG)) {
47829     X = Not;
47830     Y = N0;
47831   } else
47832     return SDValue();
47833 
47834   X = DAG.getBitcast(VT, X);
47835   Y = DAG.getBitcast(VT, Y);
47836   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
47837 }
47838 
47839 /// Try to fold:
47840 ///   and (vector_shuffle<Z,...,Z>
47841 ///            (insert_vector_elt undef, (xor X, -1), Z), undef), Y
47842 ///   ->
47843 ///   andnp (vector_shuffle<Z,...,Z>
47844 ///              (insert_vector_elt undef, X, Z), undef), Y
combineAndShuffleNot(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)47845 static SDValue combineAndShuffleNot(SDNode *N, SelectionDAG &DAG,
47846                                     const X86Subtarget &Subtarget) {
47847   assert(N->getOpcode() == ISD::AND && "Unexpected opcode combine into ANDNP");
47848 
47849   EVT VT = N->getValueType(0);
47850   // Do not split 256 and 512 bit vectors with SSE2 as they overwrite original
47851   // value and require extra moves.
47852   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
47853         ((VT.is256BitVector() || VT.is512BitVector()) && Subtarget.hasAVX())))
47854     return SDValue();
47855 
47856   auto GetNot = [&DAG](SDValue V) {
47857     auto *SVN = dyn_cast<ShuffleVectorSDNode>(peekThroughOneUseBitcasts(V));
47858     // TODO: SVN->hasOneUse() is a strong condition. It can be relaxed if all
47859     // end-users are ISD::AND including cases
47860     // (and(extract_vector_element(SVN), Y)).
47861     if (!SVN || !SVN->hasOneUse() || !SVN->isSplat() ||
47862         !SVN->getOperand(1).isUndef()) {
47863       return SDValue();
47864     }
47865     SDValue IVEN = SVN->getOperand(0);
47866     if (IVEN.getOpcode() != ISD::INSERT_VECTOR_ELT ||
47867         !IVEN.getOperand(0).isUndef() || !IVEN.hasOneUse())
47868       return SDValue();
47869     if (!isa<ConstantSDNode>(IVEN.getOperand(2)) ||
47870         IVEN.getConstantOperandAPInt(2) != SVN->getSplatIndex())
47871       return SDValue();
47872     SDValue Src = IVEN.getOperand(1);
47873     if (SDValue Not = IsNOT(Src, DAG)) {
47874       SDValue NotSrc = DAG.getBitcast(Src.getValueType(), Not);
47875       SDValue NotIVEN =
47876           DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(IVEN), IVEN.getValueType(),
47877                       IVEN.getOperand(0), NotSrc, IVEN.getOperand(2));
47878       return DAG.getVectorShuffle(SVN->getValueType(0), SDLoc(SVN), NotIVEN,
47879                                   SVN->getOperand(1), SVN->getMask());
47880     }
47881     return SDValue();
47882   };
47883 
47884   SDValue X, Y;
47885   SDValue N0 = N->getOperand(0);
47886   SDValue N1 = N->getOperand(1);
47887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47888 
47889   if (SDValue Not = GetNot(N0)) {
47890     X = Not;
47891     Y = N1;
47892   } else if (SDValue Not = GetNot(N1)) {
47893     X = Not;
47894     Y = N0;
47895   } else
47896     return SDValue();
47897 
47898   X = DAG.getBitcast(VT, X);
47899   Y = DAG.getBitcast(VT, Y);
47900   SDLoc DL(N);
47901 
47902   // We do not split for SSE at all, but we need to split vectors for AVX1 and
47903   // AVX2.
47904   if (!Subtarget.useAVX512Regs() && VT.is512BitVector() &&
47905       TLI.isTypeLegal(VT.getHalfNumVectorElementsVT(*DAG.getContext()))) {
47906     SDValue LoX, HiX;
47907     std::tie(LoX, HiX) = splitVector(X, DAG, DL);
47908     SDValue LoY, HiY;
47909     std::tie(LoY, HiY) = splitVector(Y, DAG, DL);
47910     EVT SplitVT = LoX.getValueType();
47911     SDValue LoV = DAG.getNode(X86ISD::ANDNP, DL, SplitVT, {LoX, LoY});
47912     SDValue HiV = DAG.getNode(X86ISD::ANDNP, DL, SplitVT, {HiX, HiY});
47913     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, {LoV, HiV});
47914   }
47915 
47916   if (TLI.isTypeLegal(VT))
47917     return DAG.getNode(X86ISD::ANDNP, DL, VT, {X, Y});
47918 
47919   return SDValue();
47920 }
47921 
47922 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
47923 // logical operations, like in the example below.
47924 //   or (and (truncate x, truncate y)),
47925 //      (xor (truncate z, build_vector (constants)))
47926 // Given a target type \p VT, we generate
47927 //   or (and x, y), (xor z, zext(build_vector (constants)))
47928 // given x, y and z are of type \p VT. We can do so, if operands are either
47929 // truncates from VT types, the second operand is a vector of constants or can
47930 // be recursively promoted.
PromoteMaskArithmetic(SDNode * N,EVT VT,SelectionDAG & DAG,unsigned Depth)47931 static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
47932                                      unsigned Depth) {
47933   // Limit recursion to avoid excessive compile times.
47934   if (Depth >= SelectionDAG::MaxRecursionDepth)
47935     return SDValue();
47936 
47937   if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
47938       N->getOpcode() != ISD::OR)
47939     return SDValue();
47940 
47941   SDValue N0 = N->getOperand(0);
47942   SDValue N1 = N->getOperand(1);
47943   SDLoc DL(N);
47944 
47945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47946   if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
47947     return SDValue();
47948 
47949   if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
47950     N0 = NN0;
47951   else {
47952     // The Left side has to be a trunc.
47953     if (N0.getOpcode() != ISD::TRUNCATE)
47954       return SDValue();
47955 
47956     // The type of the truncated inputs.
47957     if (N0.getOperand(0).getValueType() != VT)
47958       return SDValue();
47959 
47960     N0 = N0.getOperand(0);
47961   }
47962 
47963   if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
47964     N1 = NN1;
47965   else {
47966     // The right side has to be a 'trunc' or a constant vector.
47967     bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
47968                     N1.getOperand(0).getValueType() == VT;
47969     if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
47970       return SDValue();
47971 
47972     if (RHSTrunc)
47973       N1 = N1.getOperand(0);
47974     else
47975       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
47976   }
47977 
47978   return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
47979 }
47980 
47981 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
47982 // register. In most cases we actually compare or select YMM-sized registers
47983 // and mixing the two types creates horrible code. This method optimizes
47984 // some of the transition sequences.
47985 // Even with AVX-512 this is still useful for removing casts around logical
47986 // operations on vXi1 mask types.
PromoteMaskArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)47987 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
47988                                      const X86Subtarget &Subtarget) {
47989   EVT VT = N->getValueType(0);
47990   assert(VT.isVector() && "Expected vector type");
47991 
47992   SDLoc DL(N);
47993   assert((N->getOpcode() == ISD::ANY_EXTEND ||
47994           N->getOpcode() == ISD::ZERO_EXTEND ||
47995           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
47996 
47997   SDValue Narrow = N->getOperand(0);
47998   EVT NarrowVT = Narrow.getValueType();
47999 
48000   // Generate the wide operation.
48001   SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
48002   if (!Op)
48003     return SDValue();
48004   switch (N->getOpcode()) {
48005   default: llvm_unreachable("Unexpected opcode");
48006   case ISD::ANY_EXTEND:
48007     return Op;
48008   case ISD::ZERO_EXTEND:
48009     return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
48010   case ISD::SIGN_EXTEND:
48011     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
48012                        Op, DAG.getValueType(NarrowVT));
48013   }
48014 }
48015 
convertIntLogicToFPLogicOpcode(unsigned Opcode)48016 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
48017   unsigned FPOpcode;
48018   switch (Opcode) {
48019   default: llvm_unreachable("Unexpected input node for FP logic conversion");
48020   case ISD::AND: FPOpcode = X86ISD::FAND; break;
48021   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
48022   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
48023   }
48024   return FPOpcode;
48025 }
48026 
48027 /// If both input operands of a logic op are being cast from floating-point
48028 /// types or FP compares, try to convert this into a floating-point logic node
48029 /// to avoid unnecessary moves from SSE to integer registers.
convertIntLogicToFPLogic(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48030 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
48031                                         TargetLowering::DAGCombinerInfo &DCI,
48032                                         const X86Subtarget &Subtarget) {
48033   EVT VT = N->getValueType(0);
48034   SDValue N0 = N->getOperand(0);
48035   SDValue N1 = N->getOperand(1);
48036   SDLoc DL(N);
48037 
48038   if (!((N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) ||
48039         (N0.getOpcode() == ISD::SETCC && N1.getOpcode() == ISD::SETCC)))
48040     return SDValue();
48041 
48042   SDValue N00 = N0.getOperand(0);
48043   SDValue N10 = N1.getOperand(0);
48044   EVT N00Type = N00.getValueType();
48045   EVT N10Type = N10.getValueType();
48046 
48047   // Ensure that both types are the same and are legal scalar fp types.
48048   if (N00Type != N10Type || !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
48049                               (Subtarget.hasSSE2() && N00Type == MVT::f64) ||
48050                               (Subtarget.hasFP16() && N00Type == MVT::f16)))
48051     return SDValue();
48052 
48053   if (N0.getOpcode() == ISD::BITCAST && !DCI.isBeforeLegalizeOps()) {
48054     unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
48055     SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
48056     return DAG.getBitcast(VT, FPLogic);
48057   }
48058 
48059   if (VT != MVT::i1 || N0.getOpcode() != ISD::SETCC || !N0.hasOneUse() ||
48060       !N1.hasOneUse())
48061     return SDValue();
48062 
48063   ISD::CondCode CC0 = cast<CondCodeSDNode>(N0.getOperand(2))->get();
48064   ISD::CondCode CC1 = cast<CondCodeSDNode>(N1.getOperand(2))->get();
48065 
48066   // The vector ISA for FP predicates is incomplete before AVX, so converting
48067   // COMIS* to CMPS* may not be a win before AVX.
48068   if (!Subtarget.hasAVX() &&
48069       !(cheapX86FSETCC_SSE(CC0) && cheapX86FSETCC_SSE(CC1)))
48070     return SDValue();
48071 
48072   // Convert scalar FP compares and logic to vector compares (COMIS* to CMPS*)
48073   // and vector logic:
48074   // logic (setcc N00, N01), (setcc N10, N11) -->
48075   // extelt (logic (setcc (s2v N00), (s2v N01)), setcc (s2v N10), (s2v N11))), 0
48076   unsigned NumElts = 128 / N00Type.getSizeInBits();
48077   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), N00Type, NumElts);
48078   EVT BoolVecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
48079   SDValue ZeroIndex = DAG.getVectorIdxConstant(0, DL);
48080   SDValue N01 = N0.getOperand(1);
48081   SDValue N11 = N1.getOperand(1);
48082   SDValue Vec00 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N00);
48083   SDValue Vec01 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N01);
48084   SDValue Vec10 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N10);
48085   SDValue Vec11 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, N11);
48086   SDValue Setcc0 = DAG.getSetCC(DL, BoolVecVT, Vec00, Vec01, CC0);
48087   SDValue Setcc1 = DAG.getSetCC(DL, BoolVecVT, Vec10, Vec11, CC1);
48088   SDValue Logic = DAG.getNode(N->getOpcode(), DL, BoolVecVT, Setcc0, Setcc1);
48089   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Logic, ZeroIndex);
48090 }
48091 
48092 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
48093 // to reduce XMM->GPR traffic.
combineBitOpWithMOVMSK(SDNode * N,SelectionDAG & DAG)48094 static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
48095   unsigned Opc = N->getOpcode();
48096   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
48097          "Unexpected bit opcode");
48098 
48099   SDValue N0 = N->getOperand(0);
48100   SDValue N1 = N->getOperand(1);
48101 
48102   // Both operands must be single use MOVMSK.
48103   if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
48104       N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
48105     return SDValue();
48106 
48107   SDValue Vec0 = N0.getOperand(0);
48108   SDValue Vec1 = N1.getOperand(0);
48109   EVT VecVT0 = Vec0.getValueType();
48110   EVT VecVT1 = Vec1.getValueType();
48111 
48112   // Both MOVMSK operands must be from vectors of the same size and same element
48113   // size, but its OK for a fp/int diff.
48114   if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
48115       VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
48116     return SDValue();
48117 
48118   SDLoc DL(N);
48119   unsigned VecOpc =
48120       VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
48121   SDValue Result =
48122       DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
48123   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
48124 }
48125 
48126 // Attempt to fold BITOP(SHIFT(X,Z),SHIFT(Y,Z)) -> SHIFT(BITOP(X,Y),Z).
48127 // NOTE: This is a very limited case of what SimplifyUsingDistributiveLaws
48128 // handles in InstCombine.
combineBitOpWithShift(SDNode * N,SelectionDAG & DAG)48129 static SDValue combineBitOpWithShift(SDNode *N, SelectionDAG &DAG) {
48130   unsigned Opc = N->getOpcode();
48131   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
48132          "Unexpected bit opcode");
48133 
48134   SDValue N0 = N->getOperand(0);
48135   SDValue N1 = N->getOperand(1);
48136   EVT VT = N->getValueType(0);
48137 
48138   // Both operands must be single use.
48139   if (!N0.hasOneUse() || !N1.hasOneUse())
48140     return SDValue();
48141 
48142   // Search for matching shifts.
48143   SDValue BC0 = peekThroughOneUseBitcasts(N0);
48144   SDValue BC1 = peekThroughOneUseBitcasts(N1);
48145 
48146   unsigned BCOpc = BC0.getOpcode();
48147   EVT BCVT = BC0.getValueType();
48148   if (BCOpc != BC1->getOpcode() || BCVT != BC1.getValueType())
48149     return SDValue();
48150 
48151   switch (BCOpc) {
48152   case X86ISD::VSHLI:
48153   case X86ISD::VSRLI:
48154   case X86ISD::VSRAI: {
48155     if (BC0.getOperand(1) != BC1.getOperand(1))
48156       return SDValue();
48157 
48158     SDLoc DL(N);
48159     SDValue BitOp =
48160         DAG.getNode(Opc, DL, BCVT, BC0.getOperand(0), BC1.getOperand(0));
48161     SDValue Shift = DAG.getNode(BCOpc, DL, BCVT, BitOp, BC0.getOperand(1));
48162     return DAG.getBitcast(VT, Shift);
48163   }
48164   }
48165 
48166   return SDValue();
48167 }
48168 
48169 // Attempt to fold:
48170 // BITOP(PACKSS(X,Z),PACKSS(Y,W)) --> PACKSS(BITOP(X,Y),BITOP(Z,W)).
48171 // TODO: Handle PACKUS handling.
combineBitOpWithPACK(SDNode * N,SelectionDAG & DAG)48172 static SDValue combineBitOpWithPACK(SDNode *N, SelectionDAG &DAG) {
48173   unsigned Opc = N->getOpcode();
48174   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
48175          "Unexpected bit opcode");
48176 
48177   SDValue N0 = N->getOperand(0);
48178   SDValue N1 = N->getOperand(1);
48179   EVT VT = N->getValueType(0);
48180 
48181   // Both operands must be single use.
48182   if (!N0.hasOneUse() || !N1.hasOneUse())
48183     return SDValue();
48184 
48185   // Search for matching packs.
48186   N0 = peekThroughOneUseBitcasts(N0);
48187   N1 = peekThroughOneUseBitcasts(N1);
48188 
48189   if (N0.getOpcode() != X86ISD::PACKSS || N1.getOpcode() != X86ISD::PACKSS)
48190     return SDValue();
48191 
48192   MVT DstVT = N0.getSimpleValueType();
48193   if (DstVT != N1.getSimpleValueType())
48194     return SDValue();
48195 
48196   MVT SrcVT = N0.getOperand(0).getSimpleValueType();
48197   unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
48198 
48199   // Limit to allsignbits packing.
48200   if (DAG.ComputeNumSignBits(N0.getOperand(0)) != NumSrcBits ||
48201       DAG.ComputeNumSignBits(N0.getOperand(1)) != NumSrcBits ||
48202       DAG.ComputeNumSignBits(N1.getOperand(0)) != NumSrcBits ||
48203       DAG.ComputeNumSignBits(N1.getOperand(1)) != NumSrcBits)
48204     return SDValue();
48205 
48206   SDLoc DL(N);
48207   SDValue LHS = DAG.getNode(Opc, DL, SrcVT, N0.getOperand(0), N1.getOperand(0));
48208   SDValue RHS = DAG.getNode(Opc, DL, SrcVT, N0.getOperand(1), N1.getOperand(1));
48209   return DAG.getBitcast(VT, DAG.getNode(X86ISD::PACKSS, DL, DstVT, LHS, RHS));
48210 }
48211 
48212 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
48213 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
48214 /// with a shift-right to eliminate loading the vector constant mask value.
combineAndMaskToShift(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48215 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
48216                                      const X86Subtarget &Subtarget) {
48217   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
48218   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
48219   EVT VT = Op0.getValueType();
48220   if (VT != Op1.getValueType() || !VT.isSimple() || !VT.isInteger())
48221     return SDValue();
48222 
48223   // Try to convert an "is positive" signbit masking operation into arithmetic
48224   // shift and "andn". This saves a materialization of a -1 vector constant.
48225   // The "is negative" variant should be handled more generally because it only
48226   // requires "and" rather than "andn":
48227   // and (pcmpgt X, -1), Y --> pandn (vsrai X, BitWidth - 1), Y
48228   //
48229   // This is limited to the original type to avoid producing even more bitcasts.
48230   // If the bitcasts can't be eliminated, then it is unlikely that this fold
48231   // will be profitable.
48232   if (N->getValueType(0) == VT &&
48233       supportedVectorShiftWithImm(VT, Subtarget, ISD::SRA)) {
48234     SDValue X, Y;
48235     if (Op1.getOpcode() == X86ISD::PCMPGT &&
48236         isAllOnesOrAllOnesSplat(Op1.getOperand(1)) && Op1.hasOneUse()) {
48237       X = Op1.getOperand(0);
48238       Y = Op0;
48239     } else if (Op0.getOpcode() == X86ISD::PCMPGT &&
48240                isAllOnesOrAllOnesSplat(Op0.getOperand(1)) && Op0.hasOneUse()) {
48241       X = Op0.getOperand(0);
48242       Y = Op1;
48243     }
48244     if (X && Y) {
48245       SDLoc DL(N);
48246       SDValue Sra =
48247           getTargetVShiftByConstNode(X86ISD::VSRAI, DL, VT.getSimpleVT(), X,
48248                                      VT.getScalarSizeInBits() - 1, DAG);
48249       return DAG.getNode(X86ISD::ANDNP, DL, VT, Sra, Y);
48250     }
48251   }
48252 
48253   APInt SplatVal;
48254   if (!X86::isConstantSplat(Op1, SplatVal, false) || !SplatVal.isMask())
48255     return SDValue();
48256 
48257   // Don't prevent creation of ANDN.
48258   if (isBitwiseNot(Op0))
48259     return SDValue();
48260 
48261   if (!supportedVectorShiftWithImm(VT, Subtarget, ISD::SRL))
48262     return SDValue();
48263 
48264   unsigned EltBitWidth = VT.getScalarSizeInBits();
48265   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
48266     return SDValue();
48267 
48268   SDLoc DL(N);
48269   unsigned ShiftVal = SplatVal.countr_one();
48270   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
48271   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT, Op0, ShAmt);
48272   return DAG.getBitcast(N->getValueType(0), Shift);
48273 }
48274 
48275 // Get the index node from the lowered DAG of a GEP IR instruction with one
48276 // indexing dimension.
getIndexFromUnindexedLoad(LoadSDNode * Ld)48277 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
48278   if (Ld->isIndexed())
48279     return SDValue();
48280 
48281   SDValue Base = Ld->getBasePtr();
48282 
48283   if (Base.getOpcode() != ISD::ADD)
48284     return SDValue();
48285 
48286   SDValue ShiftedIndex = Base.getOperand(0);
48287 
48288   if (ShiftedIndex.getOpcode() != ISD::SHL)
48289     return SDValue();
48290 
48291   return ShiftedIndex.getOperand(0);
48292 
48293 }
48294 
hasBZHI(const X86Subtarget & Subtarget,MVT VT)48295 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
48296   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
48297     switch (VT.getSizeInBits()) {
48298     default: return false;
48299     case 64: return Subtarget.is64Bit() ? true : false;
48300     case 32: return true;
48301     }
48302   }
48303   return false;
48304 }
48305 
48306 // This function recognizes cases where X86 bzhi instruction can replace and
48307 // 'and-load' sequence.
48308 // In case of loading integer value from an array of constants which is defined
48309 // as follows:
48310 //
48311 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
48312 //
48313 // then applying a bitwise and on the result with another input.
48314 // It's equivalent to performing bzhi (zero high bits) on the input, with the
48315 // same index of the load.
combineAndLoadToBZHI(SDNode * Node,SelectionDAG & DAG,const X86Subtarget & Subtarget)48316 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
48317                                     const X86Subtarget &Subtarget) {
48318   MVT VT = Node->getSimpleValueType(0);
48319   SDLoc dl(Node);
48320 
48321   // Check if subtarget has BZHI instruction for the node's type
48322   if (!hasBZHI(Subtarget, VT))
48323     return SDValue();
48324 
48325   // Try matching the pattern for both operands.
48326   for (unsigned i = 0; i < 2; i++) {
48327     SDValue N = Node->getOperand(i);
48328     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
48329 
48330      // continue if the operand is not a load instruction
48331     if (!Ld)
48332       return SDValue();
48333 
48334     const Value *MemOp = Ld->getMemOperand()->getValue();
48335 
48336     if (!MemOp)
48337       return SDValue();
48338 
48339     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
48340       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
48341         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
48342 
48343           Constant *Init = GV->getInitializer();
48344           Type *Ty = Init->getType();
48345           if (!isa<ConstantDataArray>(Init) ||
48346               !Ty->getArrayElementType()->isIntegerTy() ||
48347               Ty->getArrayElementType()->getScalarSizeInBits() !=
48348                   VT.getSizeInBits() ||
48349               Ty->getArrayNumElements() >
48350                   Ty->getArrayElementType()->getScalarSizeInBits())
48351             continue;
48352 
48353           // Check if the array's constant elements are suitable to our case.
48354           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
48355           bool ConstantsMatch = true;
48356           for (uint64_t j = 0; j < ArrayElementCount; j++) {
48357             auto *Elem = cast<ConstantInt>(Init->getAggregateElement(j));
48358             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
48359               ConstantsMatch = false;
48360               break;
48361             }
48362           }
48363           if (!ConstantsMatch)
48364             continue;
48365 
48366           // Do the transformation (For 32-bit type):
48367           // -> (and (load arr[idx]), inp)
48368           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
48369           //    that will be replaced with one bzhi instruction.
48370           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
48371           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
48372 
48373           // Get the Node which indexes into the array.
48374           SDValue Index = getIndexFromUnindexedLoad(Ld);
48375           if (!Index)
48376             return SDValue();
48377           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
48378 
48379           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
48380           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
48381 
48382           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
48383           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
48384 
48385           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
48386         }
48387       }
48388     }
48389   }
48390   return SDValue();
48391 }
48392 
48393 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
48394 // Where C is a mask containing the same number of bits as the setcc and
48395 // where the setcc will freely 0 upper bits of k-register. We can replace the
48396 // undef in the concat with 0s and remove the AND. This mainly helps with
48397 // v2i1/v4i1 setcc being casted to scalar.
combineScalarAndWithMaskSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48398 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
48399                                              const X86Subtarget &Subtarget) {
48400   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
48401 
48402   EVT VT = N->getValueType(0);
48403 
48404   // Make sure this is an AND with constant. We will check the value of the
48405   // constant later.
48406   auto *C1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
48407   if (!C1)
48408     return SDValue();
48409 
48410   // This is implied by the ConstantSDNode.
48411   assert(!VT.isVector() && "Expected scalar VT!");
48412 
48413   SDValue Src = N->getOperand(0);
48414   if (!Src.hasOneUse())
48415     return SDValue();
48416 
48417   // (Optionally) peek through any_extend().
48418   if (Src.getOpcode() == ISD::ANY_EXTEND) {
48419     if (!Src.getOperand(0).hasOneUse())
48420       return SDValue();
48421     Src = Src.getOperand(0);
48422   }
48423 
48424   if (Src.getOpcode() != ISD::BITCAST || !Src.getOperand(0).hasOneUse())
48425     return SDValue();
48426 
48427   Src = Src.getOperand(0);
48428   EVT SrcVT = Src.getValueType();
48429 
48430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48431   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
48432       !TLI.isTypeLegal(SrcVT))
48433     return SDValue();
48434 
48435   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
48436     return SDValue();
48437 
48438   // We only care about the first subvector of the concat, we expect the
48439   // other subvectors to be ignored due to the AND if we make the change.
48440   SDValue SubVec = Src.getOperand(0);
48441   EVT SubVecVT = SubVec.getValueType();
48442 
48443   // The RHS of the AND should be a mask with as many bits as SubVec.
48444   if (!TLI.isTypeLegal(SubVecVT) ||
48445       !C1->getAPIntValue().isMask(SubVecVT.getVectorNumElements()))
48446     return SDValue();
48447 
48448   // First subvector should be a setcc with a legal result type or a
48449   // AND containing at least one setcc with a legal result type.
48450   auto IsLegalSetCC = [&](SDValue V) {
48451     if (V.getOpcode() != ISD::SETCC)
48452       return false;
48453     EVT SetccVT = V.getOperand(0).getValueType();
48454     if (!TLI.isTypeLegal(SetccVT) ||
48455         !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
48456       return false;
48457     if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
48458       return false;
48459     return true;
48460   };
48461   if (!(IsLegalSetCC(SubVec) || (SubVec.getOpcode() == ISD::AND &&
48462                                  (IsLegalSetCC(SubVec.getOperand(0)) ||
48463                                   IsLegalSetCC(SubVec.getOperand(1))))))
48464     return SDValue();
48465 
48466   // We passed all the checks. Rebuild the concat_vectors with zeroes
48467   // and cast it back to VT.
48468   SDLoc dl(N);
48469   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
48470                               DAG.getConstant(0, dl, SubVecVT));
48471   Ops[0] = SubVec;
48472   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
48473                                Ops);
48474   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcVT.getSizeInBits());
48475   return DAG.getZExtOrTrunc(DAG.getBitcast(IntVT, Concat), dl, VT);
48476 }
48477 
getBMIMatchingOp(unsigned Opc,SelectionDAG & DAG,SDValue OpMustEq,SDValue Op,unsigned Depth)48478 static SDValue getBMIMatchingOp(unsigned Opc, SelectionDAG &DAG,
48479                                 SDValue OpMustEq, SDValue Op, unsigned Depth) {
48480   // We don't want to go crazy with the recursion here. This isn't a super
48481   // important optimization.
48482   static constexpr unsigned kMaxDepth = 2;
48483 
48484   // Only do this re-ordering if op has one use.
48485   if (!Op.hasOneUse())
48486     return SDValue();
48487 
48488   SDLoc DL(Op);
48489   // If we hit another assosiative op, recurse further.
48490   if (Op.getOpcode() == Opc) {
48491     // Done recursing.
48492     if (Depth++ >= kMaxDepth)
48493       return SDValue();
48494 
48495     for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx)
48496       if (SDValue R =
48497               getBMIMatchingOp(Opc, DAG, OpMustEq, Op.getOperand(OpIdx), Depth))
48498         return DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), R,
48499                            Op.getOperand(1 - OpIdx));
48500 
48501   } else if (Op.getOpcode() == ISD::SUB) {
48502     if (Opc == ISD::AND) {
48503       // BLSI: (and x, (sub 0, x))
48504       if (isNullConstant(Op.getOperand(0)) && Op.getOperand(1) == OpMustEq)
48505         return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
48506     }
48507     // Opc must be ISD::AND or ISD::XOR
48508     // BLSR: (and x, (sub x, 1))
48509     // BLSMSK: (xor x, (sub x, 1))
48510     if (isOneConstant(Op.getOperand(1)) && Op.getOperand(0) == OpMustEq)
48511       return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
48512 
48513   } else if (Op.getOpcode() == ISD::ADD) {
48514     // Opc must be ISD::AND or ISD::XOR
48515     // BLSR: (and x, (add x, -1))
48516     // BLSMSK: (xor x, (add x, -1))
48517     if (isAllOnesConstant(Op.getOperand(1)) && Op.getOperand(0) == OpMustEq)
48518       return DAG.getNode(Opc, DL, Op.getValueType(), OpMustEq, Op);
48519   }
48520   return SDValue();
48521 }
48522 
combineBMILogicOp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48523 static SDValue combineBMILogicOp(SDNode *N, SelectionDAG &DAG,
48524                                  const X86Subtarget &Subtarget) {
48525   EVT VT = N->getValueType(0);
48526   // Make sure this node is a candidate for BMI instructions.
48527   if (!Subtarget.hasBMI() || !VT.isScalarInteger() ||
48528       (VT != MVT::i32 && VT != MVT::i64))
48529     return SDValue();
48530 
48531   assert(N->getOpcode() == ISD::AND || N->getOpcode() == ISD::XOR);
48532 
48533   // Try and match LHS and RHS.
48534   for (unsigned OpIdx = 0; OpIdx < 2; ++OpIdx)
48535     if (SDValue OpMatch =
48536             getBMIMatchingOp(N->getOpcode(), DAG, N->getOperand(OpIdx),
48537                              N->getOperand(1 - OpIdx), 0))
48538       return OpMatch;
48539   return SDValue();
48540 }
48541 
combineAnd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48542 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
48543                           TargetLowering::DAGCombinerInfo &DCI,
48544                           const X86Subtarget &Subtarget) {
48545   SDValue N0 = N->getOperand(0);
48546   SDValue N1 = N->getOperand(1);
48547   EVT VT = N->getValueType(0);
48548   SDLoc dl(N);
48549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48550 
48551   // If this is SSE1 only convert to FAND to avoid scalarization.
48552   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
48553     return DAG.getBitcast(MVT::v4i32,
48554                           DAG.getNode(X86ISD::FAND, dl, MVT::v4f32,
48555                                       DAG.getBitcast(MVT::v4f32, N0),
48556                                       DAG.getBitcast(MVT::v4f32, N1)));
48557   }
48558 
48559   // Use a 32-bit and+zext if upper bits known zero.
48560   if (VT == MVT::i64 && Subtarget.is64Bit() && !isa<ConstantSDNode>(N1)) {
48561     APInt HiMask = APInt::getHighBitsSet(64, 32);
48562     if (DAG.MaskedValueIsZero(N1, HiMask) ||
48563         DAG.MaskedValueIsZero(N0, HiMask)) {
48564       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N0);
48565       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N1);
48566       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
48567                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
48568     }
48569   }
48570 
48571   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
48572   // TODO: Support multiple SrcOps.
48573   if (VT == MVT::i1) {
48574     SmallVector<SDValue, 2> SrcOps;
48575     SmallVector<APInt, 2> SrcPartials;
48576     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
48577         SrcOps.size() == 1) {
48578       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
48579       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
48580       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
48581       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
48582         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
48583       if (Mask) {
48584         assert(SrcPartials[0].getBitWidth() == NumElts &&
48585                "Unexpected partial reduction mask");
48586         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
48587         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
48588         return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
48589       }
48590     }
48591   }
48592 
48593   // InstCombine converts:
48594   //    `(-x << C0) & C1`
48595   // to
48596   //    `(x * (Pow2_Ceil(C1) - (1 << C0))) & C1`
48597   // This saves an IR instruction but on x86 the neg/shift version is preferable
48598   // so undo the transform.
48599 
48600   if (N0.getOpcode() == ISD::MUL && N0.hasOneUse()) {
48601     // TODO: We don't actually need a splat for this, we just need the checks to
48602     // hold for each element.
48603     ConstantSDNode *N1C = isConstOrConstSplat(N1, /*AllowUndefs*/ true,
48604                                               /*AllowTruncation*/ false);
48605     ConstantSDNode *N01C =
48606         isConstOrConstSplat(N0.getOperand(1), /*AllowUndefs*/ true,
48607                             /*AllowTruncation*/ false);
48608     if (N1C && N01C) {
48609       const APInt &MulC = N01C->getAPIntValue();
48610       const APInt &AndC = N1C->getAPIntValue();
48611       APInt MulCLowBit = MulC & (-MulC);
48612       if (MulC.uge(AndC) && !MulC.isPowerOf2() &&
48613           (MulCLowBit + MulC).isPowerOf2()) {
48614         SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
48615                                   N0.getOperand(0));
48616         int32_t MulCLowBitLog = MulCLowBit.exactLogBase2();
48617         assert(MulCLowBitLog != -1 &&
48618                "Isolated lowbit is somehow not a power of 2!");
48619         SDValue Shift = DAG.getNode(ISD::SHL, dl, VT, Neg,
48620                                     DAG.getConstant(MulCLowBitLog, dl, VT));
48621         return DAG.getNode(ISD::AND, dl, VT, Shift, N1);
48622       }
48623     }
48624   }
48625 
48626   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
48627     return V;
48628 
48629   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
48630     return R;
48631 
48632   if (SDValue R = combineBitOpWithShift(N, DAG))
48633     return R;
48634 
48635   if (SDValue R = combineBitOpWithPACK(N, DAG))
48636     return R;
48637 
48638   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
48639     return FPLogic;
48640 
48641   if (SDValue R = combineAndShuffleNot(N, DAG, Subtarget))
48642     return R;
48643 
48644   if (DCI.isBeforeLegalizeOps())
48645     return SDValue();
48646 
48647   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
48648     return R;
48649 
48650   if (SDValue R = combineAndNotIntoANDNP(N, DAG))
48651     return R;
48652 
48653   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
48654     return ShiftRight;
48655 
48656   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
48657     return R;
48658 
48659   // fold (and (mul x, c1), c2) -> (mul x, (and c1, c2))
48660   // iff c2 is all/no bits mask - i.e. a select-with-zero mask.
48661   // TODO: Handle PMULDQ/PMULUDQ/VPMADDWD/VPMADDUBSW?
48662   if (VT.isVector() && getTargetConstantFromNode(N1)) {
48663     unsigned Opc0 = N0.getOpcode();
48664     if ((Opc0 == ISD::MUL || Opc0 == ISD::MULHU || Opc0 == ISD::MULHS) &&
48665         getTargetConstantFromNode(N0.getOperand(1)) &&
48666         DAG.ComputeNumSignBits(N1) == VT.getScalarSizeInBits() &&
48667         N0->hasOneUse() && N0.getOperand(1)->hasOneUse()) {
48668       SDValue MaskMul = DAG.getNode(ISD::AND, dl, VT, N0.getOperand(1), N1);
48669       return DAG.getNode(Opc0, dl, VT, N0.getOperand(0), MaskMul);
48670     }
48671   }
48672 
48673   // Fold AND(SRL(X,Y),1) -> SETCC(BT(X,Y), COND_B) iff Y is not a constant
48674   // avoids slow variable shift (moving shift amount to ECX etc.)
48675   if (isOneConstant(N1) && N0->hasOneUse()) {
48676     SDValue Src = N0;
48677     while ((Src.getOpcode() == ISD::ZERO_EXTEND ||
48678             Src.getOpcode() == ISD::TRUNCATE) &&
48679            Src.getOperand(0)->hasOneUse())
48680       Src = Src.getOperand(0);
48681     bool ContainsNOT = false;
48682     X86::CondCode X86CC = X86::COND_B;
48683     // Peek through AND(NOT(SRL(X,Y)),1).
48684     if (isBitwiseNot(Src)) {
48685       Src = Src.getOperand(0);
48686       X86CC = X86::COND_AE;
48687       ContainsNOT = true;
48688     }
48689     if (Src.getOpcode() == ISD::SRL &&
48690         !isa<ConstantSDNode>(Src.getOperand(1))) {
48691       SDValue BitNo = Src.getOperand(1);
48692       Src = Src.getOperand(0);
48693       // Peek through AND(SRL(NOT(X),Y),1).
48694       if (isBitwiseNot(Src)) {
48695         Src = Src.getOperand(0);
48696         X86CC = X86CC == X86::COND_AE ? X86::COND_B : X86::COND_AE;
48697         ContainsNOT = true;
48698       }
48699       // If we have BMI2 then SHRX should be faster for i32/i64 cases.
48700       if (!(Subtarget.hasBMI2() && !ContainsNOT && VT.getSizeInBits() >= 32))
48701         if (SDValue BT = getBT(Src, BitNo, dl, DAG))
48702           return DAG.getZExtOrTrunc(getSETCC(X86CC, BT, dl, DAG), dl, VT);
48703     }
48704   }
48705 
48706   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
48707     // Attempt to recursively combine a bitmask AND with shuffles.
48708     SDValue Op(N, 0);
48709     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
48710       return Res;
48711 
48712     // If either operand is a constant mask, then only the elements that aren't
48713     // zero are actually demanded by the other operand.
48714     auto GetDemandedMasks = [&](SDValue Op) {
48715       APInt UndefElts;
48716       SmallVector<APInt> EltBits;
48717       int NumElts = VT.getVectorNumElements();
48718       int EltSizeInBits = VT.getScalarSizeInBits();
48719       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
48720       APInt DemandedElts = APInt::getAllOnes(NumElts);
48721       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
48722                                         EltBits)) {
48723         DemandedBits.clearAllBits();
48724         DemandedElts.clearAllBits();
48725         for (int I = 0; I != NumElts; ++I) {
48726           if (UndefElts[I]) {
48727             // We can't assume an undef src element gives an undef dst - the
48728             // other src might be zero.
48729             DemandedBits.setAllBits();
48730             DemandedElts.setBit(I);
48731           } else if (!EltBits[I].isZero()) {
48732             DemandedBits |= EltBits[I];
48733             DemandedElts.setBit(I);
48734           }
48735         }
48736       }
48737       return std::make_pair(DemandedBits, DemandedElts);
48738     };
48739     APInt Bits0, Elts0;
48740     APInt Bits1, Elts1;
48741     std::tie(Bits0, Elts0) = GetDemandedMasks(N1);
48742     std::tie(Bits1, Elts1) = GetDemandedMasks(N0);
48743 
48744     if (TLI.SimplifyDemandedVectorElts(N0, Elts0, DCI) ||
48745         TLI.SimplifyDemandedVectorElts(N1, Elts1, DCI) ||
48746         TLI.SimplifyDemandedBits(N0, Bits0, Elts0, DCI) ||
48747         TLI.SimplifyDemandedBits(N1, Bits1, Elts1, DCI)) {
48748       if (N->getOpcode() != ISD::DELETED_NODE)
48749         DCI.AddToWorklist(N);
48750       return SDValue(N, 0);
48751     }
48752 
48753     SDValue NewN0 = TLI.SimplifyMultipleUseDemandedBits(N0, Bits0, Elts0, DAG);
48754     SDValue NewN1 = TLI.SimplifyMultipleUseDemandedBits(N1, Bits1, Elts1, DAG);
48755     if (NewN0 || NewN1)
48756       return DAG.getNode(ISD::AND, dl, VT, NewN0 ? NewN0 : N0,
48757                          NewN1 ? NewN1 : N1);
48758   }
48759 
48760   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
48761   if ((VT.getScalarSizeInBits() % 8) == 0 &&
48762       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
48763       isa<ConstantSDNode>(N0.getOperand(1)) && N0->hasOneUse()) {
48764     SDValue BitMask = N1;
48765     SDValue SrcVec = N0.getOperand(0);
48766     EVT SrcVecVT = SrcVec.getValueType();
48767 
48768     // Check that the constant bitmask masks whole bytes.
48769     APInt UndefElts;
48770     SmallVector<APInt, 64> EltBits;
48771     if (VT == SrcVecVT.getScalarType() && N0->isOnlyUserOf(SrcVec.getNode()) &&
48772         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
48773         llvm::all_of(EltBits, [](const APInt &M) {
48774           return M.isZero() || M.isAllOnes();
48775         })) {
48776       unsigned NumElts = SrcVecVT.getVectorNumElements();
48777       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
48778       unsigned Idx = N0.getConstantOperandVal(1);
48779 
48780       // Create a root shuffle mask from the byte mask and the extracted index.
48781       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
48782       for (unsigned i = 0; i != Scale; ++i) {
48783         if (UndefElts[i])
48784           continue;
48785         int VecIdx = Scale * Idx + i;
48786         ShuffleMask[VecIdx] = EltBits[i].isZero() ? SM_SentinelZero : VecIdx;
48787       }
48788 
48789       if (SDValue Shuffle = combineX86ShufflesRecursively(
48790               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
48791               X86::MaxShuffleCombineDepth,
48792               /*HasVarMask*/ false, /*AllowVarCrossLaneMask*/ true,
48793               /*AllowVarPerLaneMask*/ true, DAG, Subtarget))
48794         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Shuffle,
48795                            N0.getOperand(1));
48796     }
48797   }
48798 
48799   if (SDValue R = combineBMILogicOp(N, DAG, Subtarget))
48800     return R;
48801 
48802   return SDValue();
48803 }
48804 
48805 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
canonicalizeBitSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48806 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
48807                                      const X86Subtarget &Subtarget) {
48808   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
48809 
48810   MVT VT = N->getSimpleValueType(0);
48811   unsigned EltSizeInBits = VT.getScalarSizeInBits();
48812   if (!VT.isVector() || (EltSizeInBits % 8) != 0)
48813     return SDValue();
48814 
48815   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
48816   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
48817   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
48818     return SDValue();
48819 
48820   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
48821   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
48822   if (!(Subtarget.hasXOP() || useVPTERNLOG(Subtarget, VT) ||
48823         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
48824     return SDValue();
48825 
48826   // Attempt to extract constant byte masks.
48827   APInt UndefElts0, UndefElts1;
48828   SmallVector<APInt, 32> EltBits0, EltBits1;
48829   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
48830                                      false, false))
48831     return SDValue();
48832   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
48833                                      false, false))
48834     return SDValue();
48835 
48836   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
48837     // TODO - add UNDEF elts support.
48838     if (UndefElts0[i] || UndefElts1[i])
48839       return SDValue();
48840     if (EltBits0[i] != ~EltBits1[i])
48841       return SDValue();
48842   }
48843 
48844   SDLoc DL(N);
48845 
48846   if (useVPTERNLOG(Subtarget, VT)) {
48847     // Emit a VPTERNLOG node directly - 0xCA is the imm code for A?B:C.
48848     // VPTERNLOG is only available as vXi32/64-bit types.
48849     MVT OpSVT = EltSizeInBits <= 32 ? MVT::i32 : MVT::i64;
48850     MVT OpVT =
48851         MVT::getVectorVT(OpSVT, VT.getSizeInBits() / OpSVT.getSizeInBits());
48852     SDValue A = DAG.getBitcast(OpVT, N0.getOperand(1));
48853     SDValue B = DAG.getBitcast(OpVT, N0.getOperand(0));
48854     SDValue C = DAG.getBitcast(OpVT, N1.getOperand(0));
48855     SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
48856     SDValue Res = getAVX512Node(X86ISD::VPTERNLOG, DL, OpVT, {A, B, C, Imm},
48857                                 DAG, Subtarget);
48858     return DAG.getBitcast(VT, Res);
48859   }
48860 
48861   SDValue X = N->getOperand(0);
48862   SDValue Y =
48863       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
48864                   DAG.getBitcast(VT, N1.getOperand(0)));
48865   return DAG.getNode(ISD::OR, DL, VT, X, Y);
48866 }
48867 
48868 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
matchLogicBlend(SDNode * N,SDValue & X,SDValue & Y,SDValue & Mask)48869 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
48870   if (N->getOpcode() != ISD::OR)
48871     return false;
48872 
48873   SDValue N0 = N->getOperand(0);
48874   SDValue N1 = N->getOperand(1);
48875 
48876   // Canonicalize AND to LHS.
48877   if (N1.getOpcode() == ISD::AND)
48878     std::swap(N0, N1);
48879 
48880   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
48881   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
48882     return false;
48883 
48884   Mask = N1.getOperand(0);
48885   X = N1.getOperand(1);
48886 
48887   // Check to see if the mask appeared in both the AND and ANDNP.
48888   if (N0.getOperand(0) == Mask)
48889     Y = N0.getOperand(1);
48890   else if (N0.getOperand(1) == Mask)
48891     Y = N0.getOperand(0);
48892   else
48893     return false;
48894 
48895   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
48896   // ANDNP combine allows other combines to happen that prevent matching.
48897   return true;
48898 }
48899 
48900 // Try to fold:
48901 //   (or (and (m, y), (pandn m, x)))
48902 // into:
48903 //   (vselect m, x, y)
48904 // As a special case, try to fold:
48905 //   (or (and (m, (sub 0, x)), (pandn m, x)))
48906 // into:
48907 //   (sub (xor X, M), M)
combineLogicBlendIntoPBLENDV(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48908 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
48909                                             const X86Subtarget &Subtarget) {
48910   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
48911 
48912   EVT VT = N->getValueType(0);
48913   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
48914         (VT.is256BitVector() && Subtarget.hasInt256())))
48915     return SDValue();
48916 
48917   SDValue X, Y, Mask;
48918   if (!matchLogicBlend(N, X, Y, Mask))
48919     return SDValue();
48920 
48921   // Validate that X, Y, and Mask are bitcasts, and see through them.
48922   Mask = peekThroughBitcasts(Mask);
48923   X = peekThroughBitcasts(X);
48924   Y = peekThroughBitcasts(Y);
48925 
48926   EVT MaskVT = Mask.getValueType();
48927   unsigned EltBits = MaskVT.getScalarSizeInBits();
48928 
48929   // TODO: Attempt to handle floating point cases as well?
48930   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
48931     return SDValue();
48932 
48933   SDLoc DL(N);
48934 
48935   // Attempt to combine to conditional negate: (sub (xor X, M), M)
48936   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
48937                                                            DAG, Subtarget))
48938     return Res;
48939 
48940   // PBLENDVB is only available on SSE 4.1.
48941   if (!Subtarget.hasSSE41())
48942     return SDValue();
48943 
48944   // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
48945   if (Subtarget.hasVLX())
48946     return SDValue();
48947 
48948   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
48949 
48950   X = DAG.getBitcast(BlendVT, X);
48951   Y = DAG.getBitcast(BlendVT, Y);
48952   Mask = DAG.getBitcast(BlendVT, Mask);
48953   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
48954   return DAG.getBitcast(VT, Mask);
48955 }
48956 
48957 // Helper function for combineOrCmpEqZeroToCtlzSrl
48958 // Transforms:
48959 //   seteq(cmp x, 0)
48960 //   into:
48961 //   srl(ctlz x), log2(bitsize(x))
48962 // Input pattern is checked by caller.
lowerX86CmpEqZeroToCtlzSrl(SDValue Op,SelectionDAG & DAG)48963 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) {
48964   SDValue Cmp = Op.getOperand(1);
48965   EVT VT = Cmp.getOperand(0).getValueType();
48966   unsigned Log2b = Log2_32(VT.getSizeInBits());
48967   SDLoc dl(Op);
48968   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
48969   // The result of the shift is true or false, and on X86, the 32-bit
48970   // encoding of shr and lzcnt is more desirable.
48971   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
48972   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
48973                             DAG.getConstant(Log2b, dl, MVT::i8));
48974   return Scc;
48975 }
48976 
48977 // Try to transform:
48978 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
48979 //   into:
48980 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
48981 // Will also attempt to match more generic cases, eg:
48982 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
48983 // Only applies if the target supports the FastLZCNT feature.
combineOrCmpEqZeroToCtlzSrl(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48984 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
48985                                            TargetLowering::DAGCombinerInfo &DCI,
48986                                            const X86Subtarget &Subtarget) {
48987   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
48988     return SDValue();
48989 
48990   auto isORCandidate = [](SDValue N) {
48991     return (N->getOpcode() == ISD::OR && N->hasOneUse());
48992   };
48993 
48994   // Check the zero extend is extending to 32-bit or more. The code generated by
48995   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
48996   // instructions to clear the upper bits.
48997   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
48998       !isORCandidate(N->getOperand(0)))
48999     return SDValue();
49000 
49001   // Check the node matches: setcc(eq, cmp 0)
49002   auto isSetCCCandidate = [](SDValue N) {
49003     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
49004            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
49005            N->getOperand(1).getOpcode() == X86ISD::CMP &&
49006            isNullConstant(N->getOperand(1).getOperand(1)) &&
49007            N->getOperand(1).getValueType().bitsGE(MVT::i32);
49008   };
49009 
49010   SDNode *OR = N->getOperand(0).getNode();
49011   SDValue LHS = OR->getOperand(0);
49012   SDValue RHS = OR->getOperand(1);
49013 
49014   // Save nodes matching or(or, setcc(eq, cmp 0)).
49015   SmallVector<SDNode *, 2> ORNodes;
49016   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
49017           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
49018     ORNodes.push_back(OR);
49019     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
49020     LHS = OR->getOperand(0);
49021     RHS = OR->getOperand(1);
49022   }
49023 
49024   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
49025   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
49026       !isORCandidate(SDValue(OR, 0)))
49027     return SDValue();
49028 
49029   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
49030   // to
49031   // or(srl(ctlz),srl(ctlz)).
49032   // The dag combiner can then fold it into:
49033   // srl(or(ctlz, ctlz)).
49034   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, DAG);
49035   SDValue Ret, NewRHS;
49036   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG)))
49037     Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, NewLHS, NewRHS);
49038 
49039   if (!Ret)
49040     return SDValue();
49041 
49042   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
49043   while (!ORNodes.empty()) {
49044     OR = ORNodes.pop_back_val();
49045     LHS = OR->getOperand(0);
49046     RHS = OR->getOperand(1);
49047     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
49048     if (RHS->getOpcode() == ISD::OR)
49049       std::swap(LHS, RHS);
49050     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, DAG);
49051     if (!NewRHS)
49052       return SDValue();
49053     Ret = DAG.getNode(ISD::OR, SDLoc(OR), MVT::i32, Ret, NewRHS);
49054   }
49055 
49056   return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
49057 }
49058 
foldMaskedMergeImpl(SDValue And0_L,SDValue And0_R,SDValue And1_L,SDValue And1_R,const SDLoc & DL,SelectionDAG & DAG)49059 static SDValue foldMaskedMergeImpl(SDValue And0_L, SDValue And0_R,
49060                                    SDValue And1_L, SDValue And1_R,
49061                                    const SDLoc &DL, SelectionDAG &DAG) {
49062   if (!isBitwiseNot(And0_L, true) || !And0_L->hasOneUse())
49063     return SDValue();
49064   SDValue NotOp = And0_L->getOperand(0);
49065   if (NotOp == And1_R)
49066     std::swap(And1_R, And1_L);
49067   if (NotOp != And1_L)
49068     return SDValue();
49069 
49070   // (~(NotOp) & And0_R) | (NotOp & And1_R)
49071   // --> ((And0_R ^ And1_R) & NotOp) ^ And1_R
49072   EVT VT = And1_L->getValueType(0);
49073   SDValue Freeze_And0_R = DAG.getNode(ISD::FREEZE, SDLoc(), VT, And0_R);
49074   SDValue Xor0 = DAG.getNode(ISD::XOR, DL, VT, And1_R, Freeze_And0_R);
49075   SDValue And = DAG.getNode(ISD::AND, DL, VT, Xor0, NotOp);
49076   SDValue Xor1 = DAG.getNode(ISD::XOR, DL, VT, And, Freeze_And0_R);
49077   return Xor1;
49078 }
49079 
49080 /// Fold "masked merge" expressions like `(m & x) | (~m & y)` into the
49081 /// equivalent `((x ^ y) & m) ^ y)` pattern.
49082 /// This is typically a better representation for  targets without a fused
49083 /// "and-not" operation. This function is intended to be called from a
49084 /// `TargetLowering::PerformDAGCombine` callback on `ISD::OR` nodes.
foldMaskedMerge(SDNode * Node,SelectionDAG & DAG)49085 static SDValue foldMaskedMerge(SDNode *Node, SelectionDAG &DAG) {
49086   // Note that masked-merge variants using XOR or ADD expressions are
49087   // normalized to OR by InstCombine so we only check for OR.
49088   assert(Node->getOpcode() == ISD::OR && "Must be called with ISD::OR node");
49089   SDValue N0 = Node->getOperand(0);
49090   if (N0->getOpcode() != ISD::AND || !N0->hasOneUse())
49091     return SDValue();
49092   SDValue N1 = Node->getOperand(1);
49093   if (N1->getOpcode() != ISD::AND || !N1->hasOneUse())
49094     return SDValue();
49095 
49096   SDLoc DL(Node);
49097   SDValue N00 = N0->getOperand(0);
49098   SDValue N01 = N0->getOperand(1);
49099   SDValue N10 = N1->getOperand(0);
49100   SDValue N11 = N1->getOperand(1);
49101   if (SDValue Result = foldMaskedMergeImpl(N00, N01, N10, N11, DL, DAG))
49102     return Result;
49103   if (SDValue Result = foldMaskedMergeImpl(N01, N00, N10, N11, DL, DAG))
49104     return Result;
49105   if (SDValue Result = foldMaskedMergeImpl(N10, N11, N00, N01, DL, DAG))
49106     return Result;
49107   if (SDValue Result = foldMaskedMergeImpl(N11, N10, N00, N01, DL, DAG))
49108     return Result;
49109   return SDValue();
49110 }
49111 
49112 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
49113 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
49114 /// with CMP+{ADC, SBB}.
49115 /// Also try (ADD/SUB)+(AND(SRL,1)) bit extraction pattern with BT+{ADC, SBB}.
combineAddOrSubToADCOrSBB(bool IsSub,const SDLoc & DL,EVT VT,SDValue X,SDValue Y,SelectionDAG & DAG,bool ZeroSecondOpOnly=false)49116 static SDValue combineAddOrSubToADCOrSBB(bool IsSub, const SDLoc &DL, EVT VT,
49117                                          SDValue X, SDValue Y,
49118                                          SelectionDAG &DAG,
49119                                          bool ZeroSecondOpOnly = false) {
49120   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
49121     return SDValue();
49122 
49123   // Look through a one-use zext.
49124   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse())
49125     Y = Y.getOperand(0);
49126 
49127   X86::CondCode CC;
49128   SDValue EFLAGS;
49129   if (Y.getOpcode() == X86ISD::SETCC && Y.hasOneUse()) {
49130     CC = (X86::CondCode)Y.getConstantOperandVal(0);
49131     EFLAGS = Y.getOperand(1);
49132   } else if (Y.getOpcode() == ISD::AND && isOneConstant(Y.getOperand(1)) &&
49133              Y.hasOneUse()) {
49134     EFLAGS = LowerAndToBT(Y, ISD::SETNE, DL, DAG, CC);
49135   }
49136 
49137   if (!EFLAGS)
49138     return SDValue();
49139 
49140   // If X is -1 or 0, then we have an opportunity to avoid constants required in
49141   // the general case below.
49142   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
49143   if (ConstantX && !ZeroSecondOpOnly) {
49144     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnes()) ||
49145         (IsSub && CC == X86::COND_B && ConstantX->isZero())) {
49146       // This is a complicated way to get -1 or 0 from the carry flag:
49147       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
49148       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
49149       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49150                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49151                          EFLAGS);
49152     }
49153 
49154     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnes()) ||
49155         (IsSub && CC == X86::COND_A && ConstantX->isZero())) {
49156       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
49157           EFLAGS.getValueType().isInteger() &&
49158           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
49159         // Swap the operands of a SUB, and we have the same pattern as above.
49160         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
49161         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
49162         SDValue NewSub = DAG.getNode(
49163             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
49164             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
49165         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
49166         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49167                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49168                            NewEFLAGS);
49169       }
49170     }
49171   }
49172 
49173   if (CC == X86::COND_B) {
49174     // X + SETB Z --> adc X, 0
49175     // X - SETB Z --> sbb X, 0
49176     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
49177                        DAG.getVTList(VT, MVT::i32), X,
49178                        DAG.getConstant(0, DL, VT), EFLAGS);
49179   }
49180 
49181   if (ZeroSecondOpOnly)
49182     return SDValue();
49183 
49184   if (CC == X86::COND_A) {
49185     // Try to convert COND_A into COND_B in an attempt to facilitate
49186     // materializing "setb reg".
49187     //
49188     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
49189     // cannot take an immediate as its first operand.
49190     //
49191     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
49192         EFLAGS.getValueType().isInteger() &&
49193         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
49194       SDValue NewSub =
49195           DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
49196                       EFLAGS.getOperand(1), EFLAGS.getOperand(0));
49197       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
49198       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
49199                          DAG.getVTList(VT, MVT::i32), X,
49200                          DAG.getConstant(0, DL, VT), NewEFLAGS);
49201     }
49202   }
49203 
49204   if (CC == X86::COND_AE) {
49205     // X + SETAE --> sbb X, -1
49206     // X - SETAE --> adc X, -1
49207     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
49208                        DAG.getVTList(VT, MVT::i32), X,
49209                        DAG.getConstant(-1, DL, VT), EFLAGS);
49210   }
49211 
49212   if (CC == X86::COND_BE) {
49213     // X + SETBE --> sbb X, -1
49214     // X - SETBE --> adc X, -1
49215     // Try to convert COND_BE into COND_AE in an attempt to facilitate
49216     // materializing "setae reg".
49217     //
49218     // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
49219     // cannot take an immediate as its first operand.
49220     //
49221     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
49222         EFLAGS.getValueType().isInteger() &&
49223         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
49224       SDValue NewSub =
49225           DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
49226                       EFLAGS.getOperand(1), EFLAGS.getOperand(0));
49227       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
49228       return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
49229                          DAG.getVTList(VT, MVT::i32), X,
49230                          DAG.getConstant(-1, DL, VT), NewEFLAGS);
49231     }
49232   }
49233 
49234   if (CC != X86::COND_E && CC != X86::COND_NE)
49235     return SDValue();
49236 
49237   if (EFLAGS.getOpcode() != X86ISD::CMP || !EFLAGS.hasOneUse() ||
49238       !X86::isZeroNode(EFLAGS.getOperand(1)) ||
49239       !EFLAGS.getOperand(0).getValueType().isInteger())
49240     return SDValue();
49241 
49242   SDValue Z = EFLAGS.getOperand(0);
49243   EVT ZVT = Z.getValueType();
49244 
49245   // If X is -1 or 0, then we have an opportunity to avoid constants required in
49246   // the general case below.
49247   if (ConstantX) {
49248     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
49249     // fake operands:
49250     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
49251     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
49252     if ((IsSub && CC == X86::COND_NE && ConstantX->isZero()) ||
49253         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnes())) {
49254       SDValue Zero = DAG.getConstant(0, DL, ZVT);
49255       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
49256       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
49257       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49258                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49259                          SDValue(Neg.getNode(), 1));
49260     }
49261 
49262     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
49263     // with fake operands:
49264     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
49265     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
49266     if ((IsSub && CC == X86::COND_E && ConstantX->isZero()) ||
49267         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnes())) {
49268       SDValue One = DAG.getConstant(1, DL, ZVT);
49269       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
49270       SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
49271       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
49272                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
49273                          Cmp1.getValue(1));
49274     }
49275   }
49276 
49277   // (cmp Z, 1) sets the carry flag if Z is 0.
49278   SDValue One = DAG.getConstant(1, DL, ZVT);
49279   SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
49280   SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
49281 
49282   // Add the flags type for ADC/SBB nodes.
49283   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
49284 
49285   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
49286   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
49287   if (CC == X86::COND_NE)
49288     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
49289                        DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
49290 
49291   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
49292   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
49293   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
49294                      DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
49295 }
49296 
49297 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
49298 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
49299 /// with CMP+{ADC, SBB}.
combineAddOrSubToADCOrSBB(SDNode * N,SelectionDAG & DAG)49300 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
49301   bool IsSub = N->getOpcode() == ISD::SUB;
49302   SDValue X = N->getOperand(0);
49303   SDValue Y = N->getOperand(1);
49304   EVT VT = N->getValueType(0);
49305   SDLoc DL(N);
49306 
49307   if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, X, Y, DAG))
49308     return ADCOrSBB;
49309 
49310   // Commute and try again (negate the result for subtracts).
49311   if (SDValue ADCOrSBB = combineAddOrSubToADCOrSBB(IsSub, DL, VT, Y, X, DAG)) {
49312     if (IsSub)
49313       ADCOrSBB =
49314           DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), ADCOrSBB);
49315     return ADCOrSBB;
49316   }
49317 
49318   return SDValue();
49319 }
49320 
combineOrXorWithSETCC(SDNode * N,SDValue N0,SDValue N1,SelectionDAG & DAG)49321 static SDValue combineOrXorWithSETCC(SDNode *N, SDValue N0, SDValue N1,
49322                                      SelectionDAG &DAG) {
49323   assert((N->getOpcode() == ISD::XOR || N->getOpcode() == ISD::OR) &&
49324          "Unexpected opcode");
49325 
49326   // Delegate to combineAddOrSubToADCOrSBB if we have:
49327   //
49328   //   (xor/or (zero_extend (setcc)) imm)
49329   //
49330   // where imm is odd if and only if we have xor, in which case the XOR/OR are
49331   // equivalent to a SUB/ADD, respectively.
49332   if (N0.getOpcode() == ISD::ZERO_EXTEND &&
49333       N0.getOperand(0).getOpcode() == X86ISD::SETCC && N0.hasOneUse()) {
49334     if (auto *N1C = dyn_cast<ConstantSDNode>(N1)) {
49335       bool IsSub = N->getOpcode() == ISD::XOR;
49336       bool N1COdd = N1C->getZExtValue() & 1;
49337       if (IsSub ? N1COdd : !N1COdd) {
49338         SDLoc DL(N);
49339         EVT VT = N->getValueType(0);
49340         if (SDValue R = combineAddOrSubToADCOrSBB(IsSub, DL, VT, N1, N0, DAG))
49341           return R;
49342       }
49343     }
49344   }
49345 
49346   return SDValue();
49347 }
49348 
combineOr(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)49349 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
49350                          TargetLowering::DAGCombinerInfo &DCI,
49351                          const X86Subtarget &Subtarget) {
49352   SDValue N0 = N->getOperand(0);
49353   SDValue N1 = N->getOperand(1);
49354   EVT VT = N->getValueType(0);
49355   SDLoc dl(N);
49356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49357 
49358   // If this is SSE1 only convert to FOR to avoid scalarization.
49359   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
49360     return DAG.getBitcast(MVT::v4i32,
49361                           DAG.getNode(X86ISD::FOR, dl, MVT::v4f32,
49362                                       DAG.getBitcast(MVT::v4f32, N0),
49363                                       DAG.getBitcast(MVT::v4f32, N1)));
49364   }
49365 
49366   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
49367   // TODO: Support multiple SrcOps.
49368   if (VT == MVT::i1) {
49369     SmallVector<SDValue, 2> SrcOps;
49370     SmallVector<APInt, 2> SrcPartials;
49371     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
49372         SrcOps.size() == 1) {
49373       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
49374       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
49375       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
49376       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
49377         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
49378       if (Mask) {
49379         assert(SrcPartials[0].getBitWidth() == NumElts &&
49380                "Unexpected partial reduction mask");
49381         SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
49382         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
49383         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
49384         return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
49385       }
49386     }
49387   }
49388 
49389   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
49390     return R;
49391 
49392   if (SDValue R = combineBitOpWithShift(N, DAG))
49393     return R;
49394 
49395   if (SDValue R = combineBitOpWithPACK(N, DAG))
49396     return R;
49397 
49398   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
49399     return FPLogic;
49400 
49401   if (DCI.isBeforeLegalizeOps())
49402     return SDValue();
49403 
49404   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
49405     return R;
49406 
49407   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
49408     return R;
49409 
49410   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
49411     return R;
49412 
49413   // (0 - SetCC) | C -> (zext (not SetCC)) * (C + 1) - 1 if we can get a LEA out of it.
49414   if ((VT == MVT::i32 || VT == MVT::i64) &&
49415       N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
49416       isNullConstant(N0.getOperand(0))) {
49417     SDValue Cond = N0.getOperand(1);
49418     if (Cond.getOpcode() == ISD::ZERO_EXTEND && Cond.hasOneUse())
49419       Cond = Cond.getOperand(0);
49420 
49421     if (Cond.getOpcode() == X86ISD::SETCC && Cond.hasOneUse()) {
49422       if (auto *CN = dyn_cast<ConstantSDNode>(N1)) {
49423         uint64_t Val = CN->getZExtValue();
49424         if (Val == 1 || Val == 2 || Val == 3 || Val == 4 || Val == 7 || Val == 8) {
49425           X86::CondCode CCode = (X86::CondCode)Cond.getConstantOperandVal(0);
49426           CCode = X86::GetOppositeBranchCondition(CCode);
49427           SDValue NotCond = getSETCC(CCode, Cond.getOperand(1), SDLoc(Cond), DAG);
49428 
49429           SDValue R = DAG.getZExtOrTrunc(NotCond, dl, VT);
49430           R = DAG.getNode(ISD::MUL, dl, VT, R, DAG.getConstant(Val + 1, dl, VT));
49431           R = DAG.getNode(ISD::SUB, dl, VT, R, DAG.getConstant(1, dl, VT));
49432           return R;
49433         }
49434       }
49435     }
49436   }
49437 
49438   // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
49439   // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
49440   // iff the upper elements of the non-shifted arg are zero.
49441   // KUNPCK require 16+ bool vector elements.
49442   if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
49443     unsigned NumElts = VT.getVectorNumElements();
49444     unsigned HalfElts = NumElts / 2;
49445     APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
49446     if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
49447         N1.getConstantOperandAPInt(1) == HalfElts &&
49448         DAG.MaskedVectorIsZero(N0, UpperElts)) {
49449       return DAG.getNode(
49450           ISD::CONCAT_VECTORS, dl, VT,
49451           extractSubVector(N0, 0, DAG, dl, HalfElts),
49452           extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
49453     }
49454     if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
49455         N0.getConstantOperandAPInt(1) == HalfElts &&
49456         DAG.MaskedVectorIsZero(N1, UpperElts)) {
49457       return DAG.getNode(
49458           ISD::CONCAT_VECTORS, dl, VT,
49459           extractSubVector(N1, 0, DAG, dl, HalfElts),
49460           extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
49461     }
49462   }
49463 
49464   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
49465     // Attempt to recursively combine an OR of shuffles.
49466     SDValue Op(N, 0);
49467     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
49468       return Res;
49469 
49470     // If either operand is a constant mask, then only the elements that aren't
49471     // allones are actually demanded by the other operand.
49472     auto SimplifyUndemandedElts = [&](SDValue Op, SDValue OtherOp) {
49473       APInt UndefElts;
49474       SmallVector<APInt> EltBits;
49475       int NumElts = VT.getVectorNumElements();
49476       int EltSizeInBits = VT.getScalarSizeInBits();
49477       if (!getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts, EltBits))
49478         return false;
49479 
49480       APInt DemandedElts = APInt::getZero(NumElts);
49481       for (int I = 0; I != NumElts; ++I)
49482         if (!EltBits[I].isAllOnes())
49483           DemandedElts.setBit(I);
49484 
49485       return TLI.SimplifyDemandedVectorElts(OtherOp, DemandedElts, DCI);
49486     };
49487     if (SimplifyUndemandedElts(N0, N1) || SimplifyUndemandedElts(N1, N0)) {
49488       if (N->getOpcode() != ISD::DELETED_NODE)
49489         DCI.AddToWorklist(N);
49490       return SDValue(N, 0);
49491     }
49492   }
49493 
49494   // We should fold "masked merge" patterns when `andn` is not available.
49495   if (!Subtarget.hasBMI() && VT.isScalarInteger() && VT != MVT::i1)
49496     if (SDValue R = foldMaskedMerge(N, DAG))
49497       return R;
49498 
49499   if (SDValue R = combineOrXorWithSETCC(N, N0, N1, DAG))
49500     return R;
49501 
49502   return SDValue();
49503 }
49504 
49505 /// Try to turn tests against the signbit in the form of:
49506 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
49507 /// into:
49508 ///   SETGT(X, -1)
foldXorTruncShiftIntoCmp(SDNode * N,SelectionDAG & DAG)49509 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
49510   // This is only worth doing if the output type is i8 or i1.
49511   EVT ResultType = N->getValueType(0);
49512   if (ResultType != MVT::i8 && ResultType != MVT::i1)
49513     return SDValue();
49514 
49515   SDValue N0 = N->getOperand(0);
49516   SDValue N1 = N->getOperand(1);
49517 
49518   // We should be performing an xor against a truncated shift.
49519   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
49520     return SDValue();
49521 
49522   // Make sure we are performing an xor against one.
49523   if (!isOneConstant(N1))
49524     return SDValue();
49525 
49526   // SetCC on x86 zero extends so only act on this if it's a logical shift.
49527   SDValue Shift = N0.getOperand(0);
49528   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
49529     return SDValue();
49530 
49531   // Make sure we are truncating from one of i16, i32 or i64.
49532   EVT ShiftTy = Shift.getValueType();
49533   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
49534     return SDValue();
49535 
49536   // Make sure the shift amount extracts the sign bit.
49537   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
49538       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
49539     return SDValue();
49540 
49541   // Create a greater-than comparison against -1.
49542   // N.B. Using SETGE against 0 works but we want a canonical looking
49543   // comparison, using SETGT matches up with what TranslateX86CC.
49544   SDLoc DL(N);
49545   SDValue ShiftOp = Shift.getOperand(0);
49546   EVT ShiftOpTy = ShiftOp.getValueType();
49547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49548   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
49549                                                *DAG.getContext(), ResultType);
49550   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
49551                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
49552   if (SetCCResultType != ResultType)
49553     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
49554   return Cond;
49555 }
49556 
49557 /// Turn vector tests of the signbit in the form of:
49558 ///   xor (sra X, elt_size(X)-1), -1
49559 /// into:
49560 ///   pcmpgt X, -1
49561 ///
49562 /// This should be called before type legalization because the pattern may not
49563 /// persist after that.
foldVectorXorShiftIntoCmp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)49564 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
49565                                          const X86Subtarget &Subtarget) {
49566   EVT VT = N->getValueType(0);
49567   if (!VT.isSimple())
49568     return SDValue();
49569 
49570   switch (VT.getSimpleVT().SimpleTy) {
49571   default: return SDValue();
49572   case MVT::v16i8:
49573   case MVT::v8i16:
49574   case MVT::v4i32:
49575   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
49576   case MVT::v32i8:
49577   case MVT::v16i16:
49578   case MVT::v8i32:
49579   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
49580   }
49581 
49582   // There must be a shift right algebraic before the xor, and the xor must be a
49583   // 'not' operation.
49584   SDValue Shift = N->getOperand(0);
49585   SDValue Ones = N->getOperand(1);
49586   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
49587       !ISD::isBuildVectorAllOnes(Ones.getNode()))
49588     return SDValue();
49589 
49590   // The shift should be smearing the sign bit across each vector element.
49591   auto *ShiftAmt =
49592       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
49593   if (!ShiftAmt ||
49594       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
49595     return SDValue();
49596 
49597   // Create a greater-than comparison against -1. We don't use the more obvious
49598   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
49599   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
49600 }
49601 
49602 /// Detect patterns of truncation with unsigned saturation:
49603 ///
49604 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
49605 ///   Return the source value x to be truncated or SDValue() if the pattern was
49606 ///   not matched.
49607 ///
49608 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
49609 ///   where C1 >= 0 and C2 is unsigned max of destination type.
49610 ///
49611 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
49612 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
49613 ///
49614 ///   These two patterns are equivalent to:
49615 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
49616 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
49617 ///   pattern was not matched.
detectUSatPattern(SDValue In,EVT VT,SelectionDAG & DAG,const SDLoc & DL)49618 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
49619                                  const SDLoc &DL) {
49620   EVT InVT = In.getValueType();
49621 
49622   // Saturation with truncation. We truncate from InVT to VT.
49623   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
49624          "Unexpected types for truncate operation");
49625 
49626   // Match min/max and return limit value as a parameter.
49627   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
49628     if (V.getOpcode() == Opcode &&
49629         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
49630       return V.getOperand(0);
49631     return SDValue();
49632   };
49633 
49634   APInt C1, C2;
49635   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
49636     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
49637     // the element size of the destination type.
49638     if (C2.isMask(VT.getScalarSizeInBits()))
49639       return UMin;
49640 
49641   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
49642     if (MatchMinMax(SMin, ISD::SMAX, C1))
49643       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
49644         return SMin;
49645 
49646   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
49647     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
49648       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
49649           C2.uge(C1)) {
49650         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
49651       }
49652 
49653   return SDValue();
49654 }
49655 
49656 /// Detect patterns of truncation with signed saturation:
49657 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
49658 ///                  signed_max_of_dest_type)) to dest_type)
49659 /// or:
49660 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
49661 ///                  signed_min_of_dest_type)) to dest_type).
49662 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
49663 /// Return the source value to be truncated or SDValue() if the pattern was not
49664 /// matched.
detectSSatPattern(SDValue In,EVT VT,bool MatchPackUS=false)49665 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
49666   unsigned NumDstBits = VT.getScalarSizeInBits();
49667   unsigned NumSrcBits = In.getScalarValueSizeInBits();
49668   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
49669 
49670   auto MatchMinMax = [](SDValue V, unsigned Opcode,
49671                         const APInt &Limit) -> SDValue {
49672     APInt C;
49673     if (V.getOpcode() == Opcode &&
49674         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
49675       return V.getOperand(0);
49676     return SDValue();
49677   };
49678 
49679   APInt SignedMax, SignedMin;
49680   if (MatchPackUS) {
49681     SignedMax = APInt::getAllOnes(NumDstBits).zext(NumSrcBits);
49682     SignedMin = APInt(NumSrcBits, 0);
49683   } else {
49684     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
49685     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
49686   }
49687 
49688   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
49689     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
49690       return SMax;
49691 
49692   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
49693     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
49694       return SMin;
49695 
49696   return SDValue();
49697 }
49698 
combineTruncateWithSat(SDValue In,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)49699 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
49700                                       SelectionDAG &DAG,
49701                                       const X86Subtarget &Subtarget) {
49702   if (!Subtarget.hasSSE2() || !VT.isVector())
49703     return SDValue();
49704 
49705   EVT SVT = VT.getVectorElementType();
49706   EVT InVT = In.getValueType();
49707   EVT InSVT = InVT.getVectorElementType();
49708 
49709   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
49710   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
49711   // and concatenate at the same time. Then we can use a final vpmovuswb to
49712   // clip to 0-255.
49713   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
49714       InVT == MVT::v16i32 && VT == MVT::v16i8) {
49715     if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
49716       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
49717       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
49718                                            DL, DAG, Subtarget);
49719       assert(Mid && "Failed to pack!");
49720       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
49721     }
49722   }
49723 
49724   // vXi32 truncate instructions are available with AVX512F.
49725   // vXi16 truncate instructions are only available with AVX512BW.
49726   // For 256-bit or smaller vectors, we require VLX.
49727   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
49728   // If the result type is 256-bits or larger and we have disable 512-bit
49729   // registers, we should go ahead and use the pack instructions if possible.
49730   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
49731                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
49732                       (InVT.getSizeInBits() > 128) &&
49733                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
49734                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
49735 
49736   if (!PreferAVX512 && VT.getVectorNumElements() > 1 &&
49737       isPowerOf2_32(VT.getVectorNumElements()) &&
49738       (SVT == MVT::i8 || SVT == MVT::i16) &&
49739       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
49740     if (SDValue USatVal = detectSSatPattern(In, VT, true)) {
49741       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
49742       if (SVT == MVT::i8 && InSVT == MVT::i32) {
49743         EVT MidVT = VT.changeVectorElementType(MVT::i16);
49744         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
49745                                              DAG, Subtarget);
49746         assert(Mid && "Failed to pack!");
49747         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
49748                                            Subtarget);
49749         assert(V && "Failed to pack!");
49750         return V;
49751       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
49752         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
49753                                       Subtarget);
49754     }
49755     if (SDValue SSatVal = detectSSatPattern(In, VT))
49756       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
49757                                     Subtarget);
49758   }
49759 
49760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49761   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
49762       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI()) &&
49763       (SVT == MVT::i32 || SVT == MVT::i16 || SVT == MVT::i8)) {
49764     unsigned TruncOpc = 0;
49765     SDValue SatVal;
49766     if (SDValue SSatVal = detectSSatPattern(In, VT)) {
49767       SatVal = SSatVal;
49768       TruncOpc = X86ISD::VTRUNCS;
49769     } else if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL)) {
49770       SatVal = USatVal;
49771       TruncOpc = X86ISD::VTRUNCUS;
49772     }
49773     if (SatVal) {
49774       unsigned ResElts = VT.getVectorNumElements();
49775       // If the input type is less than 512 bits and we don't have VLX, we need
49776       // to widen to 512 bits.
49777       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
49778         unsigned NumConcats = 512 / InVT.getSizeInBits();
49779         ResElts *= NumConcats;
49780         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
49781         ConcatOps[0] = SatVal;
49782         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
49783                                 NumConcats * InVT.getVectorNumElements());
49784         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
49785       }
49786       // Widen the result if its narrower than 128 bits.
49787       if (ResElts * SVT.getSizeInBits() < 128)
49788         ResElts = 128 / SVT.getSizeInBits();
49789       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
49790       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
49791       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
49792                          DAG.getIntPtrConstant(0, DL));
49793     }
49794   }
49795 
49796   return SDValue();
49797 }
49798 
49799 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
49800 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
49801 /// ISD::AVGCEILU (AVG) instruction.
detectAVGPattern(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)49802 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
49803                                 const X86Subtarget &Subtarget,
49804                                 const SDLoc &DL) {
49805   if (!VT.isVector())
49806     return SDValue();
49807   EVT InVT = In.getValueType();
49808   unsigned NumElems = VT.getVectorNumElements();
49809 
49810   EVT ScalarVT = VT.getVectorElementType();
49811   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) && NumElems >= 2))
49812     return SDValue();
49813 
49814   // InScalarVT is the intermediate type in AVG pattern and it should be greater
49815   // than the original input type (i8/i16).
49816   EVT InScalarVT = InVT.getVectorElementType();
49817   if (InScalarVT.getFixedSizeInBits() <= ScalarVT.getFixedSizeInBits())
49818     return SDValue();
49819 
49820   if (!Subtarget.hasSSE2())
49821     return SDValue();
49822 
49823   // Detect the following pattern:
49824   //
49825   //   %1 = zext <N x i8> %a to <N x i32>
49826   //   %2 = zext <N x i8> %b to <N x i32>
49827   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
49828   //   %4 = add nuw nsw <N x i32> %3, %2
49829   //   %5 = lshr <N x i32> %N, <i32 1 x N>
49830   //   %6 = trunc <N x i32> %5 to <N x i8>
49831   //
49832   // In AVX512, the last instruction can also be a trunc store.
49833   if (In.getOpcode() != ISD::SRL)
49834     return SDValue();
49835 
49836   // A lambda checking the given SDValue is a constant vector and each element
49837   // is in the range [Min, Max].
49838   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
49839     return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
49840       return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
49841     });
49842   };
49843 
49844   auto IsZExtLike = [DAG = &DAG, ScalarVT](SDValue V) {
49845     unsigned MaxActiveBits = DAG->computeKnownBits(V).countMaxActiveBits();
49846     return MaxActiveBits <= ScalarVT.getSizeInBits();
49847   };
49848 
49849   // Check if each element of the vector is right-shifted by one.
49850   SDValue LHS = In.getOperand(0);
49851   SDValue RHS = In.getOperand(1);
49852   if (!IsConstVectorInRange(RHS, 1, 1))
49853     return SDValue();
49854   if (LHS.getOpcode() != ISD::ADD)
49855     return SDValue();
49856 
49857   // Detect a pattern of a + b + 1 where the order doesn't matter.
49858   SDValue Operands[3];
49859   Operands[0] = LHS.getOperand(0);
49860   Operands[1] = LHS.getOperand(1);
49861 
49862   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
49863                        ArrayRef<SDValue> Ops) {
49864     return DAG.getNode(ISD::AVGCEILU, DL, Ops[0].getValueType(), Ops);
49865   };
49866 
49867   auto AVGSplitter = [&](std::array<SDValue, 2> Ops) {
49868     for (SDValue &Op : Ops)
49869       if (Op.getValueType() != VT)
49870         Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
49871     // Pad to a power-of-2 vector, split+apply and extract the original vector.
49872     unsigned NumElemsPow2 = PowerOf2Ceil(NumElems);
49873     EVT Pow2VT = EVT::getVectorVT(*DAG.getContext(), ScalarVT, NumElemsPow2);
49874     if (NumElemsPow2 != NumElems) {
49875       for (SDValue &Op : Ops) {
49876         SmallVector<SDValue, 32> EltsOfOp(NumElemsPow2, DAG.getUNDEF(ScalarVT));
49877         for (unsigned i = 0; i != NumElems; ++i) {
49878           SDValue Idx = DAG.getIntPtrConstant(i, DL);
49879           EltsOfOp[i] =
49880               DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op, Idx);
49881         }
49882         Op = DAG.getBuildVector(Pow2VT, DL, EltsOfOp);
49883       }
49884     }
49885     SDValue Res = SplitOpsAndApply(DAG, Subtarget, DL, Pow2VT, Ops, AVGBuilder);
49886     if (NumElemsPow2 == NumElems)
49887       return Res;
49888     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
49889                        DAG.getIntPtrConstant(0, DL));
49890   };
49891 
49892   // Take care of the case when one of the operands is a constant vector whose
49893   // element is in the range [1, 256].
49894   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
49895       IsZExtLike(Operands[0])) {
49896     // The pattern is detected. Subtract one from the constant vector, then
49897     // demote it and emit X86ISD::AVG instruction.
49898     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
49899     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
49900     return AVGSplitter({Operands[0], Operands[1]});
49901   }
49902 
49903   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
49904   // Match the or case only if its 'add-like' - can be replaced by an add.
49905   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
49906     if (ISD::ADD == V.getOpcode()) {
49907       Op0 = V.getOperand(0);
49908       Op1 = V.getOperand(1);
49909       return true;
49910     }
49911     if (ISD::ZERO_EXTEND != V.getOpcode())
49912       return false;
49913     V = V.getOperand(0);
49914     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
49915         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
49916       return false;
49917     Op0 = V.getOperand(0);
49918     Op1 = V.getOperand(1);
49919     return true;
49920   };
49921 
49922   SDValue Op0, Op1;
49923   if (FindAddLike(Operands[0], Op0, Op1))
49924     std::swap(Operands[0], Operands[1]);
49925   else if (!FindAddLike(Operands[1], Op0, Op1))
49926     return SDValue();
49927   Operands[2] = Op0;
49928   Operands[1] = Op1;
49929 
49930   // Now we have three operands of two additions. Check that one of them is a
49931   // constant vector with ones, and the other two can be promoted from i8/i16.
49932   for (SDValue &Op : Operands) {
49933     if (!IsConstVectorInRange(Op, 1, 1))
49934       continue;
49935     std::swap(Op, Operands[2]);
49936 
49937     // Check if Operands[0] and Operands[1] are results of type promotion.
49938     for (int j = 0; j < 2; ++j)
49939       if (Operands[j].getValueType() != VT)
49940         if (!IsZExtLike(Operands[j]))
49941           return SDValue();
49942 
49943     // The pattern is detected, emit X86ISD::AVG instruction(s).
49944     return AVGSplitter({Operands[0], Operands[1]});
49945   }
49946 
49947   return SDValue();
49948 }
49949 
combineLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)49950 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
49951                            TargetLowering::DAGCombinerInfo &DCI,
49952                            const X86Subtarget &Subtarget) {
49953   LoadSDNode *Ld = cast<LoadSDNode>(N);
49954   EVT RegVT = Ld->getValueType(0);
49955   EVT MemVT = Ld->getMemoryVT();
49956   SDLoc dl(Ld);
49957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49958 
49959   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
49960   // into two 16-byte operations. Also split non-temporal aligned loads on
49961   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
49962   ISD::LoadExtType Ext = Ld->getExtensionType();
49963   unsigned Fast;
49964   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
49965       Ext == ISD::NON_EXTLOAD &&
49966       ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
49967         Ld->getAlign() >= Align(16)) ||
49968        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
49969                                *Ld->getMemOperand(), &Fast) &&
49970         !Fast))) {
49971     unsigned NumElems = RegVT.getVectorNumElements();
49972     if (NumElems < 2)
49973       return SDValue();
49974 
49975     unsigned HalfOffset = 16;
49976     SDValue Ptr1 = Ld->getBasePtr();
49977     SDValue Ptr2 =
49978         DAG.getMemBasePlusOffset(Ptr1, TypeSize::getFixed(HalfOffset), dl);
49979     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
49980                                   NumElems / 2);
49981     SDValue Load1 =
49982         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
49983                     Ld->getOriginalAlign(),
49984                     Ld->getMemOperand()->getFlags());
49985     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
49986                                 Ld->getPointerInfo().getWithOffset(HalfOffset),
49987                                 Ld->getOriginalAlign(),
49988                                 Ld->getMemOperand()->getFlags());
49989     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
49990                              Load1.getValue(1), Load2.getValue(1));
49991 
49992     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
49993     return DCI.CombineTo(N, NewVec, TF, true);
49994   }
49995 
49996   // Bool vector load - attempt to cast to an integer, as we have good
49997   // (vXiY *ext(vXi1 bitcast(iX))) handling.
49998   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
49999       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
50000     unsigned NumElts = RegVT.getVectorNumElements();
50001     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
50002     if (TLI.isTypeLegal(IntVT)) {
50003       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
50004                                     Ld->getPointerInfo(),
50005                                     Ld->getOriginalAlign(),
50006                                     Ld->getMemOperand()->getFlags());
50007       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
50008       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
50009     }
50010   }
50011 
50012   // If we also load/broadcast this to a wider type, then just extract the
50013   // lowest subvector.
50014   if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
50015       (RegVT.is128BitVector() || RegVT.is256BitVector())) {
50016     SDValue Ptr = Ld->getBasePtr();
50017     SDValue Chain = Ld->getChain();
50018     for (SDNode *User : Chain->uses()) {
50019       auto *UserLd = dyn_cast<MemSDNode>(User);
50020       if (User != N && UserLd &&
50021           (User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD ||
50022            User->getOpcode() == X86ISD::VBROADCAST_LOAD ||
50023            ISD::isNormalLoad(User)) &&
50024           UserLd->getChain() == Chain && !User->hasAnyUseOfValue(1) &&
50025           User->getValueSizeInBits(0).getFixedValue() >
50026               RegVT.getFixedSizeInBits()) {
50027         if (User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
50028             UserLd->getBasePtr() == Ptr &&
50029             UserLd->getMemoryVT().getSizeInBits() == MemVT.getSizeInBits()) {
50030           SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
50031                                              RegVT.getSizeInBits());
50032           Extract = DAG.getBitcast(RegVT, Extract);
50033           return DCI.CombineTo(N, Extract, SDValue(User, 1));
50034         }
50035         auto MatchingBits = [](const APInt &Undefs, const APInt &UserUndefs,
50036                                ArrayRef<APInt> Bits, ArrayRef<APInt> UserBits) {
50037           for (unsigned I = 0, E = Undefs.getBitWidth(); I != E; ++I) {
50038             if (Undefs[I])
50039               continue;
50040             if (UserUndefs[I] || Bits[I] != UserBits[I])
50041               return false;
50042           }
50043           return true;
50044         };
50045         // See if we are loading a constant that matches in the lower
50046         // bits of a longer constant (but from a different constant pool ptr).
50047         EVT UserVT = User->getValueType(0);
50048         SDValue UserPtr = UserLd->getBasePtr();
50049         const Constant *LdC = getTargetConstantFromBasePtr(Ptr);
50050         const Constant *UserC = getTargetConstantFromBasePtr(UserPtr);
50051         if (LdC && UserC && UserPtr != Ptr) {
50052           unsigned LdSize = LdC->getType()->getPrimitiveSizeInBits();
50053           unsigned UserSize = UserC->getType()->getPrimitiveSizeInBits();
50054           if (LdSize < UserSize || !ISD::isNormalLoad(User)) {
50055             APInt Undefs, UserUndefs;
50056             SmallVector<APInt> Bits, UserBits;
50057             unsigned NumBits = std::min(RegVT.getScalarSizeInBits(),
50058                                         UserVT.getScalarSizeInBits());
50059             if (getTargetConstantBitsFromNode(SDValue(N, 0), NumBits, Undefs,
50060                                               Bits) &&
50061                 getTargetConstantBitsFromNode(SDValue(User, 0), NumBits,
50062                                               UserUndefs, UserBits)) {
50063               if (MatchingBits(Undefs, UserUndefs, Bits, UserBits)) {
50064                 SDValue Extract = extractSubVector(
50065                     SDValue(User, 0), 0, DAG, SDLoc(N), RegVT.getSizeInBits());
50066                 Extract = DAG.getBitcast(RegVT, Extract);
50067                 return DCI.CombineTo(N, Extract, SDValue(User, 1));
50068               }
50069             }
50070           }
50071         }
50072       }
50073     }
50074   }
50075 
50076   // Cast ptr32 and ptr64 pointers to the default address space before a load.
50077   unsigned AddrSpace = Ld->getAddressSpace();
50078   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
50079       AddrSpace == X86AS::PTR32_UPTR) {
50080     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
50081     if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
50082       SDValue Cast =
50083           DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
50084       return DAG.getExtLoad(Ext, dl, RegVT, Ld->getChain(), Cast,
50085                             Ld->getPointerInfo(), MemVT, Ld->getOriginalAlign(),
50086                             Ld->getMemOperand()->getFlags());
50087     }
50088   }
50089 
50090   return SDValue();
50091 }
50092 
50093 /// If V is a build vector of boolean constants and exactly one of those
50094 /// constants is true, return the operand index of that true element.
50095 /// Otherwise, return -1.
getOneTrueElt(SDValue V)50096 static int getOneTrueElt(SDValue V) {
50097   // This needs to be a build vector of booleans.
50098   // TODO: Checking for the i1 type matches the IR definition for the mask,
50099   // but the mask check could be loosened to i8 or other types. That might
50100   // also require checking more than 'allOnesValue'; eg, the x86 HW
50101   // instructions only require that the MSB is set for each mask element.
50102   // The ISD::MSTORE comments/definition do not specify how the mask operand
50103   // is formatted.
50104   auto *BV = dyn_cast<BuildVectorSDNode>(V);
50105   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
50106     return -1;
50107 
50108   int TrueIndex = -1;
50109   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
50110   for (unsigned i = 0; i < NumElts; ++i) {
50111     const SDValue &Op = BV->getOperand(i);
50112     if (Op.isUndef())
50113       continue;
50114     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
50115     if (!ConstNode)
50116       return -1;
50117     if (ConstNode->getAPIntValue().countr_one() >= 1) {
50118       // If we already found a one, this is too many.
50119       if (TrueIndex >= 0)
50120         return -1;
50121       TrueIndex = i;
50122     }
50123   }
50124   return TrueIndex;
50125 }
50126 
50127 /// Given a masked memory load/store operation, return true if it has one mask
50128 /// bit set. If it has one mask bit set, then also return the memory address of
50129 /// the scalar element to load/store, the vector index to insert/extract that
50130 /// scalar element, and the alignment for the scalar memory access.
getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode * MaskedOp,SelectionDAG & DAG,SDValue & Addr,SDValue & Index,Align & Alignment,unsigned & Offset)50131 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
50132                                          SelectionDAG &DAG, SDValue &Addr,
50133                                          SDValue &Index, Align &Alignment,
50134                                          unsigned &Offset) {
50135   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
50136   if (TrueMaskElt < 0)
50137     return false;
50138 
50139   // Get the address of the one scalar element that is specified by the mask
50140   // using the appropriate offset from the base pointer.
50141   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
50142   Offset = 0;
50143   Addr = MaskedOp->getBasePtr();
50144   if (TrueMaskElt != 0) {
50145     Offset = TrueMaskElt * EltVT.getStoreSize();
50146     Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::getFixed(Offset),
50147                                     SDLoc(MaskedOp));
50148   }
50149 
50150   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
50151   Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
50152                               EltVT.getStoreSize());
50153   return true;
50154 }
50155 
50156 /// If exactly one element of the mask is set for a non-extending masked load,
50157 /// it is a scalar load and vector insert.
50158 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
50159 /// mask have already been optimized in IR, so we don't bother with those here.
50160 static SDValue
reduceMaskedLoadToScalarLoad(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)50161 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
50162                              TargetLowering::DAGCombinerInfo &DCI,
50163                              const X86Subtarget &Subtarget) {
50164   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
50165   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
50166   // However, some target hooks may need to be added to know when the transform
50167   // is profitable. Endianness would also have to be considered.
50168 
50169   SDValue Addr, VecIndex;
50170   Align Alignment;
50171   unsigned Offset;
50172   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
50173     return SDValue();
50174 
50175   // Load the one scalar element that is specified by the mask using the
50176   // appropriate offset from the base pointer.
50177   SDLoc DL(ML);
50178   EVT VT = ML->getValueType(0);
50179   EVT EltVT = VT.getVectorElementType();
50180 
50181   EVT CastVT = VT;
50182   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
50183     EltVT = MVT::f64;
50184     CastVT = VT.changeVectorElementType(EltVT);
50185   }
50186 
50187   SDValue Load =
50188       DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
50189                   ML->getPointerInfo().getWithOffset(Offset),
50190                   Alignment, ML->getMemOperand()->getFlags());
50191 
50192   SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
50193 
50194   // Insert the loaded element into the appropriate place in the vector.
50195   SDValue Insert =
50196       DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
50197   Insert = DAG.getBitcast(VT, Insert);
50198   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
50199 }
50200 
50201 static SDValue
combineMaskedLoadConstantMask(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)50202 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
50203                               TargetLowering::DAGCombinerInfo &DCI) {
50204   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
50205   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
50206     return SDValue();
50207 
50208   SDLoc DL(ML);
50209   EVT VT = ML->getValueType(0);
50210 
50211   // If we are loading the first and last elements of a vector, it is safe and
50212   // always faster to load the whole vector. Replace the masked load with a
50213   // vector load and select.
50214   unsigned NumElts = VT.getVectorNumElements();
50215   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
50216   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
50217   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
50218   if (LoadFirstElt && LoadLastElt) {
50219     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
50220                                 ML->getMemOperand());
50221     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
50222                                   ML->getPassThru());
50223     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
50224   }
50225 
50226   // Convert a masked load with a constant mask into a masked load and a select.
50227   // This allows the select operation to use a faster kind of select instruction
50228   // (for example, vblendvps -> vblendps).
50229 
50230   // Don't try this if the pass-through operand is already undefined. That would
50231   // cause an infinite loop because that's what we're about to create.
50232   if (ML->getPassThru().isUndef())
50233     return SDValue();
50234 
50235   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
50236     return SDValue();
50237 
50238   // The new masked load has an undef pass-through operand. The select uses the
50239   // original pass-through operand.
50240   SDValue NewML = DAG.getMaskedLoad(
50241       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
50242       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
50243       ML->getAddressingMode(), ML->getExtensionType());
50244   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
50245                                 ML->getPassThru());
50246 
50247   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
50248 }
50249 
combineMaskedLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)50250 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
50251                                  TargetLowering::DAGCombinerInfo &DCI,
50252                                  const X86Subtarget &Subtarget) {
50253   auto *Mld = cast<MaskedLoadSDNode>(N);
50254 
50255   // TODO: Expanding load with constant mask may be optimized as well.
50256   if (Mld->isExpandingLoad())
50257     return SDValue();
50258 
50259   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
50260     if (SDValue ScalarLoad =
50261             reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
50262       return ScalarLoad;
50263 
50264     // TODO: Do some AVX512 subsets benefit from this transform?
50265     if (!Subtarget.hasAVX512())
50266       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
50267         return Blend;
50268   }
50269 
50270   // If the mask value has been legalized to a non-boolean vector, try to
50271   // simplify ops leading up to it. We only demand the MSB of each lane.
50272   SDValue Mask = Mld->getMask();
50273   if (Mask.getScalarValueSizeInBits() != 1) {
50274     EVT VT = Mld->getValueType(0);
50275     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50276     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
50277     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
50278       if (N->getOpcode() != ISD::DELETED_NODE)
50279         DCI.AddToWorklist(N);
50280       return SDValue(N, 0);
50281     }
50282     if (SDValue NewMask =
50283             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
50284       return DAG.getMaskedLoad(
50285           VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
50286           NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
50287           Mld->getAddressingMode(), Mld->getExtensionType());
50288   }
50289 
50290   return SDValue();
50291 }
50292 
50293 /// If exactly one element of the mask is set for a non-truncating masked store,
50294 /// it is a vector extract and scalar store.
50295 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
50296 /// mask have already been optimized in IR, so we don't bother with those here.
reduceMaskedStoreToScalarStore(MaskedStoreSDNode * MS,SelectionDAG & DAG,const X86Subtarget & Subtarget)50297 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
50298                                               SelectionDAG &DAG,
50299                                               const X86Subtarget &Subtarget) {
50300   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
50301   // However, some target hooks may need to be added to know when the transform
50302   // is profitable. Endianness would also have to be considered.
50303 
50304   SDValue Addr, VecIndex;
50305   Align Alignment;
50306   unsigned Offset;
50307   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
50308     return SDValue();
50309 
50310   // Extract the one scalar element that is actually being stored.
50311   SDLoc DL(MS);
50312   SDValue Value = MS->getValue();
50313   EVT VT = Value.getValueType();
50314   EVT EltVT = VT.getVectorElementType();
50315   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
50316     EltVT = MVT::f64;
50317     EVT CastVT = VT.changeVectorElementType(EltVT);
50318     Value = DAG.getBitcast(CastVT, Value);
50319   }
50320   SDValue Extract =
50321       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
50322 
50323   // Store that element at the appropriate offset from the base pointer.
50324   return DAG.getStore(MS->getChain(), DL, Extract, Addr,
50325                       MS->getPointerInfo().getWithOffset(Offset),
50326                       Alignment, MS->getMemOperand()->getFlags());
50327 }
50328 
combineMaskedStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)50329 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
50330                                   TargetLowering::DAGCombinerInfo &DCI,
50331                                   const X86Subtarget &Subtarget) {
50332   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
50333   if (Mst->isCompressingStore())
50334     return SDValue();
50335 
50336   EVT VT = Mst->getValue().getValueType();
50337   SDLoc dl(Mst);
50338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50339 
50340   if (Mst->isTruncatingStore())
50341     return SDValue();
50342 
50343   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
50344     return ScalarStore;
50345 
50346   // If the mask value has been legalized to a non-boolean vector, try to
50347   // simplify ops leading up to it. We only demand the MSB of each lane.
50348   SDValue Mask = Mst->getMask();
50349   if (Mask.getScalarValueSizeInBits() != 1) {
50350     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
50351     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
50352       if (N->getOpcode() != ISD::DELETED_NODE)
50353         DCI.AddToWorklist(N);
50354       return SDValue(N, 0);
50355     }
50356     if (SDValue NewMask =
50357             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
50358       return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
50359                                 Mst->getBasePtr(), Mst->getOffset(), NewMask,
50360                                 Mst->getMemoryVT(), Mst->getMemOperand(),
50361                                 Mst->getAddressingMode());
50362   }
50363 
50364   SDValue Value = Mst->getValue();
50365   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
50366       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
50367                             Mst->getMemoryVT())) {
50368     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
50369                               Mst->getBasePtr(), Mst->getOffset(), Mask,
50370                               Mst->getMemoryVT(), Mst->getMemOperand(),
50371                               Mst->getAddressingMode(), true);
50372   }
50373 
50374   return SDValue();
50375 }
50376 
combineStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)50377 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
50378                             TargetLowering::DAGCombinerInfo &DCI,
50379                             const X86Subtarget &Subtarget) {
50380   StoreSDNode *St = cast<StoreSDNode>(N);
50381   EVT StVT = St->getMemoryVT();
50382   SDLoc dl(St);
50383   SDValue StoredVal = St->getValue();
50384   EVT VT = StoredVal.getValueType();
50385   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50386 
50387   // Convert a store of vXi1 into a store of iX and a bitcast.
50388   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
50389       VT.getVectorElementType() == MVT::i1) {
50390 
50391     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
50392     StoredVal = DAG.getBitcast(NewVT, StoredVal);
50393 
50394     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
50395                         St->getPointerInfo(), St->getOriginalAlign(),
50396                         St->getMemOperand()->getFlags());
50397   }
50398 
50399   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
50400   // This will avoid a copy to k-register.
50401   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
50402       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
50403       StoredVal.getOperand(0).getValueType() == MVT::i8) {
50404     SDValue Val = StoredVal.getOperand(0);
50405     // We must store zeros to the unused bits.
50406     Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
50407     return DAG.getStore(St->getChain(), dl, Val,
50408                         St->getBasePtr(), St->getPointerInfo(),
50409                         St->getOriginalAlign(),
50410                         St->getMemOperand()->getFlags());
50411   }
50412 
50413   // Widen v2i1/v4i1 stores to v8i1.
50414   if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
50415       Subtarget.hasAVX512()) {
50416     unsigned NumConcats = 8 / VT.getVectorNumElements();
50417     // We must store zeros to the unused bits.
50418     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
50419     Ops[0] = StoredVal;
50420     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
50421     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
50422                         St->getPointerInfo(), St->getOriginalAlign(),
50423                         St->getMemOperand()->getFlags());
50424   }
50425 
50426   // Turn vXi1 stores of constants into a scalar store.
50427   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
50428        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
50429       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
50430     // If its a v64i1 store without 64-bit support, we need two stores.
50431     if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
50432       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
50433                                       StoredVal->ops().slice(0, 32));
50434       Lo = combinevXi1ConstantToInteger(Lo, DAG);
50435       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
50436                                       StoredVal->ops().slice(32, 32));
50437       Hi = combinevXi1ConstantToInteger(Hi, DAG);
50438 
50439       SDValue Ptr0 = St->getBasePtr();
50440       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::getFixed(4), dl);
50441 
50442       SDValue Ch0 =
50443           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
50444                        St->getOriginalAlign(),
50445                        St->getMemOperand()->getFlags());
50446       SDValue Ch1 =
50447           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
50448                        St->getPointerInfo().getWithOffset(4),
50449                        St->getOriginalAlign(),
50450                        St->getMemOperand()->getFlags());
50451       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
50452     }
50453 
50454     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
50455     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
50456                         St->getPointerInfo(), St->getOriginalAlign(),
50457                         St->getMemOperand()->getFlags());
50458   }
50459 
50460   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
50461   // Sandy Bridge, perform two 16-byte stores.
50462   unsigned Fast;
50463   if (VT.is256BitVector() && StVT == VT &&
50464       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
50465                              *St->getMemOperand(), &Fast) &&
50466       !Fast) {
50467     unsigned NumElems = VT.getVectorNumElements();
50468     if (NumElems < 2)
50469       return SDValue();
50470 
50471     return splitVectorStore(St, DAG);
50472   }
50473 
50474   // Split under-aligned vector non-temporal stores.
50475   if (St->isNonTemporal() && StVT == VT &&
50476       St->getAlign().value() < VT.getStoreSize()) {
50477     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
50478     // vectors or the legalizer can scalarize it to use MOVNTI.
50479     if (VT.is256BitVector() || VT.is512BitVector()) {
50480       unsigned NumElems = VT.getVectorNumElements();
50481       if (NumElems < 2)
50482         return SDValue();
50483       return splitVectorStore(St, DAG);
50484     }
50485 
50486     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
50487     // to use MOVNTI.
50488     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
50489       MVT NTVT = Subtarget.hasSSE4A()
50490                      ? MVT::v2f64
50491                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
50492       return scalarizeVectorStore(St, NTVT, DAG);
50493     }
50494   }
50495 
50496   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
50497   // supported, but avx512f is by extending to v16i32 and truncating.
50498   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
50499       St->getValue().getOpcode() == ISD::TRUNCATE &&
50500       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
50501       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
50502       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
50503     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32,
50504                               St->getValue().getOperand(0));
50505     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
50506                              MVT::v16i8, St->getMemOperand());
50507   }
50508 
50509   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
50510   if (!St->isTruncatingStore() &&
50511       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
50512        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
50513       StoredVal.hasOneUse() &&
50514       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
50515     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
50516     return EmitTruncSStore(IsSigned, St->getChain(),
50517                            dl, StoredVal.getOperand(0), St->getBasePtr(),
50518                            VT, St->getMemOperand(), DAG);
50519   }
50520 
50521   // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
50522   if (!St->isTruncatingStore()) {
50523     auto IsExtractedElement = [](SDValue V) {
50524       if (V.getOpcode() == ISD::TRUNCATE && V.hasOneUse())
50525         V = V.getOperand(0);
50526       unsigned Opc = V.getOpcode();
50527       if ((Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) &&
50528           isNullConstant(V.getOperand(1)) && V.hasOneUse() &&
50529           V.getOperand(0).hasOneUse())
50530         return V.getOperand(0);
50531       return SDValue();
50532     };
50533     if (SDValue Extract = IsExtractedElement(StoredVal)) {
50534       SDValue Trunc = peekThroughOneUseBitcasts(Extract);
50535       if (Trunc.getOpcode() == X86ISD::VTRUNC) {
50536         SDValue Src = Trunc.getOperand(0);
50537         MVT DstVT = Trunc.getSimpleValueType();
50538         MVT SrcVT = Src.getSimpleValueType();
50539         unsigned NumSrcElts = SrcVT.getVectorNumElements();
50540         unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
50541         MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
50542         if (NumTruncBits == VT.getSizeInBits() &&
50543             TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
50544           return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
50545                                    TruncVT, St->getMemOperand());
50546         }
50547       }
50548     }
50549   }
50550 
50551   // Optimize trunc store (of multiple scalars) to shuffle and store.
50552   // First, pack all of the elements in one place. Next, store to memory
50553   // in fewer chunks.
50554   if (St->isTruncatingStore() && VT.isVector()) {
50555     // Check if we can detect an AVG pattern from the truncation. If yes,
50556     // replace the trunc store by a normal store with the result of X86ISD::AVG
50557     // instruction.
50558     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
50559       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
50560                                          Subtarget, dl))
50561         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
50562                             St->getPointerInfo(), St->getOriginalAlign(),
50563                             St->getMemOperand()->getFlags());
50564 
50565     if (TLI.isTruncStoreLegal(VT, StVT)) {
50566       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
50567         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
50568                                dl, Val, St->getBasePtr(),
50569                                St->getMemoryVT(), St->getMemOperand(), DAG);
50570       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
50571                                           DAG, dl))
50572         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
50573                                dl, Val, St->getBasePtr(),
50574                                St->getMemoryVT(), St->getMemOperand(), DAG);
50575     }
50576 
50577     return SDValue();
50578   }
50579 
50580   // Cast ptr32 and ptr64 pointers to the default address space before a store.
50581   unsigned AddrSpace = St->getAddressSpace();
50582   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
50583       AddrSpace == X86AS::PTR32_UPTR) {
50584     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
50585     if (PtrVT != St->getBasePtr().getSimpleValueType()) {
50586       SDValue Cast =
50587           DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
50588       return DAG.getTruncStore(
50589           St->getChain(), dl, StoredVal, Cast, St->getPointerInfo(), StVT,
50590           St->getOriginalAlign(), St->getMemOperand()->getFlags(),
50591           St->getAAInfo());
50592     }
50593   }
50594 
50595   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
50596   // the FP state in cases where an emms may be missing.
50597   // A preferable solution to the general problem is to figure out the right
50598   // places to insert EMMS.  This qualifies as a quick hack.
50599 
50600   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
50601   if (VT.getSizeInBits() != 64)
50602     return SDValue();
50603 
50604   const Function &F = DAG.getMachineFunction().getFunction();
50605   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
50606   bool F64IsLegal =
50607       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
50608 
50609   if (!F64IsLegal || Subtarget.is64Bit())
50610     return SDValue();
50611 
50612   if (VT == MVT::i64 && isa<LoadSDNode>(St->getValue()) &&
50613       cast<LoadSDNode>(St->getValue())->isSimple() &&
50614       St->getChain().hasOneUse() && St->isSimple()) {
50615     auto *Ld = cast<LoadSDNode>(St->getValue());
50616 
50617     if (!ISD::isNormalLoad(Ld))
50618       return SDValue();
50619 
50620     // Avoid the transformation if there are multiple uses of the loaded value.
50621     if (!Ld->hasNUsesOfValue(1, 0))
50622       return SDValue();
50623 
50624     SDLoc LdDL(Ld);
50625     SDLoc StDL(N);
50626     // Lower to a single movq load/store pair.
50627     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
50628                                 Ld->getBasePtr(), Ld->getMemOperand());
50629 
50630     // Make sure new load is placed in same chain order.
50631     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
50632     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
50633                         St->getMemOperand());
50634   }
50635 
50636   // This is similar to the above case, but here we handle a scalar 64-bit
50637   // integer store that is extracted from a vector on a 32-bit target.
50638   // If we have SSE2, then we can treat it like a floating-point double
50639   // to get past legalization. The execution dependencies fixup pass will
50640   // choose the optimal machine instruction for the store if this really is
50641   // an integer or v2f32 rather than an f64.
50642   if (VT == MVT::i64 &&
50643       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
50644     SDValue OldExtract = St->getOperand(1);
50645     SDValue ExtOp0 = OldExtract.getOperand(0);
50646     unsigned VecSize = ExtOp0.getValueSizeInBits();
50647     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
50648     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
50649     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
50650                                      BitCast, OldExtract.getOperand(1));
50651     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
50652                         St->getPointerInfo(), St->getOriginalAlign(),
50653                         St->getMemOperand()->getFlags());
50654   }
50655 
50656   return SDValue();
50657 }
50658 
combineVEXTRACT_STORE(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)50659 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
50660                                      TargetLowering::DAGCombinerInfo &DCI,
50661                                      const X86Subtarget &Subtarget) {
50662   auto *St = cast<MemIntrinsicSDNode>(N);
50663 
50664   SDValue StoredVal = N->getOperand(1);
50665   MVT VT = StoredVal.getSimpleValueType();
50666   EVT MemVT = St->getMemoryVT();
50667 
50668   // Figure out which elements we demand.
50669   unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
50670   APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
50671 
50672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50673   if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, DCI)) {
50674     if (N->getOpcode() != ISD::DELETED_NODE)
50675       DCI.AddToWorklist(N);
50676     return SDValue(N, 0);
50677   }
50678 
50679   return SDValue();
50680 }
50681 
50682 /// Return 'true' if this vector operation is "horizontal"
50683 /// and return the operands for the horizontal operation in LHS and RHS.  A
50684 /// horizontal operation performs the binary operation on successive elements
50685 /// of its first operand, then on successive elements of its second operand,
50686 /// returning the resulting values in a vector.  For example, if
50687 ///   A = < float a0, float a1, float a2, float a3 >
50688 /// and
50689 ///   B = < float b0, float b1, float b2, float b3 >
50690 /// then the result of doing a horizontal operation on A and B is
50691 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
50692 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
50693 /// A horizontal-op B, for some already available A and B, and if so then LHS is
50694 /// set to A, RHS to B, and the routine returns 'true'.
isHorizontalBinOp(unsigned HOpcode,SDValue & LHS,SDValue & RHS,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool IsCommutative,SmallVectorImpl<int> & PostShuffleMask)50695 static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
50696                               SelectionDAG &DAG, const X86Subtarget &Subtarget,
50697                               bool IsCommutative,
50698                               SmallVectorImpl<int> &PostShuffleMask) {
50699   // If either operand is undef, bail out. The binop should be simplified.
50700   if (LHS.isUndef() || RHS.isUndef())
50701     return false;
50702 
50703   // Look for the following pattern:
50704   //   A = < float a0, float a1, float a2, float a3 >
50705   //   B = < float b0, float b1, float b2, float b3 >
50706   // and
50707   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
50708   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
50709   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
50710   // which is A horizontal-op B.
50711 
50712   MVT VT = LHS.getSimpleValueType();
50713   assert((VT.is128BitVector() || VT.is256BitVector()) &&
50714          "Unsupported vector type for horizontal add/sub");
50715   unsigned NumElts = VT.getVectorNumElements();
50716 
50717   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
50718                         SmallVectorImpl<int> &ShuffleMask) {
50719     bool UseSubVector = false;
50720     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
50721         Op.getOperand(0).getValueType().is256BitVector() &&
50722         llvm::isNullConstant(Op.getOperand(1))) {
50723       Op = Op.getOperand(0);
50724       UseSubVector = true;
50725     }
50726     SmallVector<SDValue, 2> SrcOps;
50727     SmallVector<int, 16> SrcMask, ScaledMask;
50728     SDValue BC = peekThroughBitcasts(Op);
50729     if (getTargetShuffleInputs(BC, SrcOps, SrcMask, DAG) &&
50730         !isAnyZero(SrcMask) && all_of(SrcOps, [BC](SDValue Op) {
50731           return Op.getValueSizeInBits() == BC.getValueSizeInBits();
50732         })) {
50733       resolveTargetShuffleInputsAndMask(SrcOps, SrcMask);
50734       if (!UseSubVector && SrcOps.size() <= 2 &&
50735           scaleShuffleElements(SrcMask, NumElts, ScaledMask)) {
50736         N0 = !SrcOps.empty() ? SrcOps[0] : SDValue();
50737         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
50738         ShuffleMask.assign(ScaledMask.begin(), ScaledMask.end());
50739       }
50740       if (UseSubVector && SrcOps.size() == 1 &&
50741           scaleShuffleElements(SrcMask, 2 * NumElts, ScaledMask)) {
50742         std::tie(N0, N1) = DAG.SplitVector(SrcOps[0], SDLoc(Op));
50743         ArrayRef<int> Mask = ArrayRef<int>(ScaledMask).slice(0, NumElts);
50744         ShuffleMask.assign(Mask.begin(), Mask.end());
50745       }
50746     }
50747   };
50748 
50749   // View LHS in the form
50750   //   LHS = VECTOR_SHUFFLE A, B, LMask
50751   // If LHS is not a shuffle, then pretend it is the identity shuffle:
50752   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
50753   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
50754   SDValue A, B;
50755   SmallVector<int, 16> LMask;
50756   GetShuffle(LHS, A, B, LMask);
50757 
50758   // Likewise, view RHS in the form
50759   //   RHS = VECTOR_SHUFFLE C, D, RMask
50760   SDValue C, D;
50761   SmallVector<int, 16> RMask;
50762   GetShuffle(RHS, C, D, RMask);
50763 
50764   // At least one of the operands should be a vector shuffle.
50765   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
50766   if (NumShuffles == 0)
50767     return false;
50768 
50769   if (LMask.empty()) {
50770     A = LHS;
50771     for (unsigned i = 0; i != NumElts; ++i)
50772       LMask.push_back(i);
50773   }
50774 
50775   if (RMask.empty()) {
50776     C = RHS;
50777     for (unsigned i = 0; i != NumElts; ++i)
50778       RMask.push_back(i);
50779   }
50780 
50781   // If we have an unary mask, ensure the other op is set to null.
50782   if (isUndefOrInRange(LMask, 0, NumElts))
50783     B = SDValue();
50784   else if (isUndefOrInRange(LMask, NumElts, NumElts * 2))
50785     A = SDValue();
50786 
50787   if (isUndefOrInRange(RMask, 0, NumElts))
50788     D = SDValue();
50789   else if (isUndefOrInRange(RMask, NumElts, NumElts * 2))
50790     C = SDValue();
50791 
50792   // If A and B occur in reverse order in RHS, then canonicalize by commuting
50793   // RHS operands and shuffle mask.
50794   if (A != C) {
50795     std::swap(C, D);
50796     ShuffleVectorSDNode::commuteMask(RMask);
50797   }
50798   // Check that the shuffles are both shuffling the same vectors.
50799   if (!(A == C && B == D))
50800     return false;
50801 
50802   PostShuffleMask.clear();
50803   PostShuffleMask.append(NumElts, SM_SentinelUndef);
50804 
50805   // LHS and RHS are now:
50806   //   LHS = shuffle A, B, LMask
50807   //   RHS = shuffle A, B, RMask
50808   // Check that the masks correspond to performing a horizontal operation.
50809   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
50810   // so we just repeat the inner loop if this is a 256-bit op.
50811   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
50812   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
50813   unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
50814   assert((NumEltsPer128BitChunk % 2 == 0) &&
50815          "Vector type should have an even number of elements in each lane");
50816   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
50817     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
50818       // Ignore undefined components.
50819       int LIdx = LMask[i + j], RIdx = RMask[i + j];
50820       if (LIdx < 0 || RIdx < 0 ||
50821           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
50822           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
50823         continue;
50824 
50825       // Check that successive odd/even elements are being operated on. If not,
50826       // this is not a horizontal operation.
50827       if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
50828           !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
50829         return false;
50830 
50831       // Compute the post-shuffle mask index based on where the element
50832       // is stored in the HOP result, and where it needs to be moved to.
50833       int Base = LIdx & ~1u;
50834       int Index = ((Base % NumEltsPer128BitChunk) / 2) +
50835                   ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
50836 
50837       // The  low half of the 128-bit result must choose from A.
50838       // The high half of the 128-bit result must choose from B,
50839       // unless B is undef. In that case, we are always choosing from A.
50840       if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
50841         Index += NumEltsPer64BitChunk;
50842       PostShuffleMask[i + j] = Index;
50843     }
50844   }
50845 
50846   SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
50847   SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
50848 
50849   bool IsIdentityPostShuffle =
50850       isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
50851   if (IsIdentityPostShuffle)
50852     PostShuffleMask.clear();
50853 
50854   // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
50855   if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
50856       isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
50857     return false;
50858 
50859   // If the source nodes are already used in HorizOps then always accept this.
50860   // Shuffle folding should merge these back together.
50861   bool FoundHorizLHS = llvm::any_of(NewLHS->uses(), [&](SDNode *User) {
50862     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
50863   });
50864   bool FoundHorizRHS = llvm::any_of(NewRHS->uses(), [&](SDNode *User) {
50865     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
50866   });
50867   bool ForceHorizOp = FoundHorizLHS && FoundHorizRHS;
50868 
50869   // Assume a SingleSource HOP if we only shuffle one input and don't need to
50870   // shuffle the result.
50871   if (!ForceHorizOp &&
50872       !shouldUseHorizontalOp(NewLHS == NewRHS &&
50873                                  (NumShuffles < 2 || !IsIdentityPostShuffle),
50874                              DAG, Subtarget))
50875     return false;
50876 
50877   LHS = DAG.getBitcast(VT, NewLHS);
50878   RHS = DAG.getBitcast(VT, NewRHS);
50879   return true;
50880 }
50881 
50882 // Try to synthesize horizontal (f)hadd/hsub from (f)adds/subs of shuffles.
combineToHorizontalAddSub(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)50883 static SDValue combineToHorizontalAddSub(SDNode *N, SelectionDAG &DAG,
50884                                          const X86Subtarget &Subtarget) {
50885   EVT VT = N->getValueType(0);
50886   unsigned Opcode = N->getOpcode();
50887   bool IsAdd = (Opcode == ISD::FADD) || (Opcode == ISD::ADD);
50888   SmallVector<int, 8> PostShuffleMask;
50889 
50890   switch (Opcode) {
50891   case ISD::FADD:
50892   case ISD::FSUB:
50893     if ((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
50894         (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
50895       SDValue LHS = N->getOperand(0);
50896       SDValue RHS = N->getOperand(1);
50897       auto HorizOpcode = IsAdd ? X86ISD::FHADD : X86ISD::FHSUB;
50898       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
50899                             PostShuffleMask)) {
50900         SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
50901         if (!PostShuffleMask.empty())
50902           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
50903                                             DAG.getUNDEF(VT), PostShuffleMask);
50904         return HorizBinOp;
50905       }
50906     }
50907     break;
50908   case ISD::ADD:
50909   case ISD::SUB:
50910     if (Subtarget.hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
50911                                  VT == MVT::v16i16 || VT == MVT::v8i32)) {
50912       SDValue LHS = N->getOperand(0);
50913       SDValue RHS = N->getOperand(1);
50914       auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
50915       if (isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsAdd,
50916                             PostShuffleMask)) {
50917         auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
50918                                         ArrayRef<SDValue> Ops) {
50919           return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
50920         };
50921         SDValue HorizBinOp = SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
50922                                               {LHS, RHS}, HOpBuilder);
50923         if (!PostShuffleMask.empty())
50924           HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
50925                                             DAG.getUNDEF(VT), PostShuffleMask);
50926         return HorizBinOp;
50927       }
50928     }
50929     break;
50930   }
50931 
50932   return SDValue();
50933 }
50934 
50935 //  Try to combine the following nodes
50936 //  t29: i64 = X86ISD::Wrapper TargetConstantPool:i64
50937 //    <i32 -2147483648[float -0.000000e+00]> 0
50938 //  t27: v16i32[v16f32],ch = X86ISD::VBROADCAST_LOAD
50939 //    <(load 4 from constant-pool)> t0, t29
50940 //  [t30: v16i32 = bitcast t27]
50941 //  t6: v16i32 = xor t7, t27[t30]
50942 //  t11: v16f32 = bitcast t6
50943 //  t21: v16f32 = X86ISD::VFMULC[X86ISD::VCFMULC] t11, t8
50944 //  into X86ISD::VFCMULC[X86ISD::VFMULC] if possible:
50945 //  t22: v16f32 = bitcast t7
50946 //  t23: v16f32 = X86ISD::VFCMULC[X86ISD::VFMULC] t8, t22
50947 //  t24: v32f16 = bitcast t23
combineFMulcFCMulc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)50948 static SDValue combineFMulcFCMulc(SDNode *N, SelectionDAG &DAG,
50949                                   const X86Subtarget &Subtarget) {
50950   EVT VT = N->getValueType(0);
50951   SDValue LHS = N->getOperand(0);
50952   SDValue RHS = N->getOperand(1);
50953   int CombineOpcode =
50954       N->getOpcode() == X86ISD::VFCMULC ? X86ISD::VFMULC : X86ISD::VFCMULC;
50955   auto combineConjugation = [&](SDValue &r) {
50956     if (LHS->getOpcode() == ISD::BITCAST && RHS.hasOneUse()) {
50957       SDValue XOR = LHS.getOperand(0);
50958       if (XOR->getOpcode() == ISD::XOR && XOR.hasOneUse()) {
50959         KnownBits XORRHS = DAG.computeKnownBits(XOR.getOperand(1));
50960         if (XORRHS.isConstant()) {
50961           APInt ConjugationInt32 = APInt(32, 0x80000000, true);
50962           APInt ConjugationInt64 = APInt(64, 0x8000000080000000ULL, true);
50963           if ((XORRHS.getBitWidth() == 32 &&
50964                XORRHS.getConstant() == ConjugationInt32) ||
50965               (XORRHS.getBitWidth() == 64 &&
50966                XORRHS.getConstant() == ConjugationInt64)) {
50967             SelectionDAG::FlagInserter FlagsInserter(DAG, N);
50968             SDValue I2F = DAG.getBitcast(VT, LHS.getOperand(0).getOperand(0));
50969             SDValue FCMulC = DAG.getNode(CombineOpcode, SDLoc(N), VT, RHS, I2F);
50970             r = DAG.getBitcast(VT, FCMulC);
50971             return true;
50972           }
50973         }
50974       }
50975     }
50976     return false;
50977   };
50978   SDValue Res;
50979   if (combineConjugation(Res))
50980     return Res;
50981   std::swap(LHS, RHS);
50982   if (combineConjugation(Res))
50983     return Res;
50984   return Res;
50985 }
50986 
50987 //  Try to combine the following nodes:
50988 //  FADD(A, FMA(B, C, 0)) and FADD(A, FMUL(B, C)) to FMA(B, C, A)
combineFaddCFmul(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)50989 static SDValue combineFaddCFmul(SDNode *N, SelectionDAG &DAG,
50990                                 const X86Subtarget &Subtarget) {
50991   auto AllowContract = [&DAG](const SDNodeFlags &Flags) {
50992     return DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
50993            Flags.hasAllowContract();
50994   };
50995 
50996   auto HasNoSignedZero = [&DAG](const SDNodeFlags &Flags) {
50997     return DAG.getTarget().Options.NoSignedZerosFPMath ||
50998            Flags.hasNoSignedZeros();
50999   };
51000   auto IsVectorAllNegativeZero = [&DAG](SDValue Op) {
51001     APInt AI = APInt(32, 0x80008000, true);
51002     KnownBits Bits = DAG.computeKnownBits(Op);
51003     return Bits.getBitWidth() == 32 && Bits.isConstant() &&
51004            Bits.getConstant() == AI;
51005   };
51006 
51007   if (N->getOpcode() != ISD::FADD || !Subtarget.hasFP16() ||
51008       !AllowContract(N->getFlags()))
51009     return SDValue();
51010 
51011   EVT VT = N->getValueType(0);
51012   if (VT != MVT::v8f16 && VT != MVT::v16f16 && VT != MVT::v32f16)
51013     return SDValue();
51014 
51015   SDValue LHS = N->getOperand(0);
51016   SDValue RHS = N->getOperand(1);
51017   bool IsConj;
51018   SDValue FAddOp1, MulOp0, MulOp1;
51019   auto GetCFmulFrom = [&MulOp0, &MulOp1, &IsConj, &AllowContract,
51020                        &IsVectorAllNegativeZero,
51021                        &HasNoSignedZero](SDValue N) -> bool {
51022     if (!N.hasOneUse() || N.getOpcode() != ISD::BITCAST)
51023       return false;
51024     SDValue Op0 = N.getOperand(0);
51025     unsigned Opcode = Op0.getOpcode();
51026     if (Op0.hasOneUse() && AllowContract(Op0->getFlags())) {
51027       if ((Opcode == X86ISD::VFMULC || Opcode == X86ISD::VFCMULC)) {
51028         MulOp0 = Op0.getOperand(0);
51029         MulOp1 = Op0.getOperand(1);
51030         IsConj = Opcode == X86ISD::VFCMULC;
51031         return true;
51032       }
51033       if ((Opcode == X86ISD::VFMADDC || Opcode == X86ISD::VFCMADDC) &&
51034           ((ISD::isBuildVectorAllZeros(Op0->getOperand(2).getNode()) &&
51035             HasNoSignedZero(Op0->getFlags())) ||
51036            IsVectorAllNegativeZero(Op0->getOperand(2)))) {
51037         MulOp0 = Op0.getOperand(0);
51038         MulOp1 = Op0.getOperand(1);
51039         IsConj = Opcode == X86ISD::VFCMADDC;
51040         return true;
51041       }
51042     }
51043     return false;
51044   };
51045 
51046   if (GetCFmulFrom(LHS))
51047     FAddOp1 = RHS;
51048   else if (GetCFmulFrom(RHS))
51049     FAddOp1 = LHS;
51050   else
51051     return SDValue();
51052 
51053   MVT CVT = MVT::getVectorVT(MVT::f32, VT.getVectorNumElements() / 2);
51054   FAddOp1 = DAG.getBitcast(CVT, FAddOp1);
51055   unsigned NewOp = IsConj ? X86ISD::VFCMADDC : X86ISD::VFMADDC;
51056   // FIXME: How do we handle when fast math flags of FADD are different from
51057   // CFMUL's?
51058   SDValue CFmul =
51059       DAG.getNode(NewOp, SDLoc(N), CVT, MulOp0, MulOp1, FAddOp1, N->getFlags());
51060   return DAG.getBitcast(VT, CFmul);
51061 }
51062 
51063 /// Do target-specific dag combines on floating-point adds/subs.
combineFaddFsub(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51064 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
51065                                const X86Subtarget &Subtarget) {
51066   if (SDValue HOp = combineToHorizontalAddSub(N, DAG, Subtarget))
51067     return HOp;
51068 
51069   if (SDValue COp = combineFaddCFmul(N, DAG, Subtarget))
51070     return COp;
51071 
51072   return SDValue();
51073 }
51074 
51075 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
51076 /// the codegen.
51077 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
51078 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
51079 ///       anything that is guaranteed to be transformed by DAGCombiner.
combineTruncatedArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)51080 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
51081                                           const X86Subtarget &Subtarget,
51082                                           const SDLoc &DL) {
51083   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
51084   SDValue Src = N->getOperand(0);
51085   unsigned SrcOpcode = Src.getOpcode();
51086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51087 
51088   EVT VT = N->getValueType(0);
51089   EVT SrcVT = Src.getValueType();
51090 
51091   auto IsFreeTruncation = [VT](SDValue Op) {
51092     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
51093 
51094     // See if this has been extended from a smaller/equal size to
51095     // the truncation size, allowing a truncation to combine with the extend.
51096     unsigned Opcode = Op.getOpcode();
51097     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
51098          Opcode == ISD::ZERO_EXTEND) &&
51099         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
51100       return true;
51101 
51102     // See if this is a single use constant which can be constant folded.
51103     // NOTE: We don't peek throught bitcasts here because there is currently
51104     // no support for constant folding truncate+bitcast+vector_of_constants. So
51105     // we'll just send up with a truncate on both operands which will
51106     // get turned back into (truncate (binop)) causing an infinite loop.
51107     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
51108   };
51109 
51110   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
51111     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
51112     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
51113     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
51114   };
51115 
51116   // Don't combine if the operation has other uses.
51117   if (!Src.hasOneUse())
51118     return SDValue();
51119 
51120   // Only support vector truncation for now.
51121   // TODO: i64 scalar math would benefit as well.
51122   if (!VT.isVector())
51123     return SDValue();
51124 
51125   // In most cases its only worth pre-truncating if we're only facing the cost
51126   // of one truncation.
51127   // i.e. if one of the inputs will constant fold or the input is repeated.
51128   switch (SrcOpcode) {
51129   case ISD::MUL:
51130     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
51131     // better to truncate if we have the chance.
51132     if (SrcVT.getScalarType() == MVT::i64 &&
51133         TLI.isOperationLegal(SrcOpcode, VT) &&
51134         !TLI.isOperationLegal(SrcOpcode, SrcVT))
51135       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
51136     [[fallthrough]];
51137   case ISD::AND:
51138   case ISD::XOR:
51139   case ISD::OR:
51140   case ISD::ADD:
51141   case ISD::SUB: {
51142     SDValue Op0 = Src.getOperand(0);
51143     SDValue Op1 = Src.getOperand(1);
51144     if (TLI.isOperationLegal(SrcOpcode, VT) &&
51145         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
51146       return TruncateArithmetic(Op0, Op1);
51147     break;
51148   }
51149   }
51150 
51151   return SDValue();
51152 }
51153 
51154 // Try to form a MULHU or MULHS node by looking for
51155 // (trunc (srl (mul ext, ext), 16))
51156 // TODO: This is X86 specific because we want to be able to handle wide types
51157 // before type legalization. But we can only do it if the vector will be
51158 // legalized via widening/splitting. Type legalization can't handle promotion
51159 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
51160 // combiner.
combinePMULH(SDValue Src,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)51161 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
51162                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
51163   // First instruction should be a right shift of a multiply.
51164   if (Src.getOpcode() != ISD::SRL ||
51165       Src.getOperand(0).getOpcode() != ISD::MUL)
51166     return SDValue();
51167 
51168   if (!Subtarget.hasSSE2())
51169     return SDValue();
51170 
51171   // Only handle vXi16 types that are at least 128-bits unless they will be
51172   // widened.
51173   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
51174     return SDValue();
51175 
51176   // Input type should be at least vXi32.
51177   EVT InVT = Src.getValueType();
51178   if (InVT.getVectorElementType().getSizeInBits() < 32)
51179     return SDValue();
51180 
51181   // Need a shift by 16.
51182   APInt ShiftAmt;
51183   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
51184       ShiftAmt != 16)
51185     return SDValue();
51186 
51187   SDValue LHS = Src.getOperand(0).getOperand(0);
51188   SDValue RHS = Src.getOperand(0).getOperand(1);
51189 
51190   // Count leading sign/zero bits on both inputs - if there are enough then
51191   // truncation back to vXi16 will be cheap - either as a pack/shuffle
51192   // sequence or using AVX512 truncations. If the inputs are sext/zext then the
51193   // truncations may actually be free by peeking through to the ext source.
51194   auto IsSext = [&DAG](SDValue V) {
51195     return DAG.ComputeMaxSignificantBits(V) <= 16;
51196   };
51197   auto IsZext = [&DAG](SDValue V) {
51198     return DAG.computeKnownBits(V).countMaxActiveBits() <= 16;
51199   };
51200 
51201   bool IsSigned = IsSext(LHS) && IsSext(RHS);
51202   bool IsUnsigned = IsZext(LHS) && IsZext(RHS);
51203   if (!IsSigned && !IsUnsigned)
51204     return SDValue();
51205 
51206   // Check if both inputs are extensions, which will be removed by truncation.
51207   bool IsTruncateFree = (LHS.getOpcode() == ISD::SIGN_EXTEND ||
51208                          LHS.getOpcode() == ISD::ZERO_EXTEND) &&
51209                         (RHS.getOpcode() == ISD::SIGN_EXTEND ||
51210                          RHS.getOpcode() == ISD::ZERO_EXTEND) &&
51211                         LHS.getOperand(0).getScalarValueSizeInBits() <= 16 &&
51212                         RHS.getOperand(0).getScalarValueSizeInBits() <= 16;
51213 
51214   // For AVX2+ targets, with the upper bits known zero, we can perform MULHU on
51215   // the (bitcasted) inputs directly, and then cheaply pack/truncate the result
51216   // (upper elts will be zero). Don't attempt this with just AVX512F as MULHU
51217   // will have to split anyway.
51218   unsigned InSizeInBits = InVT.getSizeInBits();
51219   if (IsUnsigned && !IsTruncateFree && Subtarget.hasInt256() &&
51220       !(Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.is256BitVector()) &&
51221       (InSizeInBits % 16) == 0) {
51222     EVT BCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
51223                                 InVT.getSizeInBits() / 16);
51224     SDValue Res = DAG.getNode(ISD::MULHU, DL, BCVT, DAG.getBitcast(BCVT, LHS),
51225                               DAG.getBitcast(BCVT, RHS));
51226     return DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getBitcast(InVT, Res));
51227   }
51228 
51229   // Truncate back to source type.
51230   LHS = DAG.getNode(ISD::TRUNCATE, DL, VT, LHS);
51231   RHS = DAG.getNode(ISD::TRUNCATE, DL, VT, RHS);
51232 
51233   unsigned Opc = IsSigned ? ISD::MULHS : ISD::MULHU;
51234   return DAG.getNode(Opc, DL, VT, LHS, RHS);
51235 }
51236 
51237 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
51238 // from one vector with signed bytes from another vector, adds together
51239 // adjacent pairs of 16-bit products, and saturates the result before
51240 // truncating to 16-bits.
51241 //
51242 // Which looks something like this:
51243 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
51244 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
detectPMADDUBSW(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)51245 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
51246                                const X86Subtarget &Subtarget,
51247                                const SDLoc &DL) {
51248   if (!VT.isVector() || !Subtarget.hasSSSE3())
51249     return SDValue();
51250 
51251   unsigned NumElems = VT.getVectorNumElements();
51252   EVT ScalarVT = VT.getVectorElementType();
51253   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
51254     return SDValue();
51255 
51256   SDValue SSatVal = detectSSatPattern(In, VT);
51257   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
51258     return SDValue();
51259 
51260   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
51261   // of multiplies from even/odd elements.
51262   SDValue N0 = SSatVal.getOperand(0);
51263   SDValue N1 = SSatVal.getOperand(1);
51264 
51265   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
51266     return SDValue();
51267 
51268   SDValue N00 = N0.getOperand(0);
51269   SDValue N01 = N0.getOperand(1);
51270   SDValue N10 = N1.getOperand(0);
51271   SDValue N11 = N1.getOperand(1);
51272 
51273   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
51274   // Canonicalize zero_extend to LHS.
51275   if (N01.getOpcode() == ISD::ZERO_EXTEND)
51276     std::swap(N00, N01);
51277   if (N11.getOpcode() == ISD::ZERO_EXTEND)
51278     std::swap(N10, N11);
51279 
51280   // Ensure we have a zero_extend and a sign_extend.
51281   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
51282       N01.getOpcode() != ISD::SIGN_EXTEND ||
51283       N10.getOpcode() != ISD::ZERO_EXTEND ||
51284       N11.getOpcode() != ISD::SIGN_EXTEND)
51285     return SDValue();
51286 
51287   // Peek through the extends.
51288   N00 = N00.getOperand(0);
51289   N01 = N01.getOperand(0);
51290   N10 = N10.getOperand(0);
51291   N11 = N11.getOperand(0);
51292 
51293   // Ensure the extend is from vXi8.
51294   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
51295       N01.getValueType().getVectorElementType() != MVT::i8 ||
51296       N10.getValueType().getVectorElementType() != MVT::i8 ||
51297       N11.getValueType().getVectorElementType() != MVT::i8)
51298     return SDValue();
51299 
51300   // All inputs should be build_vectors.
51301   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
51302       N01.getOpcode() != ISD::BUILD_VECTOR ||
51303       N10.getOpcode() != ISD::BUILD_VECTOR ||
51304       N11.getOpcode() != ISD::BUILD_VECTOR)
51305     return SDValue();
51306 
51307   // N00/N10 are zero extended. N01/N11 are sign extended.
51308 
51309   // For each element, we need to ensure we have an odd element from one vector
51310   // multiplied by the odd element of another vector and the even element from
51311   // one of the same vectors being multiplied by the even element from the
51312   // other vector. So we need to make sure for each element i, this operator
51313   // is being performed:
51314   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
51315   SDValue ZExtIn, SExtIn;
51316   for (unsigned i = 0; i != NumElems; ++i) {
51317     SDValue N00Elt = N00.getOperand(i);
51318     SDValue N01Elt = N01.getOperand(i);
51319     SDValue N10Elt = N10.getOperand(i);
51320     SDValue N11Elt = N11.getOperand(i);
51321     // TODO: Be more tolerant to undefs.
51322     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51323         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51324         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
51325         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
51326       return SDValue();
51327     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
51328     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
51329     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
51330     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
51331     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
51332       return SDValue();
51333     unsigned IdxN00 = ConstN00Elt->getZExtValue();
51334     unsigned IdxN01 = ConstN01Elt->getZExtValue();
51335     unsigned IdxN10 = ConstN10Elt->getZExtValue();
51336     unsigned IdxN11 = ConstN11Elt->getZExtValue();
51337     // Add is commutative so indices can be reordered.
51338     if (IdxN00 > IdxN10) {
51339       std::swap(IdxN00, IdxN10);
51340       std::swap(IdxN01, IdxN11);
51341     }
51342     // N0 indices be the even element. N1 indices must be the next odd element.
51343     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
51344         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
51345       return SDValue();
51346     SDValue N00In = N00Elt.getOperand(0);
51347     SDValue N01In = N01Elt.getOperand(0);
51348     SDValue N10In = N10Elt.getOperand(0);
51349     SDValue N11In = N11Elt.getOperand(0);
51350     // First time we find an input capture it.
51351     if (!ZExtIn) {
51352       ZExtIn = N00In;
51353       SExtIn = N01In;
51354     }
51355     if (ZExtIn != N00In || SExtIn != N01In ||
51356         ZExtIn != N10In || SExtIn != N11In)
51357       return SDValue();
51358   }
51359 
51360   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
51361                          ArrayRef<SDValue> Ops) {
51362     // Shrink by adding truncate nodes and let DAGCombine fold with the
51363     // sources.
51364     EVT InVT = Ops[0].getValueType();
51365     assert(InVT.getScalarType() == MVT::i8 &&
51366            "Unexpected scalar element type");
51367     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
51368     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
51369                                  InVT.getVectorNumElements() / 2);
51370     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
51371   };
51372   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
51373                           PMADDBuilder);
51374 }
51375 
combineTruncate(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51376 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
51377                                const X86Subtarget &Subtarget) {
51378   EVT VT = N->getValueType(0);
51379   SDValue Src = N->getOperand(0);
51380   SDLoc DL(N);
51381 
51382   // Attempt to pre-truncate inputs to arithmetic ops instead.
51383   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
51384     return V;
51385 
51386   // Try to detect AVG pattern first.
51387   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
51388     return Avg;
51389 
51390   // Try to detect PMADD
51391   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
51392     return PMAdd;
51393 
51394   // Try to combine truncation with signed/unsigned saturation.
51395   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
51396     return Val;
51397 
51398   // Try to combine PMULHUW/PMULHW for vXi16.
51399   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
51400     return V;
51401 
51402   // The bitcast source is a direct mmx result.
51403   // Detect bitcasts between i32 to x86mmx
51404   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
51405     SDValue BCSrc = Src.getOperand(0);
51406     if (BCSrc.getValueType() == MVT::x86mmx)
51407       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
51408   }
51409 
51410   return SDValue();
51411 }
51412 
combineVTRUNC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)51413 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
51414                              TargetLowering::DAGCombinerInfo &DCI) {
51415   EVT VT = N->getValueType(0);
51416   SDValue In = N->getOperand(0);
51417   SDLoc DL(N);
51418 
51419   if (SDValue SSatVal = detectSSatPattern(In, VT))
51420     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
51421   if (SDValue USatVal = detectUSatPattern(In, VT, DAG, DL))
51422     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
51423 
51424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51425   APInt DemandedMask(APInt::getAllOnes(VT.getScalarSizeInBits()));
51426   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
51427     return SDValue(N, 0);
51428 
51429   return SDValue();
51430 }
51431 
51432 /// Returns the negated value if the node \p N flips sign of FP value.
51433 ///
51434 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
51435 /// or FSUB(0, x)
51436 /// AVX512F does not have FXOR, so FNEG is lowered as
51437 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
51438 /// In this case we go though all bitcasts.
51439 /// This also recognizes splat of a negated value and returns the splat of that
51440 /// value.
isFNEG(SelectionDAG & DAG,SDNode * N,unsigned Depth=0)51441 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
51442   if (N->getOpcode() == ISD::FNEG)
51443     return N->getOperand(0);
51444 
51445   // Don't recurse exponentially.
51446   if (Depth > SelectionDAG::MaxRecursionDepth)
51447     return SDValue();
51448 
51449   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
51450 
51451   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
51452   EVT VT = Op->getValueType(0);
51453 
51454   // Make sure the element size doesn't change.
51455   if (VT.getScalarSizeInBits() != ScalarSize)
51456     return SDValue();
51457 
51458   unsigned Opc = Op.getOpcode();
51459   switch (Opc) {
51460   case ISD::VECTOR_SHUFFLE: {
51461     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
51462     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
51463     if (!Op.getOperand(1).isUndef())
51464       return SDValue();
51465     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
51466       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
51467         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
51468                                     cast<ShuffleVectorSDNode>(Op)->getMask());
51469     break;
51470   }
51471   case ISD::INSERT_VECTOR_ELT: {
51472     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
51473     // -V, INDEX).
51474     SDValue InsVector = Op.getOperand(0);
51475     SDValue InsVal = Op.getOperand(1);
51476     if (!InsVector.isUndef())
51477       return SDValue();
51478     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
51479       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
51480         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
51481                            NegInsVal, Op.getOperand(2));
51482     break;
51483   }
51484   case ISD::FSUB:
51485   case ISD::XOR:
51486   case X86ISD::FXOR: {
51487     SDValue Op1 = Op.getOperand(1);
51488     SDValue Op0 = Op.getOperand(0);
51489 
51490     // For XOR and FXOR, we want to check if constant
51491     // bits of Op1 are sign bit masks. For FSUB, we
51492     // have to check if constant bits of Op0 are sign
51493     // bit masks and hence we swap the operands.
51494     if (Opc == ISD::FSUB)
51495       std::swap(Op0, Op1);
51496 
51497     APInt UndefElts;
51498     SmallVector<APInt, 16> EltBits;
51499     // Extract constant bits and see if they are all
51500     // sign bit masks. Ignore the undef elements.
51501     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
51502                                       /* AllowWholeUndefs */ true,
51503                                       /* AllowPartialUndefs */ false)) {
51504       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
51505         if (!UndefElts[I] && !EltBits[I].isSignMask())
51506           return SDValue();
51507 
51508       // Only allow bitcast from correctly-sized constant.
51509       Op0 = peekThroughBitcasts(Op0);
51510       if (Op0.getScalarValueSizeInBits() == ScalarSize)
51511         return Op0;
51512     }
51513     break;
51514   } // case
51515   } // switch
51516 
51517   return SDValue();
51518 }
51519 
negateFMAOpcode(unsigned Opcode,bool NegMul,bool NegAcc,bool NegRes)51520 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
51521                                 bool NegRes) {
51522   if (NegMul) {
51523     switch (Opcode) {
51524     default: llvm_unreachable("Unexpected opcode");
51525     case ISD::FMA:              Opcode = X86ISD::FNMADD;        break;
51526     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FNMADD; break;
51527     case X86ISD::FMADD_RND:     Opcode = X86ISD::FNMADD_RND;    break;
51528     case X86ISD::FMSUB:         Opcode = X86ISD::FNMSUB;        break;
51529     case X86ISD::STRICT_FMSUB:  Opcode = X86ISD::STRICT_FNMSUB; break;
51530     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FNMSUB_RND;    break;
51531     case X86ISD::FNMADD:        Opcode = ISD::FMA;              break;
51532     case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA;       break;
51533     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FMADD_RND;     break;
51534     case X86ISD::FNMSUB:        Opcode = X86ISD::FMSUB;         break;
51535     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB;  break;
51536     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FMSUB_RND;     break;
51537     }
51538   }
51539 
51540   if (NegAcc) {
51541     switch (Opcode) {
51542     default: llvm_unreachable("Unexpected opcode");
51543     case ISD::FMA:              Opcode = X86ISD::FMSUB;         break;
51544     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FMSUB;  break;
51545     case X86ISD::FMADD_RND:     Opcode = X86ISD::FMSUB_RND;     break;
51546     case X86ISD::FMSUB:         Opcode = ISD::FMA;              break;
51547     case X86ISD::STRICT_FMSUB:  Opcode = ISD::STRICT_FMA;       break;
51548     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FMADD_RND;     break;
51549     case X86ISD::FNMADD:        Opcode = X86ISD::FNMSUB;        break;
51550     case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
51551     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FNMSUB_RND;    break;
51552     case X86ISD::FNMSUB:        Opcode = X86ISD::FNMADD;        break;
51553     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
51554     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FNMADD_RND;    break;
51555     case X86ISD::FMADDSUB:      Opcode = X86ISD::FMSUBADD;      break;
51556     case X86ISD::FMADDSUB_RND:  Opcode = X86ISD::FMSUBADD_RND;  break;
51557     case X86ISD::FMSUBADD:      Opcode = X86ISD::FMADDSUB;      break;
51558     case X86ISD::FMSUBADD_RND:  Opcode = X86ISD::FMADDSUB_RND;  break;
51559     }
51560   }
51561 
51562   if (NegRes) {
51563     switch (Opcode) {
51564     // For accuracy reason, we never combine fneg and fma under strict FP.
51565     default: llvm_unreachable("Unexpected opcode");
51566     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
51567     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
51568     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
51569     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
51570     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
51571     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
51572     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
51573     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
51574     }
51575   }
51576 
51577   return Opcode;
51578 }
51579 
51580 /// Do target-specific dag combines on floating point negations.
combineFneg(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)51581 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
51582                            TargetLowering::DAGCombinerInfo &DCI,
51583                            const X86Subtarget &Subtarget) {
51584   EVT OrigVT = N->getValueType(0);
51585   SDValue Arg = isFNEG(DAG, N);
51586   if (!Arg)
51587     return SDValue();
51588 
51589   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51590   EVT VT = Arg.getValueType();
51591   EVT SVT = VT.getScalarType();
51592   SDLoc DL(N);
51593 
51594   // Let legalize expand this if it isn't a legal type yet.
51595   if (!TLI.isTypeLegal(VT))
51596     return SDValue();
51597 
51598   // If we're negating a FMUL node on a target with FMA, then we can avoid the
51599   // use of a constant by performing (-0 - A*B) instead.
51600   // FIXME: Check rounding control flags as well once it becomes available.
51601   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
51602       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
51603     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
51604     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
51605                                   Arg.getOperand(1), Zero);
51606     return DAG.getBitcast(OrigVT, NewNode);
51607   }
51608 
51609   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
51610   bool LegalOperations = !DCI.isBeforeLegalizeOps();
51611   if (SDValue NegArg =
51612           TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
51613     return DAG.getBitcast(OrigVT, NegArg);
51614 
51615   return SDValue();
51616 }
51617 
getNegatedExpression(SDValue Op,SelectionDAG & DAG,bool LegalOperations,bool ForCodeSize,NegatibleCost & Cost,unsigned Depth) const51618 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
51619                                                 bool LegalOperations,
51620                                                 bool ForCodeSize,
51621                                                 NegatibleCost &Cost,
51622                                                 unsigned Depth) const {
51623   // fneg patterns are removable even if they have multiple uses.
51624   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
51625     Cost = NegatibleCost::Cheaper;
51626     return DAG.getBitcast(Op.getValueType(), Arg);
51627   }
51628 
51629   EVT VT = Op.getValueType();
51630   EVT SVT = VT.getScalarType();
51631   unsigned Opc = Op.getOpcode();
51632   SDNodeFlags Flags = Op.getNode()->getFlags();
51633   switch (Opc) {
51634   case ISD::FMA:
51635   case X86ISD::FMSUB:
51636   case X86ISD::FNMADD:
51637   case X86ISD::FNMSUB:
51638   case X86ISD::FMADD_RND:
51639   case X86ISD::FMSUB_RND:
51640   case X86ISD::FNMADD_RND:
51641   case X86ISD::FNMSUB_RND: {
51642     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
51643         !(SVT == MVT::f32 || SVT == MVT::f64) ||
51644         !isOperationLegal(ISD::FMA, VT))
51645       break;
51646 
51647     // Don't fold (fneg (fma (fneg x), y, (fneg z))) to (fma x, y, z)
51648     // if it may have signed zeros.
51649     if (!Flags.hasNoSignedZeros())
51650       break;
51651 
51652     // This is always negatible for free but we might be able to remove some
51653     // extra operand negations as well.
51654     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
51655     for (int i = 0; i != 3; ++i)
51656       NewOps[i] = getCheaperNegatedExpression(
51657           Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
51658 
51659     bool NegA = !!NewOps[0];
51660     bool NegB = !!NewOps[1];
51661     bool NegC = !!NewOps[2];
51662     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
51663 
51664     Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
51665                                   : NegatibleCost::Neutral;
51666 
51667     // Fill in the non-negated ops with the original values.
51668     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
51669       if (!NewOps[i])
51670         NewOps[i] = Op.getOperand(i);
51671     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
51672   }
51673   case X86ISD::FRCP:
51674     if (SDValue NegOp0 =
51675             getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
51676                                  ForCodeSize, Cost, Depth + 1))
51677       return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
51678     break;
51679   }
51680 
51681   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
51682                                               ForCodeSize, Cost, Depth);
51683 }
51684 
lowerX86FPLogicOp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51685 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
51686                                  const X86Subtarget &Subtarget) {
51687   MVT VT = N->getSimpleValueType(0);
51688   // If we have integer vector types available, use the integer opcodes.
51689   if (!VT.isVector() || !Subtarget.hasSSE2())
51690     return SDValue();
51691 
51692   SDLoc dl(N);
51693 
51694   unsigned IntBits = VT.getScalarSizeInBits();
51695   MVT IntSVT = MVT::getIntegerVT(IntBits);
51696   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
51697 
51698   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
51699   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
51700   unsigned IntOpcode;
51701   switch (N->getOpcode()) {
51702   default: llvm_unreachable("Unexpected FP logic op");
51703   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
51704   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
51705   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
51706   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
51707   }
51708   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
51709   return DAG.getBitcast(VT, IntOp);
51710 }
51711 
51712 
51713 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
foldXor1SetCC(SDNode * N,SelectionDAG & DAG)51714 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
51715   if (N->getOpcode() != ISD::XOR)
51716     return SDValue();
51717 
51718   SDValue LHS = N->getOperand(0);
51719   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
51720     return SDValue();
51721 
51722   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
51723       X86::CondCode(LHS->getConstantOperandVal(0)));
51724   SDLoc DL(N);
51725   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
51726 }
51727 
combineXorSubCTLZ(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51728 static SDValue combineXorSubCTLZ(SDNode *N, SelectionDAG &DAG,
51729                                  const X86Subtarget &Subtarget) {
51730   assert((N->getOpcode() == ISD::XOR || N->getOpcode() == ISD::SUB) &&
51731          "Invalid opcode for combing with CTLZ");
51732   if (Subtarget.hasFastLZCNT())
51733     return SDValue();
51734 
51735   EVT VT = N->getValueType(0);
51736   if (VT != MVT::i8 && VT != MVT::i16 && VT != MVT::i32 &&
51737       (VT != MVT::i64 || !Subtarget.is64Bit()))
51738     return SDValue();
51739 
51740   SDValue N0 = N->getOperand(0);
51741   SDValue N1 = N->getOperand(1);
51742 
51743   if (N0.getOpcode() != ISD::CTLZ_ZERO_UNDEF &&
51744       N1.getOpcode() != ISD::CTLZ_ZERO_UNDEF)
51745     return SDValue();
51746 
51747   SDValue OpCTLZ;
51748   SDValue OpSizeTM1;
51749 
51750   if (N1.getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
51751     OpCTLZ = N1;
51752     OpSizeTM1 = N0;
51753   } else if (N->getOpcode() == ISD::SUB) {
51754     return SDValue();
51755   } else {
51756     OpCTLZ = N0;
51757     OpSizeTM1 = N1;
51758   }
51759 
51760   if (!OpCTLZ.hasOneUse())
51761     return SDValue();
51762   auto *C = dyn_cast<ConstantSDNode>(OpSizeTM1);
51763   if (!C)
51764     return SDValue();
51765 
51766   if (C->getZExtValue() != uint64_t(OpCTLZ.getValueSizeInBits() - 1))
51767     return SDValue();
51768   SDLoc DL(N);
51769   EVT OpVT = VT;
51770   SDValue Op = OpCTLZ.getOperand(0);
51771   if (VT == MVT::i8) {
51772     // Zero extend to i32 since there is not an i8 bsr.
51773     OpVT = MVT::i32;
51774     Op = DAG.getNode(ISD::ZERO_EXTEND, DL, OpVT, Op);
51775   }
51776 
51777   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
51778   Op = DAG.getNode(X86ISD::BSR, DL, VTs, Op);
51779   if (VT == MVT::i8)
51780     Op = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Op);
51781 
51782   return Op;
51783 }
51784 
combineXor(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)51785 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
51786                           TargetLowering::DAGCombinerInfo &DCI,
51787                           const X86Subtarget &Subtarget) {
51788   SDValue N0 = N->getOperand(0);
51789   SDValue N1 = N->getOperand(1);
51790   EVT VT = N->getValueType(0);
51791 
51792   // If this is SSE1 only convert to FXOR to avoid scalarization.
51793   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
51794     return DAG.getBitcast(MVT::v4i32,
51795                           DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
51796                                       DAG.getBitcast(MVT::v4f32, N0),
51797                                       DAG.getBitcast(MVT::v4f32, N1)));
51798   }
51799 
51800   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
51801     return Cmp;
51802 
51803   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
51804     return R;
51805 
51806   if (SDValue R = combineBitOpWithShift(N, DAG))
51807     return R;
51808 
51809   if (SDValue R = combineBitOpWithPACK(N, DAG))
51810     return R;
51811 
51812   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, DCI, Subtarget))
51813     return FPLogic;
51814 
51815   if (SDValue R = combineXorSubCTLZ(N, DAG, Subtarget))
51816     return R;
51817 
51818   if (DCI.isBeforeLegalizeOps())
51819     return SDValue();
51820 
51821   if (SDValue SetCC = foldXor1SetCC(N, DAG))
51822     return SetCC;
51823 
51824   if (SDValue R = combineOrXorWithSETCC(N, N0, N1, DAG))
51825     return R;
51826 
51827   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
51828     return RV;
51829 
51830   // Fold not(iX bitcast(vXi1)) -> (iX bitcast(not(vec))) for legal boolvecs.
51831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51832   if (llvm::isAllOnesConstant(N1) && N0.getOpcode() == ISD::BITCAST &&
51833       N0.getOperand(0).getValueType().isVector() &&
51834       N0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
51835       TLI.isTypeLegal(N0.getOperand(0).getValueType()) && N0.hasOneUse()) {
51836     return DAG.getBitcast(VT, DAG.getNOT(SDLoc(N), N0.getOperand(0),
51837                                          N0.getOperand(0).getValueType()));
51838   }
51839 
51840   // Handle AVX512 mask widening.
51841   // Fold not(insert_subvector(undef,sub)) -> insert_subvector(undef,not(sub))
51842   if (ISD::isBuildVectorAllOnes(N1.getNode()) && VT.isVector() &&
51843       VT.getVectorElementType() == MVT::i1 &&
51844       N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.getOperand(0).isUndef() &&
51845       TLI.isTypeLegal(N0.getOperand(1).getValueType())) {
51846     return DAG.getNode(
51847         ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
51848         DAG.getNOT(SDLoc(N), N0.getOperand(1), N0.getOperand(1).getValueType()),
51849         N0.getOperand(2));
51850   }
51851 
51852   // Fold xor(zext(xor(x,c1)),c2) -> xor(zext(x),xor(zext(c1),c2))
51853   // Fold xor(truncate(xor(x,c1)),c2) -> xor(truncate(x),xor(truncate(c1),c2))
51854   // TODO: Under what circumstances could this be performed in DAGCombine?
51855   if ((N0.getOpcode() == ISD::TRUNCATE || N0.getOpcode() == ISD::ZERO_EXTEND) &&
51856       N0.getOperand(0).getOpcode() == N->getOpcode()) {
51857     SDValue TruncExtSrc = N0.getOperand(0);
51858     auto *N1C = dyn_cast<ConstantSDNode>(N1);
51859     auto *N001C = dyn_cast<ConstantSDNode>(TruncExtSrc.getOperand(1));
51860     if (N1C && !N1C->isOpaque() && N001C && !N001C->isOpaque()) {
51861       SDLoc DL(N);
51862       SDValue LHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(0), DL, VT);
51863       SDValue RHS = DAG.getZExtOrTrunc(TruncExtSrc.getOperand(1), DL, VT);
51864       return DAG.getNode(ISD::XOR, DL, VT, LHS,
51865                          DAG.getNode(ISD::XOR, DL, VT, RHS, N1));
51866     }
51867   }
51868 
51869   if (SDValue R = combineBMILogicOp(N, DAG, Subtarget))
51870     return R;
51871 
51872   return combineFneg(N, DAG, DCI, Subtarget);
51873 }
51874 
combineBITREVERSE(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)51875 static SDValue combineBITREVERSE(SDNode *N, SelectionDAG &DAG,
51876                                  TargetLowering::DAGCombinerInfo &DCI,
51877                                  const X86Subtarget &Subtarget) {
51878   SDValue N0 = N->getOperand(0);
51879   EVT VT = N->getValueType(0);
51880 
51881   // Convert a (iX bitreverse(bitcast(vXi1 X))) -> (iX bitcast(shuffle(X)))
51882   if (VT.isInteger() && N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) {
51883     SDValue Src = N0.getOperand(0);
51884     EVT SrcVT = Src.getValueType();
51885     if (SrcVT.isVector() && SrcVT.getScalarType() == MVT::i1 &&
51886         (DCI.isBeforeLegalize() ||
51887          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)) &&
51888         Subtarget.hasSSSE3()) {
51889       unsigned NumElts = SrcVT.getVectorNumElements();
51890       SmallVector<int, 32> ReverseMask(NumElts);
51891       for (unsigned I = 0; I != NumElts; ++I)
51892         ReverseMask[I] = (NumElts - 1) - I;
51893       SDValue Rev =
51894           DAG.getVectorShuffle(SrcVT, SDLoc(N), Src, Src, ReverseMask);
51895       return DAG.getBitcast(VT, Rev);
51896     }
51897   }
51898 
51899   return SDValue();
51900 }
51901 
combineBEXTR(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)51902 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
51903                             TargetLowering::DAGCombinerInfo &DCI,
51904                             const X86Subtarget &Subtarget) {
51905   EVT VT = N->getValueType(0);
51906   unsigned NumBits = VT.getSizeInBits();
51907 
51908   // TODO - Constant Folding.
51909 
51910   // Simplify the inputs.
51911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
51912   APInt DemandedMask(APInt::getAllOnes(NumBits));
51913   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
51914     return SDValue(N, 0);
51915 
51916   return SDValue();
51917 }
51918 
isNullFPScalarOrVectorConst(SDValue V)51919 static bool isNullFPScalarOrVectorConst(SDValue V) {
51920   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
51921 }
51922 
51923 /// If a value is a scalar FP zero or a vector FP zero (potentially including
51924 /// undefined elements), return a zero constant that may be used to fold away
51925 /// that value. In the case of a vector, the returned constant will not contain
51926 /// undefined elements even if the input parameter does. This makes it suitable
51927 /// to be used as a replacement operand with operations (eg, bitwise-and) where
51928 /// an undef should not propagate.
getNullFPConstForNullVal(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)51929 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
51930                                         const X86Subtarget &Subtarget) {
51931   if (!isNullFPScalarOrVectorConst(V))
51932     return SDValue();
51933 
51934   if (V.getValueType().isVector())
51935     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
51936 
51937   return V;
51938 }
51939 
combineFAndFNotToFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51940 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
51941                                       const X86Subtarget &Subtarget) {
51942   SDValue N0 = N->getOperand(0);
51943   SDValue N1 = N->getOperand(1);
51944   EVT VT = N->getValueType(0);
51945   SDLoc DL(N);
51946 
51947   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
51948   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
51949         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
51950         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
51951     return SDValue();
51952 
51953   auto isAllOnesConstantFP = [](SDValue V) {
51954     if (V.getSimpleValueType().isVector())
51955       return ISD::isBuildVectorAllOnes(V.getNode());
51956     auto *C = dyn_cast<ConstantFPSDNode>(V);
51957     return C && C->getConstantFPValue()->isAllOnesValue();
51958   };
51959 
51960   // fand (fxor X, -1), Y --> fandn X, Y
51961   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
51962     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
51963 
51964   // fand X, (fxor Y, -1) --> fandn Y, X
51965   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
51966     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
51967 
51968   return SDValue();
51969 }
51970 
51971 /// Do target-specific dag combines on X86ISD::FAND nodes.
combineFAnd(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51972 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
51973                            const X86Subtarget &Subtarget) {
51974   // FAND(0.0, x) -> 0.0
51975   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
51976     return V;
51977 
51978   // FAND(x, 0.0) -> 0.0
51979   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
51980     return V;
51981 
51982   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
51983     return V;
51984 
51985   return lowerX86FPLogicOp(N, DAG, Subtarget);
51986 }
51987 
51988 /// Do target-specific dag combines on X86ISD::FANDN nodes.
combineFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)51989 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
51990                             const X86Subtarget &Subtarget) {
51991   // FANDN(0.0, x) -> x
51992   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
51993     return N->getOperand(1);
51994 
51995   // FANDN(x, 0.0) -> 0.0
51996   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
51997     return V;
51998 
51999   return lowerX86FPLogicOp(N, DAG, Subtarget);
52000 }
52001 
52002 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
combineFOr(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)52003 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
52004                           TargetLowering::DAGCombinerInfo &DCI,
52005                           const X86Subtarget &Subtarget) {
52006   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
52007 
52008   // F[X]OR(0.0, x) -> x
52009   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
52010     return N->getOperand(1);
52011 
52012   // F[X]OR(x, 0.0) -> x
52013   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
52014     return N->getOperand(0);
52015 
52016   if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
52017     return NewVal;
52018 
52019   return lowerX86FPLogicOp(N, DAG, Subtarget);
52020 }
52021 
52022 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
combineFMinFMax(SDNode * N,SelectionDAG & DAG)52023 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
52024   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
52025 
52026   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
52027   if (!DAG.getTarget().Options.NoNaNsFPMath ||
52028       !DAG.getTarget().Options.NoSignedZerosFPMath)
52029     return SDValue();
52030 
52031   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
52032   // into FMINC and FMAXC, which are Commutative operations.
52033   unsigned NewOp = 0;
52034   switch (N->getOpcode()) {
52035     default: llvm_unreachable("unknown opcode");
52036     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
52037     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
52038   }
52039 
52040   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
52041                      N->getOperand(0), N->getOperand(1));
52042 }
52043 
combineFMinNumFMaxNum(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)52044 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
52045                                      const X86Subtarget &Subtarget) {
52046   EVT VT = N->getValueType(0);
52047   if (Subtarget.useSoftFloat() || isSoftF16(VT, Subtarget))
52048     return SDValue();
52049 
52050   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52051 
52052   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
52053         (Subtarget.hasSSE2() && VT == MVT::f64) ||
52054         (Subtarget.hasFP16() && VT == MVT::f16) ||
52055         (VT.isVector() && TLI.isTypeLegal(VT))))
52056     return SDValue();
52057 
52058   SDValue Op0 = N->getOperand(0);
52059   SDValue Op1 = N->getOperand(1);
52060   SDLoc DL(N);
52061   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
52062 
52063   // If we don't have to respect NaN inputs, this is a direct translation to x86
52064   // min/max instructions.
52065   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
52066     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
52067 
52068   // If one of the operands is known non-NaN use the native min/max instructions
52069   // with the non-NaN input as second operand.
52070   if (DAG.isKnownNeverNaN(Op1))
52071     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
52072   if (DAG.isKnownNeverNaN(Op0))
52073     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
52074 
52075   // If we have to respect NaN inputs, this takes at least 3 instructions.
52076   // Favor a library call when operating on a scalar and minimizing code size.
52077   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
52078     return SDValue();
52079 
52080   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
52081                                          VT);
52082 
52083   // There are 4 possibilities involving NaN inputs, and these are the required
52084   // outputs:
52085   //                   Op1
52086   //               Num     NaN
52087   //            ----------------
52088   //       Num  |  Max  |  Op0 |
52089   // Op0        ----------------
52090   //       NaN  |  Op1  |  NaN |
52091   //            ----------------
52092   //
52093   // The SSE FP max/min instructions were not designed for this case, but rather
52094   // to implement:
52095   //   Min = Op1 < Op0 ? Op1 : Op0
52096   //   Max = Op1 > Op0 ? Op1 : Op0
52097   //
52098   // So they always return Op0 if either input is a NaN. However, we can still
52099   // use those instructions for fmaxnum by selecting away a NaN input.
52100 
52101   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
52102   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
52103   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
52104 
52105   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
52106   // are NaN, the NaN value of Op1 is the result.
52107   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
52108 }
52109 
combineX86INT_TO_FP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)52110 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
52111                                    TargetLowering::DAGCombinerInfo &DCI) {
52112   EVT VT = N->getValueType(0);
52113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52114 
52115   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
52116   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
52117     return SDValue(N, 0);
52118 
52119   // Convert a full vector load into vzload when not all bits are needed.
52120   SDValue In = N->getOperand(0);
52121   MVT InVT = In.getSimpleValueType();
52122   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
52123       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
52124     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
52125     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
52126     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
52127     MVT MemVT = MVT::getIntegerVT(NumBits);
52128     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
52129     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
52130       SDLoc dl(N);
52131       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
52132                                     DAG.getBitcast(InVT, VZLoad));
52133       DCI.CombineTo(N, Convert);
52134       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
52135       DCI.recursivelyDeleteUnusedNodes(LN);
52136       return SDValue(N, 0);
52137     }
52138   }
52139 
52140   return SDValue();
52141 }
52142 
combineCVTP2I_CVTTP2I(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)52143 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
52144                                      TargetLowering::DAGCombinerInfo &DCI) {
52145   bool IsStrict = N->isTargetStrictFPOpcode();
52146   EVT VT = N->getValueType(0);
52147 
52148   // Convert a full vector load into vzload when not all bits are needed.
52149   SDValue In = N->getOperand(IsStrict ? 1 : 0);
52150   MVT InVT = In.getSimpleValueType();
52151   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
52152       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
52153     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
52154     LoadSDNode *LN = cast<LoadSDNode>(In);
52155     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
52156     MVT MemVT = MVT::getFloatingPointVT(NumBits);
52157     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
52158     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
52159       SDLoc dl(N);
52160       if (IsStrict) {
52161         SDValue Convert =
52162             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
52163                         {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
52164         DCI.CombineTo(N, Convert, Convert.getValue(1));
52165       } else {
52166         SDValue Convert =
52167             DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
52168         DCI.CombineTo(N, Convert);
52169       }
52170       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
52171       DCI.recursivelyDeleteUnusedNodes(LN);
52172       return SDValue(N, 0);
52173     }
52174   }
52175 
52176   return SDValue();
52177 }
52178 
52179 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
combineAndnp(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)52180 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
52181                             TargetLowering::DAGCombinerInfo &DCI,
52182                             const X86Subtarget &Subtarget) {
52183   SDValue N0 = N->getOperand(0);
52184   SDValue N1 = N->getOperand(1);
52185   MVT VT = N->getSimpleValueType(0);
52186   int NumElts = VT.getVectorNumElements();
52187   unsigned EltSizeInBits = VT.getScalarSizeInBits();
52188   SDLoc DL(N);
52189 
52190   // ANDNP(undef, x) -> 0
52191   // ANDNP(x, undef) -> 0
52192   if (N0.isUndef() || N1.isUndef())
52193     return DAG.getConstant(0, DL, VT);
52194 
52195   // ANDNP(0, x) -> x
52196   if (ISD::isBuildVectorAllZeros(N0.getNode()))
52197     return N1;
52198 
52199   // ANDNP(x, 0) -> 0
52200   if (ISD::isBuildVectorAllZeros(N1.getNode()))
52201     return DAG.getConstant(0, DL, VT);
52202 
52203   // ANDNP(x, -1) -> NOT(x) -> XOR(x, -1)
52204   if (ISD::isBuildVectorAllOnes(N1.getNode()))
52205     return DAG.getNOT(DL, N0, VT);
52206 
52207   // Turn ANDNP back to AND if input is inverted.
52208   if (SDValue Not = IsNOT(N0, DAG))
52209     return DAG.getNode(ISD::AND, DL, VT, DAG.getBitcast(VT, Not), N1);
52210 
52211   // Fold for better commutatvity:
52212   // ANDNP(x,NOT(y)) -> AND(NOT(x),NOT(y)) -> NOT(OR(X,Y)).
52213   if (N1->hasOneUse())
52214     if (SDValue Not = IsNOT(N1, DAG))
52215       return DAG.getNOT(
52216           DL, DAG.getNode(ISD::OR, DL, VT, N0, DAG.getBitcast(VT, Not)), VT);
52217 
52218   // Constant Folding
52219   APInt Undefs0, Undefs1;
52220   SmallVector<APInt> EltBits0, EltBits1;
52221   if (getTargetConstantBitsFromNode(N0, EltSizeInBits, Undefs0, EltBits0)) {
52222     if (getTargetConstantBitsFromNode(N1, EltSizeInBits, Undefs1, EltBits1)) {
52223       SmallVector<APInt> ResultBits;
52224       for (int I = 0; I != NumElts; ++I)
52225         ResultBits.push_back(~EltBits0[I] & EltBits1[I]);
52226       return getConstVector(ResultBits, VT, DAG, DL);
52227     }
52228 
52229     // Constant fold NOT(N0) to allow us to use AND.
52230     // Ensure this is only performed if we can confirm that the bitcasted source
52231     // has oneuse to prevent an infinite loop with canonicalizeBitSelect.
52232     if (N0->hasOneUse()) {
52233       SDValue BC0 = peekThroughOneUseBitcasts(N0);
52234       if (BC0.getOpcode() != ISD::BITCAST) {
52235         for (APInt &Elt : EltBits0)
52236           Elt = ~Elt;
52237         SDValue Not = getConstVector(EltBits0, VT, DAG, DL);
52238         return DAG.getNode(ISD::AND, DL, VT, Not, N1);
52239       }
52240     }
52241   }
52242 
52243   // Attempt to recursively combine a bitmask ANDNP with shuffles.
52244   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
52245     SDValue Op(N, 0);
52246     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
52247       return Res;
52248 
52249     // If either operand is a constant mask, then only the elements that aren't
52250     // zero are actually demanded by the other operand.
52251     auto GetDemandedMasks = [&](SDValue Op, bool Invert = false) {
52252       APInt UndefElts;
52253       SmallVector<APInt> EltBits;
52254       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
52255       APInt DemandedElts = APInt::getAllOnes(NumElts);
52256       if (getTargetConstantBitsFromNode(Op, EltSizeInBits, UndefElts,
52257                                         EltBits)) {
52258         DemandedBits.clearAllBits();
52259         DemandedElts.clearAllBits();
52260         for (int I = 0; I != NumElts; ++I) {
52261           if (UndefElts[I]) {
52262             // We can't assume an undef src element gives an undef dst - the
52263             // other src might be zero.
52264             DemandedBits.setAllBits();
52265             DemandedElts.setBit(I);
52266           } else if ((Invert && !EltBits[I].isAllOnes()) ||
52267                      (!Invert && !EltBits[I].isZero())) {
52268             DemandedBits |= Invert ? ~EltBits[I] : EltBits[I];
52269             DemandedElts.setBit(I);
52270           }
52271         }
52272       }
52273       return std::make_pair(DemandedBits, DemandedElts);
52274     };
52275     APInt Bits0, Elts0;
52276     APInt Bits1, Elts1;
52277     std::tie(Bits0, Elts0) = GetDemandedMasks(N1);
52278     std::tie(Bits1, Elts1) = GetDemandedMasks(N0, true);
52279 
52280     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52281     if (TLI.SimplifyDemandedVectorElts(N0, Elts0, DCI) ||
52282         TLI.SimplifyDemandedVectorElts(N1, Elts1, DCI) ||
52283         TLI.SimplifyDemandedBits(N0, Bits0, Elts0, DCI) ||
52284         TLI.SimplifyDemandedBits(N1, Bits1, Elts1, DCI)) {
52285       if (N->getOpcode() != ISD::DELETED_NODE)
52286         DCI.AddToWorklist(N);
52287       return SDValue(N, 0);
52288     }
52289   }
52290 
52291   return SDValue();
52292 }
52293 
combineBT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)52294 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
52295                          TargetLowering::DAGCombinerInfo &DCI) {
52296   SDValue N1 = N->getOperand(1);
52297 
52298   // BT ignores high bits in the bit index operand.
52299   unsigned BitWidth = N1.getValueSizeInBits();
52300   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
52301   if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
52302     if (N->getOpcode() != ISD::DELETED_NODE)
52303       DCI.AddToWorklist(N);
52304     return SDValue(N, 0);
52305   }
52306 
52307   return SDValue();
52308 }
52309 
combineCVTPH2PS(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)52310 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
52311                                TargetLowering::DAGCombinerInfo &DCI) {
52312   bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
52313   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
52314 
52315   if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
52316     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52317     APInt DemandedElts = APInt::getLowBitsSet(8, 4);
52318     if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, DCI)) {
52319       if (N->getOpcode() != ISD::DELETED_NODE)
52320         DCI.AddToWorklist(N);
52321       return SDValue(N, 0);
52322     }
52323 
52324     // Convert a full vector load into vzload when not all bits are needed.
52325     if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
52326       LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
52327       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
52328         SDLoc dl(N);
52329         if (IsStrict) {
52330           SDValue Convert = DAG.getNode(
52331               N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
52332               {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
52333           DCI.CombineTo(N, Convert, Convert.getValue(1));
52334         } else {
52335           SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
52336                                         DAG.getBitcast(MVT::v8i16, VZLoad));
52337           DCI.CombineTo(N, Convert);
52338         }
52339 
52340         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
52341         DCI.recursivelyDeleteUnusedNodes(LN);
52342         return SDValue(N, 0);
52343       }
52344     }
52345   }
52346 
52347   return SDValue();
52348 }
52349 
52350 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
combineSextInRegCmov(SDNode * N,SelectionDAG & DAG)52351 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
52352   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
52353 
52354   EVT DstVT = N->getValueType(0);
52355 
52356   SDValue N0 = N->getOperand(0);
52357   SDValue N1 = N->getOperand(1);
52358   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
52359 
52360   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
52361     return SDValue();
52362 
52363   // Look through single use any_extends / truncs.
52364   SDValue IntermediateBitwidthOp;
52365   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
52366       N0.hasOneUse()) {
52367     IntermediateBitwidthOp = N0;
52368     N0 = N0.getOperand(0);
52369   }
52370 
52371   // See if we have a single use cmov.
52372   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
52373     return SDValue();
52374 
52375   SDValue CMovOp0 = N0.getOperand(0);
52376   SDValue CMovOp1 = N0.getOperand(1);
52377 
52378   // Make sure both operands are constants.
52379   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
52380       !isa<ConstantSDNode>(CMovOp1.getNode()))
52381     return SDValue();
52382 
52383   SDLoc DL(N);
52384 
52385   // If we looked through an any_extend/trunc above, add one to the constants.
52386   if (IntermediateBitwidthOp) {
52387     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
52388     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
52389     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
52390   }
52391 
52392   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
52393   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
52394 
52395   EVT CMovVT = DstVT;
52396   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
52397   if (DstVT == MVT::i16) {
52398     CMovVT = MVT::i32;
52399     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
52400     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
52401   }
52402 
52403   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
52404                              N0.getOperand(2), N0.getOperand(3));
52405 
52406   if (CMovVT != DstVT)
52407     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
52408 
52409   return CMov;
52410 }
52411 
combineSignExtendInReg(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)52412 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
52413                                       const X86Subtarget &Subtarget) {
52414   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
52415 
52416   if (SDValue V = combineSextInRegCmov(N, DAG))
52417     return V;
52418 
52419   EVT VT = N->getValueType(0);
52420   SDValue N0 = N->getOperand(0);
52421   SDValue N1 = N->getOperand(1);
52422   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
52423   SDLoc dl(N);
52424 
52425   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
52426   // both SSE and AVX2 since there is no sign-extended shift right
52427   // operation on a vector with 64-bit elements.
52428   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
52429   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
52430   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
52431                            N0.getOpcode() == ISD::SIGN_EXTEND)) {
52432     SDValue N00 = N0.getOperand(0);
52433 
52434     // EXTLOAD has a better solution on AVX2,
52435     // it may be replaced with X86ISD::VSEXT node.
52436     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
52437       if (!ISD::isNormalLoad(N00.getNode()))
52438         return SDValue();
52439 
52440     // Attempt to promote any comparison mask ops before moving the
52441     // SIGN_EXTEND_INREG in the way.
52442     if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
52443       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
52444 
52445     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
52446       SDValue Tmp =
52447           DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
52448       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
52449     }
52450   }
52451   return SDValue();
52452 }
52453 
52454 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
52455 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
52456 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
52457 /// opportunities to combine math ops, use an LEA, or use a complex addressing
52458 /// mode. This can eliminate extend, add, and shift instructions.
promoteExtBeforeAdd(SDNode * Ext,SelectionDAG & DAG,const X86Subtarget & Subtarget)52459 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
52460                                    const X86Subtarget &Subtarget) {
52461   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
52462       Ext->getOpcode() != ISD::ZERO_EXTEND)
52463     return SDValue();
52464 
52465   // TODO: This should be valid for other integer types.
52466   EVT VT = Ext->getValueType(0);
52467   if (VT != MVT::i64)
52468     return SDValue();
52469 
52470   SDValue Add = Ext->getOperand(0);
52471   if (Add.getOpcode() != ISD::ADD)
52472     return SDValue();
52473 
52474   SDValue AddOp0 = Add.getOperand(0);
52475   SDValue AddOp1 = Add.getOperand(1);
52476   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
52477   bool NSW = Add->getFlags().hasNoSignedWrap();
52478   bool NUW = Add->getFlags().hasNoUnsignedWrap();
52479   NSW = NSW || (Sext && DAG.willNotOverflowAdd(true, AddOp0, AddOp1));
52480   NUW = NUW || (!Sext && DAG.willNotOverflowAdd(false, AddOp0, AddOp1));
52481 
52482   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
52483   // into the 'zext'
52484   if ((Sext && !NSW) || (!Sext && !NUW))
52485     return SDValue();
52486 
52487   // Having a constant operand to the 'add' ensures that we are not increasing
52488   // the instruction count because the constant is extended for free below.
52489   // A constant operand can also become the displacement field of an LEA.
52490   auto *AddOp1C = dyn_cast<ConstantSDNode>(AddOp1);
52491   if (!AddOp1C)
52492     return SDValue();
52493 
52494   // Don't make the 'add' bigger if there's no hope of combining it with some
52495   // other 'add' or 'shl' instruction.
52496   // TODO: It may be profitable to generate simpler LEA instructions in place
52497   // of single 'add' instructions, but the cost model for selecting an LEA
52498   // currently has a high threshold.
52499   bool HasLEAPotential = false;
52500   for (auto *User : Ext->uses()) {
52501     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
52502       HasLEAPotential = true;
52503       break;
52504     }
52505   }
52506   if (!HasLEAPotential)
52507     return SDValue();
52508 
52509   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
52510   int64_t AddC = Sext ? AddOp1C->getSExtValue() : AddOp1C->getZExtValue();
52511   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
52512   SDValue NewConstant = DAG.getConstant(AddC, SDLoc(Add), VT);
52513 
52514   // The wider add is guaranteed to not wrap because both operands are
52515   // sign-extended.
52516   SDNodeFlags Flags;
52517   Flags.setNoSignedWrap(NSW);
52518   Flags.setNoUnsignedWrap(NUW);
52519   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
52520 }
52521 
52522 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
52523 // operands and the result of CMOV is not used anywhere else - promote CMOV
52524 // itself instead of promoting its result. This could be beneficial, because:
52525 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
52526 //        (or more) pseudo-CMOVs only when they go one-after-another and
52527 //        getting rid of result extension code after CMOV will help that.
52528 //     2) Promotion of constant CMOV arguments is free, hence the
52529 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
52530 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
52531 //        promotion is also good in terms of code-size.
52532 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
52533 //         promotion).
combineToExtendCMOV(SDNode * Extend,SelectionDAG & DAG)52534 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
52535   SDValue CMovN = Extend->getOperand(0);
52536   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
52537     return SDValue();
52538 
52539   EVT TargetVT = Extend->getValueType(0);
52540   unsigned ExtendOpcode = Extend->getOpcode();
52541   SDLoc DL(Extend);
52542 
52543   EVT VT = CMovN.getValueType();
52544   SDValue CMovOp0 = CMovN.getOperand(0);
52545   SDValue CMovOp1 = CMovN.getOperand(1);
52546 
52547   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
52548       !isa<ConstantSDNode>(CMovOp1.getNode()))
52549     return SDValue();
52550 
52551   // Only extend to i32 or i64.
52552   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
52553     return SDValue();
52554 
52555   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
52556   // are free.
52557   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
52558     return SDValue();
52559 
52560   // If this a zero extend to i64, we should only extend to i32 and use a free
52561   // zero extend to finish.
52562   EVT ExtendVT = TargetVT;
52563   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
52564     ExtendVT = MVT::i32;
52565 
52566   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
52567   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
52568 
52569   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
52570                             CMovN.getOperand(2), CMovN.getOperand(3));
52571 
52572   // Finish extending if needed.
52573   if (ExtendVT != TargetVT)
52574     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
52575 
52576   return Res;
52577 }
52578 
52579 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
52580 // result type.
combineExtSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)52581 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
52582                                const X86Subtarget &Subtarget) {
52583   SDValue N0 = N->getOperand(0);
52584   EVT VT = N->getValueType(0);
52585   SDLoc dl(N);
52586 
52587   // Only do this combine with AVX512 for vector extends.
52588   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
52589     return SDValue();
52590 
52591   // Only combine legal element types.
52592   EVT SVT = VT.getVectorElementType();
52593   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
52594       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
52595     return SDValue();
52596 
52597   // We don't have CMPP Instruction for vxf16
52598   if (N0.getOperand(0).getValueType().getVectorElementType() == MVT::f16)
52599     return SDValue();
52600   // We can only do this if the vector size in 256 bits or less.
52601   unsigned Size = VT.getSizeInBits();
52602   if (Size > 256 && Subtarget.useAVX512Regs())
52603     return SDValue();
52604 
52605   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
52606   // that's the only integer compares with we have.
52607   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
52608   if (ISD::isUnsignedIntSetCC(CC))
52609     return SDValue();
52610 
52611   // Only do this combine if the extension will be fully consumed by the setcc.
52612   EVT N00VT = N0.getOperand(0).getValueType();
52613   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
52614   if (Size != MatchingVecType.getSizeInBits())
52615     return SDValue();
52616 
52617   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
52618 
52619   if (N->getOpcode() == ISD::ZERO_EXTEND)
52620     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
52621 
52622   return Res;
52623 }
52624 
combineSext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)52625 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
52626                            TargetLowering::DAGCombinerInfo &DCI,
52627                            const X86Subtarget &Subtarget) {
52628   SDValue N0 = N->getOperand(0);
52629   EVT VT = N->getValueType(0);
52630   SDLoc DL(N);
52631 
52632   // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
52633   if (!DCI.isBeforeLegalizeOps() &&
52634       N0.getOpcode() == X86ISD::SETCC_CARRY) {
52635     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
52636                                  N0->getOperand(1));
52637     bool ReplaceOtherUses = !N0.hasOneUse();
52638     DCI.CombineTo(N, Setcc);
52639     // Replace other uses with a truncate of the widened setcc_carry.
52640     if (ReplaceOtherUses) {
52641       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
52642                                   N0.getValueType(), Setcc);
52643       DCI.CombineTo(N0.getNode(), Trunc);
52644     }
52645 
52646     return SDValue(N, 0);
52647   }
52648 
52649   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
52650     return NewCMov;
52651 
52652   if (!DCI.isBeforeLegalizeOps())
52653     return SDValue();
52654 
52655   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
52656     return V;
52657 
52658   if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), DL, VT, N0,
52659                                                  DAG, DCI, Subtarget))
52660     return V;
52661 
52662   if (VT.isVector()) {
52663     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
52664       return R;
52665 
52666     if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
52667       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
52668   }
52669 
52670   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
52671     return NewAdd;
52672 
52673   return SDValue();
52674 }
52675 
52676 // Inverting a constant vector is profitable if it can be eliminated and the
52677 // inverted vector is already present in DAG. Otherwise, it will be loaded
52678 // anyway.
52679 //
52680 // We determine which of the values can be completely eliminated and invert it.
52681 // If both are eliminable, select a vector with the first negative element.
getInvertedVectorForFMA(SDValue V,SelectionDAG & DAG)52682 static SDValue getInvertedVectorForFMA(SDValue V, SelectionDAG &DAG) {
52683   assert(ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()) &&
52684          "ConstantFP build vector expected");
52685   // Check if we can eliminate V. We assume if a value is only used in FMAs, we
52686   // can eliminate it. Since this function is invoked for each FMA with this
52687   // vector.
52688   auto IsNotFMA = [](SDNode *Use) {
52689     return Use->getOpcode() != ISD::FMA && Use->getOpcode() != ISD::STRICT_FMA;
52690   };
52691   if (llvm::any_of(V->uses(), IsNotFMA))
52692     return SDValue();
52693 
52694   SmallVector<SDValue, 8> Ops;
52695   EVT VT = V.getValueType();
52696   EVT EltVT = VT.getVectorElementType();
52697   for (auto Op : V->op_values()) {
52698     if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
52699       Ops.push_back(DAG.getConstantFP(-Cst->getValueAPF(), SDLoc(Op), EltVT));
52700     } else {
52701       assert(Op.isUndef());
52702       Ops.push_back(DAG.getUNDEF(EltVT));
52703     }
52704   }
52705 
52706   SDNode *NV = DAG.getNodeIfExists(ISD::BUILD_VECTOR, DAG.getVTList(VT), Ops);
52707   if (!NV)
52708     return SDValue();
52709 
52710   // If an inverted version cannot be eliminated, choose it instead of the
52711   // original version.
52712   if (llvm::any_of(NV->uses(), IsNotFMA))
52713     return SDValue(NV, 0);
52714 
52715   // If the inverted version also can be eliminated, we have to consistently
52716   // prefer one of the values. We prefer a constant with a negative value on
52717   // the first place.
52718   // N.B. We need to skip undefs that may precede a value.
52719   for (auto op : V->op_values()) {
52720     if (auto *Cst = dyn_cast<ConstantFPSDNode>(op)) {
52721       if (Cst->isNegative())
52722         return SDValue();
52723       break;
52724     }
52725   }
52726   return SDValue(NV, 0);
52727 }
52728 
combineFMA(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)52729 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
52730                           TargetLowering::DAGCombinerInfo &DCI,
52731                           const X86Subtarget &Subtarget) {
52732   SDLoc dl(N);
52733   EVT VT = N->getValueType(0);
52734   bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
52735 
52736   // Let legalize expand this if it isn't a legal type yet.
52737   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52738   if (!TLI.isTypeLegal(VT))
52739     return SDValue();
52740 
52741   SDValue A = N->getOperand(IsStrict ? 1 : 0);
52742   SDValue B = N->getOperand(IsStrict ? 2 : 1);
52743   SDValue C = N->getOperand(IsStrict ? 3 : 2);
52744 
52745   // If the operation allows fast-math and the target does not support FMA,
52746   // split this into mul+add to avoid libcall(s).
52747   SDNodeFlags Flags = N->getFlags();
52748   if (!IsStrict && Flags.hasAllowReassociation() &&
52749       TLI.isOperationExpand(ISD::FMA, VT)) {
52750     SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
52751     return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
52752   }
52753 
52754   EVT ScalarVT = VT.getScalarType();
52755   if (((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
52756        !Subtarget.hasAnyFMA()) &&
52757       !(ScalarVT == MVT::f16 && Subtarget.hasFP16()))
52758     return SDValue();
52759 
52760   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
52761     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
52762     bool LegalOperations = !DCI.isBeforeLegalizeOps();
52763     if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
52764                                                        CodeSize)) {
52765       V = NegV;
52766       return true;
52767     }
52768     // Look through extract_vector_elts. If it comes from an FNEG, create a
52769     // new extract from the FNEG input.
52770     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
52771         isNullConstant(V.getOperand(1))) {
52772       SDValue Vec = V.getOperand(0);
52773       if (SDValue NegV = TLI.getCheaperNegatedExpression(
52774               Vec, DAG, LegalOperations, CodeSize)) {
52775         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
52776                         NegV, V.getOperand(1));
52777         return true;
52778       }
52779     }
52780     // Lookup if there is an inverted version of constant vector V in DAG.
52781     if (ISD::isBuildVectorOfConstantFPSDNodes(V.getNode())) {
52782       if (SDValue NegV = getInvertedVectorForFMA(V, DAG)) {
52783         V = NegV;
52784         return true;
52785       }
52786     }
52787     return false;
52788   };
52789 
52790   // Do not convert the passthru input of scalar intrinsics.
52791   // FIXME: We could allow negations of the lower element only.
52792   bool NegA = invertIfNegative(A);
52793   bool NegB = invertIfNegative(B);
52794   bool NegC = invertIfNegative(C);
52795 
52796   if (!NegA && !NegB && !NegC)
52797     return SDValue();
52798 
52799   unsigned NewOpcode =
52800       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
52801 
52802   // Propagate fast-math-flags to new FMA node.
52803   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
52804   if (IsStrict) {
52805     assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
52806     return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
52807                        {N->getOperand(0), A, B, C});
52808   } else {
52809     if (N->getNumOperands() == 4)
52810       return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
52811     return DAG.getNode(NewOpcode, dl, VT, A, B, C);
52812   }
52813 }
52814 
52815 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
52816 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
combineFMADDSUB(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)52817 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
52818                                TargetLowering::DAGCombinerInfo &DCI) {
52819   SDLoc dl(N);
52820   EVT VT = N->getValueType(0);
52821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52822   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
52823   bool LegalOperations = !DCI.isBeforeLegalizeOps();
52824 
52825   SDValue N2 = N->getOperand(2);
52826 
52827   SDValue NegN2 =
52828       TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
52829   if (!NegN2)
52830     return SDValue();
52831   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
52832 
52833   if (N->getNumOperands() == 4)
52834     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
52835                        NegN2, N->getOperand(3));
52836   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
52837                      NegN2);
52838 }
52839 
combineZext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)52840 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
52841                            TargetLowering::DAGCombinerInfo &DCI,
52842                            const X86Subtarget &Subtarget) {
52843   SDLoc dl(N);
52844   SDValue N0 = N->getOperand(0);
52845   EVT VT = N->getValueType(0);
52846 
52847   // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
52848   // FIXME: Is this needed? We don't seem to have any tests for it.
52849   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
52850       N0.getOpcode() == X86ISD::SETCC_CARRY) {
52851     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
52852                                  N0->getOperand(1));
52853     bool ReplaceOtherUses = !N0.hasOneUse();
52854     DCI.CombineTo(N, Setcc);
52855     // Replace other uses with a truncate of the widened setcc_carry.
52856     if (ReplaceOtherUses) {
52857       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
52858                                   N0.getValueType(), Setcc);
52859       DCI.CombineTo(N0.getNode(), Trunc);
52860     }
52861 
52862     return SDValue(N, 0);
52863   }
52864 
52865   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
52866     return NewCMov;
52867 
52868   if (DCI.isBeforeLegalizeOps())
52869     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
52870       return V;
52871 
52872   if (SDValue V = combineToExtendBoolVectorInReg(N->getOpcode(), dl, VT, N0,
52873                                                  DAG, DCI, Subtarget))
52874     return V;
52875 
52876   if (VT.isVector())
52877     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
52878       return R;
52879 
52880   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
52881     return NewAdd;
52882 
52883   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
52884     return R;
52885 
52886   // TODO: Combine with any target/faux shuffle.
52887   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
52888       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
52889     SDValue N00 = N0.getOperand(0);
52890     SDValue N01 = N0.getOperand(1);
52891     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
52892     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
52893     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
52894         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
52895       return concatSubVectors(N00, N01, DAG, dl);
52896     }
52897   }
52898 
52899   return SDValue();
52900 }
52901 
52902 /// If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
52903 /// pre-promote its result type since vXi1 vectors don't get promoted
52904 /// during type legalization.
truncateAVX512SetCCNoBWI(EVT VT,EVT OpVT,SDValue LHS,SDValue RHS,ISD::CondCode CC,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)52905 static SDValue truncateAVX512SetCCNoBWI(EVT VT, EVT OpVT, SDValue LHS,
52906                                         SDValue RHS, ISD::CondCode CC,
52907                                         const SDLoc &DL, SelectionDAG &DAG,
52908                                         const X86Subtarget &Subtarget) {
52909   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
52910       VT.getVectorElementType() == MVT::i1 &&
52911       (OpVT.getVectorElementType() == MVT::i8 ||
52912        OpVT.getVectorElementType() == MVT::i16)) {
52913     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
52914     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
52915   }
52916   return SDValue();
52917 }
52918 
combineSetCC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)52919 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
52920                             TargetLowering::DAGCombinerInfo &DCI,
52921                             const X86Subtarget &Subtarget) {
52922   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
52923   const SDValue LHS = N->getOperand(0);
52924   const SDValue RHS = N->getOperand(1);
52925   EVT VT = N->getValueType(0);
52926   EVT OpVT = LHS.getValueType();
52927   SDLoc DL(N);
52928 
52929   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
52930     if (SDValue V = combineVectorSizedSetCCEquality(VT, LHS, RHS, CC, DL, DAG,
52931                                                     Subtarget))
52932       return V;
52933 
52934     if (VT == MVT::i1) {
52935       X86::CondCode X86CC;
52936       if (SDValue V =
52937               MatchVectorAllEqualTest(LHS, RHS, CC, DL, Subtarget, DAG, X86CC))
52938         return DAG.getNode(ISD::TRUNCATE, DL, VT, getSETCC(X86CC, V, DL, DAG));
52939     }
52940 
52941     if (OpVT.isScalarInteger()) {
52942       // cmpeq(or(X,Y),X) --> cmpeq(and(~X,Y),0)
52943       // cmpne(or(X,Y),X) --> cmpne(and(~X,Y),0)
52944       auto MatchOrCmpEq = [&](SDValue N0, SDValue N1) {
52945         if (N0.getOpcode() == ISD::OR && N0->hasOneUse()) {
52946           if (N0.getOperand(0) == N1)
52947             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
52948                                N0.getOperand(1));
52949           if (N0.getOperand(1) == N1)
52950             return DAG.getNode(ISD::AND, DL, OpVT, DAG.getNOT(DL, N1, OpVT),
52951                                N0.getOperand(0));
52952         }
52953         return SDValue();
52954       };
52955       if (SDValue AndN = MatchOrCmpEq(LHS, RHS))
52956         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52957       if (SDValue AndN = MatchOrCmpEq(RHS, LHS))
52958         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52959 
52960       // cmpeq(and(X,Y),Y) --> cmpeq(and(~X,Y),0)
52961       // cmpne(and(X,Y),Y) --> cmpne(and(~X,Y),0)
52962       auto MatchAndCmpEq = [&](SDValue N0, SDValue N1) {
52963         if (N0.getOpcode() == ISD::AND && N0->hasOneUse()) {
52964           if (N0.getOperand(0) == N1)
52965             return DAG.getNode(ISD::AND, DL, OpVT, N1,
52966                                DAG.getNOT(DL, N0.getOperand(1), OpVT));
52967           if (N0.getOperand(1) == N1)
52968             return DAG.getNode(ISD::AND, DL, OpVT, N1,
52969                                DAG.getNOT(DL, N0.getOperand(0), OpVT));
52970         }
52971         return SDValue();
52972       };
52973       if (SDValue AndN = MatchAndCmpEq(LHS, RHS))
52974         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52975       if (SDValue AndN = MatchAndCmpEq(RHS, LHS))
52976         return DAG.getSetCC(DL, VT, AndN, DAG.getConstant(0, DL, OpVT), CC);
52977 
52978       // cmpeq(trunc(x),C) --> cmpeq(x,C)
52979       // cmpne(trunc(x),C) --> cmpne(x,C)
52980       // iff x upper bits are zero.
52981       if (LHS.getOpcode() == ISD::TRUNCATE &&
52982           LHS.getOperand(0).getScalarValueSizeInBits() >= 32 &&
52983           isa<ConstantSDNode>(RHS) && !DCI.isBeforeLegalize()) {
52984         EVT SrcVT = LHS.getOperand(0).getValueType();
52985         APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
52986                                                 OpVT.getScalarSizeInBits());
52987         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
52988         auto *C = cast<ConstantSDNode>(RHS);
52989         if (DAG.MaskedValueIsZero(LHS.getOperand(0), UpperBits) &&
52990             TLI.isTypeLegal(LHS.getOperand(0).getValueType()))
52991           return DAG.getSetCC(DL, VT, LHS.getOperand(0),
52992                               DAG.getConstant(C->getAPIntValue().zextOrTrunc(
52993                                                   SrcVT.getScalarSizeInBits()),
52994                                               DL, SrcVT),
52995                               CC);
52996       }
52997 
52998       // With C as a power of 2 and C != 0 and C != INT_MIN:
52999       //    icmp eq Abs(X) C ->
53000       //        (icmp eq A, C) | (icmp eq A, -C)
53001       //    icmp ne Abs(X) C ->
53002       //        (icmp ne A, C) & (icmp ne A, -C)
53003       // Both of these patterns can be better optimized in
53004       // DAGCombiner::foldAndOrOfSETCC. Note this only applies for scalar
53005       // integers which is checked above.
53006       if (LHS.getOpcode() == ISD::ABS && LHS.hasOneUse()) {
53007         if (auto *C = dyn_cast<ConstantSDNode>(RHS)) {
53008           const APInt &CInt = C->getAPIntValue();
53009           // We can better optimize this case in DAGCombiner::foldAndOrOfSETCC.
53010           if (CInt.isPowerOf2() && !CInt.isMinSignedValue()) {
53011             SDValue BaseOp = LHS.getOperand(0);
53012             SDValue SETCC0 = DAG.getSetCC(DL, VT, BaseOp, RHS, CC);
53013             SDValue SETCC1 = DAG.getSetCC(
53014                 DL, VT, BaseOp, DAG.getConstant(-CInt, DL, OpVT), CC);
53015             return DAG.getNode(CC == ISD::SETEQ ? ISD::OR : ISD::AND, DL, VT,
53016                                SETCC0, SETCC1);
53017           }
53018         }
53019       }
53020     }
53021   }
53022 
53023   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
53024       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
53025     // Using temporaries to avoid messing up operand ordering for later
53026     // transformations if this doesn't work.
53027     SDValue Op0 = LHS;
53028     SDValue Op1 = RHS;
53029     ISD::CondCode TmpCC = CC;
53030     // Put build_vector on the right.
53031     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
53032       std::swap(Op0, Op1);
53033       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
53034     }
53035 
53036     bool IsSEXT0 =
53037         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
53038         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
53039     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
53040 
53041     if (IsSEXT0 && IsVZero1) {
53042       assert(VT == Op0.getOperand(0).getValueType() &&
53043              "Unexpected operand type");
53044       if (TmpCC == ISD::SETGT)
53045         return DAG.getConstant(0, DL, VT);
53046       if (TmpCC == ISD::SETLE)
53047         return DAG.getConstant(1, DL, VT);
53048       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
53049         return DAG.getNOT(DL, Op0.getOperand(0), VT);
53050 
53051       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
53052              "Unexpected condition code!");
53053       return Op0.getOperand(0);
53054     }
53055   }
53056 
53057   // Try and make unsigned vector comparison signed. On pre AVX512 targets there
53058   // only are unsigned comparisons (`PCMPGT`) and on AVX512 its often better to
53059   // use `PCMPGT` if the result is mean to stay in a vector (and if its going to
53060   // a mask, there are signed AVX512 comparisons).
53061   if (VT.isVector() && OpVT.isVector() && OpVT.isInteger()) {
53062     bool CanMakeSigned = false;
53063     if (ISD::isUnsignedIntSetCC(CC)) {
53064       KnownBits CmpKnown =
53065           DAG.computeKnownBits(LHS).intersectWith(DAG.computeKnownBits(RHS));
53066       // If we know LHS/RHS share the same sign bit at each element we can
53067       // make this signed.
53068       // NOTE: `computeKnownBits` on a vector type aggregates common bits
53069       // across all lanes. So a pattern where the sign varies from lane to
53070       // lane, but at each lane Sign(LHS) is known to equal Sign(RHS), will be
53071       // missed. We could get around this by demanding each lane
53072       // independently, but this isn't the most important optimization and
53073       // that may eat into compile time.
53074       CanMakeSigned =
53075           CmpKnown.Zero.isSignBitSet() || CmpKnown.One.isSignBitSet();
53076     }
53077     if (CanMakeSigned || ISD::isSignedIntSetCC(CC)) {
53078       SDValue LHSOut = LHS;
53079       SDValue RHSOut = RHS;
53080       ISD::CondCode NewCC = CC;
53081       switch (CC) {
53082       case ISD::SETGE:
53083       case ISD::SETUGE:
53084         if (SDValue NewLHS = incDecVectorConstant(LHS, DAG, /*IsInc*/ true,
53085                                                   /*NSW*/ true))
53086           LHSOut = NewLHS;
53087         else if (SDValue NewRHS = incDecVectorConstant(
53088                      RHS, DAG, /*IsInc*/ false, /*NSW*/ true))
53089           RHSOut = NewRHS;
53090         else
53091           break;
53092 
53093         [[fallthrough]];
53094       case ISD::SETUGT:
53095         NewCC = ISD::SETGT;
53096         break;
53097 
53098       case ISD::SETLE:
53099       case ISD::SETULE:
53100         if (SDValue NewLHS = incDecVectorConstant(LHS, DAG, /*IsInc*/ false,
53101                                                   /*NSW*/ true))
53102           LHSOut = NewLHS;
53103         else if (SDValue NewRHS = incDecVectorConstant(RHS, DAG, /*IsInc*/ true,
53104                                                        /*NSW*/ true))
53105           RHSOut = NewRHS;
53106         else
53107           break;
53108 
53109         [[fallthrough]];
53110       case ISD::SETULT:
53111         // Will be swapped to SETGT in LowerVSETCC*.
53112         NewCC = ISD::SETLT;
53113         break;
53114       default:
53115         break;
53116       }
53117       if (NewCC != CC) {
53118         if (SDValue R = truncateAVX512SetCCNoBWI(VT, OpVT, LHSOut, RHSOut,
53119                                                  NewCC, DL, DAG, Subtarget))
53120           return R;
53121         return DAG.getSetCC(DL, VT, LHSOut, RHSOut, NewCC);
53122       }
53123     }
53124   }
53125 
53126   if (SDValue R =
53127           truncateAVX512SetCCNoBWI(VT, OpVT, LHS, RHS, CC, DL, DAG, Subtarget))
53128     return R;
53129 
53130   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
53131   // to avoid scalarization via legalization because v4i32 is not a legal type.
53132   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
53133       LHS.getValueType() == MVT::v4f32)
53134     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
53135 
53136   // X pred 0.0 --> X pred -X
53137   // If the negation of X already exists, use it in the comparison. This removes
53138   // the need to materialize 0.0 and allows matching to SSE's MIN/MAX
53139   // instructions in patterns with a 'select' node.
53140   if (isNullFPScalarOrVectorConst(RHS)) {
53141     SDVTList FNegVT = DAG.getVTList(OpVT);
53142     if (SDNode *FNeg = DAG.getNodeIfExists(ISD::FNEG, FNegVT, {LHS}))
53143       return DAG.getSetCC(DL, VT, LHS, SDValue(FNeg, 0), CC);
53144   }
53145 
53146   return SDValue();
53147 }
53148 
combineMOVMSK(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)53149 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
53150                              TargetLowering::DAGCombinerInfo &DCI,
53151                              const X86Subtarget &Subtarget) {
53152   SDValue Src = N->getOperand(0);
53153   MVT SrcVT = Src.getSimpleValueType();
53154   MVT VT = N->getSimpleValueType(0);
53155   unsigned NumBits = VT.getScalarSizeInBits();
53156   unsigned NumElts = SrcVT.getVectorNumElements();
53157   unsigned NumBitsPerElt = SrcVT.getScalarSizeInBits();
53158   assert(VT == MVT::i32 && NumElts <= NumBits && "Unexpected MOVMSK types");
53159 
53160   // Perform constant folding.
53161   APInt UndefElts;
53162   SmallVector<APInt, 32> EltBits;
53163   if (getTargetConstantBitsFromNode(Src, NumBitsPerElt, UndefElts, EltBits)) {
53164     APInt Imm(32, 0);
53165     for (unsigned Idx = 0; Idx != NumElts; ++Idx)
53166       if (!UndefElts[Idx] && EltBits[Idx].isNegative())
53167         Imm.setBit(Idx);
53168 
53169     return DAG.getConstant(Imm, SDLoc(N), VT);
53170   }
53171 
53172   // Look through int->fp bitcasts that don't change the element width.
53173   unsigned EltWidth = SrcVT.getScalarSizeInBits();
53174   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
53175       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
53176     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
53177 
53178   // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
53179   // with scalar comparisons.
53180   if (SDValue NotSrc = IsNOT(Src, DAG)) {
53181     SDLoc DL(N);
53182     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
53183     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
53184     return DAG.getNode(ISD::XOR, DL, VT,
53185                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
53186                        DAG.getConstant(NotMask, DL, VT));
53187   }
53188 
53189   // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
53190   // results with scalar comparisons.
53191   if (Src.getOpcode() == X86ISD::PCMPGT &&
53192       ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
53193     SDLoc DL(N);
53194     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
53195     return DAG.getNode(ISD::XOR, DL, VT,
53196                        DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
53197                        DAG.getConstant(NotMask, DL, VT));
53198   }
53199 
53200   // Fold movmsk(icmp_eq(and(x,c1),c1)) -> movmsk(shl(x,c2))
53201   // Fold movmsk(icmp_eq(and(x,c1),0)) -> movmsk(not(shl(x,c2)))
53202   // iff pow2splat(c1).
53203   // Use KnownBits to determine if only a single bit is non-zero
53204   // in each element (pow2 or zero), and shift that bit to the msb.
53205   if (Src.getOpcode() == X86ISD::PCMPEQ) {
53206     KnownBits KnownLHS = DAG.computeKnownBits(Src.getOperand(0));
53207     KnownBits KnownRHS = DAG.computeKnownBits(Src.getOperand(1));
53208     unsigned ShiftAmt = KnownLHS.countMinLeadingZeros();
53209     if (KnownLHS.countMaxPopulation() == 1 &&
53210         (KnownRHS.isZero() || (KnownRHS.countMaxPopulation() == 1 &&
53211                                ShiftAmt == KnownRHS.countMinLeadingZeros()))) {
53212       SDLoc DL(N);
53213       MVT ShiftVT = SrcVT;
53214       SDValue ShiftLHS = Src.getOperand(0);
53215       SDValue ShiftRHS = Src.getOperand(1);
53216       if (ShiftVT.getScalarType() == MVT::i8) {
53217         // vXi8 shifts - we only care about the signbit so can use PSLLW.
53218         ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
53219         ShiftLHS = DAG.getBitcast(ShiftVT, ShiftLHS);
53220         ShiftRHS = DAG.getBitcast(ShiftVT, ShiftRHS);
53221       }
53222       ShiftLHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT,
53223                                             ShiftLHS, ShiftAmt, DAG);
53224       ShiftRHS = getTargetVShiftByConstNode(X86ISD::VSHLI, DL, ShiftVT,
53225                                             ShiftRHS, ShiftAmt, DAG);
53226       ShiftLHS = DAG.getBitcast(SrcVT, ShiftLHS);
53227       ShiftRHS = DAG.getBitcast(SrcVT, ShiftRHS);
53228       SDValue Res = DAG.getNode(ISD::XOR, DL, SrcVT, ShiftLHS, ShiftRHS);
53229       return DAG.getNode(X86ISD::MOVMSK, DL, VT, DAG.getNOT(DL, Res, SrcVT));
53230     }
53231   }
53232 
53233   // Fold movmsk(logic(X,C)) -> logic(movmsk(X),C)
53234   if (N->isOnlyUserOf(Src.getNode())) {
53235     SDValue SrcBC = peekThroughOneUseBitcasts(Src);
53236     if (ISD::isBitwiseLogicOp(SrcBC.getOpcode())) {
53237       APInt UndefElts;
53238       SmallVector<APInt, 32> EltBits;
53239       if (getTargetConstantBitsFromNode(SrcBC.getOperand(1), NumBitsPerElt,
53240                                         UndefElts, EltBits)) {
53241         APInt Mask = APInt::getZero(NumBits);
53242         for (unsigned Idx = 0; Idx != NumElts; ++Idx) {
53243           if (!UndefElts[Idx] && EltBits[Idx].isNegative())
53244             Mask.setBit(Idx);
53245         }
53246         SDLoc DL(N);
53247         SDValue NewSrc = DAG.getBitcast(SrcVT, SrcBC.getOperand(0));
53248         SDValue NewMovMsk = DAG.getNode(X86ISD::MOVMSK, DL, VT, NewSrc);
53249         return DAG.getNode(SrcBC.getOpcode(), DL, VT, NewMovMsk,
53250                            DAG.getConstant(Mask, DL, VT));
53251       }
53252     }
53253   }
53254 
53255   // Simplify the inputs.
53256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53257   APInt DemandedMask(APInt::getAllOnes(NumBits));
53258   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
53259     return SDValue(N, 0);
53260 
53261   return SDValue();
53262 }
53263 
combineTESTP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)53264 static SDValue combineTESTP(SDNode *N, SelectionDAG &DAG,
53265                             TargetLowering::DAGCombinerInfo &DCI,
53266                             const X86Subtarget &Subtarget) {
53267   MVT VT = N->getSimpleValueType(0);
53268   unsigned NumBits = VT.getScalarSizeInBits();
53269 
53270   // Simplify the inputs.
53271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53272   APInt DemandedMask(APInt::getAllOnes(NumBits));
53273   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
53274     return SDValue(N, 0);
53275 
53276   return SDValue();
53277 }
53278 
combineX86GatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)53279 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
53280                                        TargetLowering::DAGCombinerInfo &DCI) {
53281   auto *MemOp = cast<X86MaskedGatherScatterSDNode>(N);
53282   SDValue Mask = MemOp->getMask();
53283 
53284   // With vector masks we only demand the upper bit of the mask.
53285   if (Mask.getScalarValueSizeInBits() != 1) {
53286     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53287     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
53288     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
53289       if (N->getOpcode() != ISD::DELETED_NODE)
53290         DCI.AddToWorklist(N);
53291       return SDValue(N, 0);
53292     }
53293   }
53294 
53295   return SDValue();
53296 }
53297 
rebuildGatherScatter(MaskedGatherScatterSDNode * GorS,SDValue Index,SDValue Base,SDValue Scale,SelectionDAG & DAG)53298 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
53299                                     SDValue Index, SDValue Base, SDValue Scale,
53300                                     SelectionDAG &DAG) {
53301   SDLoc DL(GorS);
53302 
53303   if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
53304     SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
53305                       Gather->getMask(), Base, Index, Scale } ;
53306     return DAG.getMaskedGather(Gather->getVTList(),
53307                                Gather->getMemoryVT(), DL, Ops,
53308                                Gather->getMemOperand(),
53309                                Gather->getIndexType(),
53310                                Gather->getExtensionType());
53311   }
53312   auto *Scatter = cast<MaskedScatterSDNode>(GorS);
53313   SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
53314                     Scatter->getMask(), Base, Index, Scale };
53315   return DAG.getMaskedScatter(Scatter->getVTList(),
53316                               Scatter->getMemoryVT(), DL,
53317                               Ops, Scatter->getMemOperand(),
53318                               Scatter->getIndexType(),
53319                               Scatter->isTruncatingStore());
53320 }
53321 
combineGatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)53322 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
53323                                     TargetLowering::DAGCombinerInfo &DCI) {
53324   SDLoc DL(N);
53325   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
53326   SDValue Index = GorS->getIndex();
53327   SDValue Base = GorS->getBasePtr();
53328   SDValue Scale = GorS->getScale();
53329 
53330   if (DCI.isBeforeLegalize()) {
53331     unsigned IndexWidth = Index.getScalarValueSizeInBits();
53332 
53333     // Shrink constant indices if they are larger than 32-bits.
53334     // Only do this before legalize types since v2i64 could become v2i32.
53335     // FIXME: We could check that the type is legal if we're after legalize
53336     // types, but then we would need to construct test cases where that happens.
53337     // FIXME: We could support more than just constant vectors, but we need to
53338     // careful with costing. A truncate that can be optimized out would be fine.
53339     // Otherwise we might only want to create a truncate if it avoids a split.
53340     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
53341       if (BV->isConstant() && IndexWidth > 32 &&
53342           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
53343         EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
53344         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
53345         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
53346       }
53347     }
53348 
53349     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
53350     // there are sufficient sign bits. Only do this before legalize types to
53351     // avoid creating illegal types in truncate.
53352     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
53353          Index.getOpcode() == ISD::ZERO_EXTEND) &&
53354         IndexWidth > 32 &&
53355         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
53356         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
53357       EVT NewVT = Index.getValueType().changeVectorElementType(MVT::i32);
53358       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
53359       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
53360     }
53361   }
53362 
53363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53364   EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
53365   // Try to move splat constant adders from the index operand to the base
53366   // pointer operand. Taking care to multiply by the scale. We can only do
53367   // this when index element type is the same as the pointer type.
53368   // Otherwise we need to be sure the math doesn't wrap before the scale.
53369   if (Index.getOpcode() == ISD::ADD &&
53370       Index.getValueType().getVectorElementType() == PtrVT &&
53371       isa<ConstantSDNode>(Scale)) {
53372     uint64_t ScaleAmt = Scale->getAsZExtVal();
53373     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index.getOperand(1))) {
53374       BitVector UndefElts;
53375       if (ConstantSDNode *C = BV->getConstantSplatNode(&UndefElts)) {
53376         // FIXME: Allow non-constant?
53377         if (UndefElts.none()) {
53378           // Apply the scale.
53379           APInt Adder = C->getAPIntValue() * ScaleAmt;
53380           // Add it to the existing base.
53381           Base = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
53382                              DAG.getConstant(Adder, DL, PtrVT));
53383           Index = Index.getOperand(0);
53384           return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
53385         }
53386       }
53387 
53388       // It's also possible base is just a constant. In that case, just
53389       // replace it with 0 and move the displacement into the index.
53390       if (BV->isConstant() && isa<ConstantSDNode>(Base) &&
53391           isOneConstant(Scale)) {
53392         SDValue Splat = DAG.getSplatBuildVector(Index.getValueType(), DL, Base);
53393         // Combine the constant build_vector and the constant base.
53394         Splat = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
53395                             Index.getOperand(1), Splat);
53396         // Add to the LHS of the original Index add.
53397         Index = DAG.getNode(ISD::ADD, DL, Index.getValueType(),
53398                             Index.getOperand(0), Splat);
53399         Base = DAG.getConstant(0, DL, Base.getValueType());
53400         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
53401       }
53402     }
53403   }
53404 
53405   if (DCI.isBeforeLegalizeOps()) {
53406     unsigned IndexWidth = Index.getScalarValueSizeInBits();
53407 
53408     // Make sure the index is either i32 or i64
53409     if (IndexWidth != 32 && IndexWidth != 64) {
53410       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
53411       EVT IndexVT = Index.getValueType().changeVectorElementType(EltVT);
53412       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
53413       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
53414     }
53415   }
53416 
53417   // With vector masks we only demand the upper bit of the mask.
53418   SDValue Mask = GorS->getMask();
53419   if (Mask.getScalarValueSizeInBits() != 1) {
53420     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53421     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
53422     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
53423       if (N->getOpcode() != ISD::DELETED_NODE)
53424         DCI.AddToWorklist(N);
53425       return SDValue(N, 0);
53426     }
53427   }
53428 
53429   return SDValue();
53430 }
53431 
53432 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
combineX86SetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)53433 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
53434                                const X86Subtarget &Subtarget) {
53435   SDLoc DL(N);
53436   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
53437   SDValue EFLAGS = N->getOperand(1);
53438 
53439   // Try to simplify the EFLAGS and condition code operands.
53440   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
53441     return getSETCC(CC, Flags, DL, DAG);
53442 
53443   return SDValue();
53444 }
53445 
53446 /// Optimize branch condition evaluation.
combineBrCond(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)53447 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
53448                              const X86Subtarget &Subtarget) {
53449   SDLoc DL(N);
53450   SDValue EFLAGS = N->getOperand(3);
53451   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
53452 
53453   // Try to simplify the EFLAGS and condition code operands.
53454   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
53455   // RAUW them under us.
53456   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
53457     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
53458     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
53459                        N->getOperand(1), Cond, Flags);
53460   }
53461 
53462   return SDValue();
53463 }
53464 
53465 // TODO: Could we move this to DAGCombine?
combineVectorCompareAndMaskUnaryOp(SDNode * N,SelectionDAG & DAG)53466 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
53467                                                   SelectionDAG &DAG) {
53468   // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
53469   // to optimize away operation when it's from a constant.
53470   //
53471   // The general transformation is:
53472   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
53473   //       AND(VECTOR_CMP(x,y), constant2)
53474   //    constant2 = UNARYOP(constant)
53475 
53476   // Early exit if this isn't a vector operation, the operand of the
53477   // unary operation isn't a bitwise AND, or if the sizes of the operations
53478   // aren't the same.
53479   EVT VT = N->getValueType(0);
53480   bool IsStrict = N->isStrictFPOpcode();
53481   unsigned NumEltBits = VT.getScalarSizeInBits();
53482   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
53483   if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
53484       DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
53485       VT.getSizeInBits() != Op0.getValueSizeInBits())
53486     return SDValue();
53487 
53488   // Now check that the other operand of the AND is a constant. We could
53489   // make the transformation for non-constant splats as well, but it's unclear
53490   // that would be a benefit as it would not eliminate any operations, just
53491   // perform one more step in scalar code before moving to the vector unit.
53492   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
53493     // Bail out if the vector isn't a constant.
53494     if (!BV->isConstant())
53495       return SDValue();
53496 
53497     // Everything checks out. Build up the new and improved node.
53498     SDLoc DL(N);
53499     EVT IntVT = BV->getValueType(0);
53500     // Create a new constant of the appropriate type for the transformed
53501     // DAG.
53502     SDValue SourceConst;
53503     if (IsStrict)
53504       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
53505                                 {N->getOperand(0), SDValue(BV, 0)});
53506     else
53507       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
53508     // The AND node needs bitcasts to/from an integer vector type around it.
53509     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
53510     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
53511                                  MaskConst);
53512     SDValue Res = DAG.getBitcast(VT, NewAnd);
53513     if (IsStrict)
53514       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
53515     return Res;
53516   }
53517 
53518   return SDValue();
53519 }
53520 
53521 /// If we are converting a value to floating-point, try to replace scalar
53522 /// truncate of an extracted vector element with a bitcast. This tries to keep
53523 /// the sequence on XMM registers rather than moving between vector and GPRs.
combineToFPTruncExtElt(SDNode * N,SelectionDAG & DAG)53524 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
53525   // TODO: This is currently only used by combineSIntToFP, but it is generalized
53526   //       to allow being called by any similar cast opcode.
53527   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
53528   SDValue Trunc = N->getOperand(0);
53529   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
53530     return SDValue();
53531 
53532   SDValue ExtElt = Trunc.getOperand(0);
53533   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
53534       !isNullConstant(ExtElt.getOperand(1)))
53535     return SDValue();
53536 
53537   EVT TruncVT = Trunc.getValueType();
53538   EVT SrcVT = ExtElt.getValueType();
53539   unsigned DestWidth = TruncVT.getSizeInBits();
53540   unsigned SrcWidth = SrcVT.getSizeInBits();
53541   if (SrcWidth % DestWidth != 0)
53542     return SDValue();
53543 
53544   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
53545   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
53546   unsigned VecWidth = SrcVecVT.getSizeInBits();
53547   unsigned NumElts = VecWidth / DestWidth;
53548   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
53549   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
53550   SDLoc DL(N);
53551   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
53552                                   BitcastVec, ExtElt.getOperand(1));
53553   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
53554 }
53555 
combineUIntToFP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)53556 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
53557                                const X86Subtarget &Subtarget) {
53558   bool IsStrict = N->isStrictFPOpcode();
53559   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
53560   EVT VT = N->getValueType(0);
53561   EVT InVT = Op0.getValueType();
53562 
53563   // Using i16 as an intermediate type is a bad idea, unless we have HW support
53564   // for it. Therefore for type sizes equal or smaller than 32 just go with i32.
53565   // if hasFP16 support:
53566   //   UINT_TO_FP(vXi1~15)  -> SINT_TO_FP(ZEXT(vXi1~15  to vXi16))
53567   //   UINT_TO_FP(vXi17~31) -> SINT_TO_FP(ZEXT(vXi17~31 to vXi32))
53568   // else
53569   //   UINT_TO_FP(vXi1~31) -> SINT_TO_FP(ZEXT(vXi1~31 to vXi32))
53570   // UINT_TO_FP(vXi33~63) -> SINT_TO_FP(ZEXT(vXi33~63 to vXi64))
53571   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
53572     unsigned ScalarSize = InVT.getScalarSizeInBits();
53573     if ((ScalarSize == 16 && Subtarget.hasFP16()) || ScalarSize == 32 ||
53574         ScalarSize >= 64)
53575       return SDValue();
53576     SDLoc dl(N);
53577     EVT DstVT =
53578         EVT::getVectorVT(*DAG.getContext(),
53579                          (Subtarget.hasFP16() && ScalarSize < 16) ? MVT::i16
53580                          : ScalarSize < 32                        ? MVT::i32
53581                                                                   : MVT::i64,
53582                          InVT.getVectorNumElements());
53583     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
53584     if (IsStrict)
53585       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
53586                          {N->getOperand(0), P});
53587     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
53588   }
53589 
53590   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
53591   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
53592   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
53593   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
53594       VT.getScalarType() != MVT::f16) {
53595     SDLoc dl(N);
53596     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
53597     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
53598 
53599     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
53600     if (IsStrict)
53601       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
53602                          {N->getOperand(0), P});
53603     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
53604   }
53605 
53606   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
53607   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
53608   // the optimization here.
53609   if (DAG.SignBitIsZero(Op0)) {
53610     if (IsStrict)
53611       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
53612                          {N->getOperand(0), Op0});
53613     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
53614   }
53615 
53616   return SDValue();
53617 }
53618 
combineSIntToFP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)53619 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
53620                                TargetLowering::DAGCombinerInfo &DCI,
53621                                const X86Subtarget &Subtarget) {
53622   // First try to optimize away the conversion entirely when it's
53623   // conditionally from a constant. Vectors only.
53624   bool IsStrict = N->isStrictFPOpcode();
53625   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
53626     return Res;
53627 
53628   // Now move on to more general possibilities.
53629   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
53630   EVT VT = N->getValueType(0);
53631   EVT InVT = Op0.getValueType();
53632 
53633   // Using i16 as an intermediate type is a bad idea, unless we have HW support
53634   // for it. Therefore for type sizes equal or smaller than 32 just go with i32.
53635   // if hasFP16 support:
53636   //   SINT_TO_FP(vXi1~15)  -> SINT_TO_FP(SEXT(vXi1~15  to vXi16))
53637   //   SINT_TO_FP(vXi17~31) -> SINT_TO_FP(SEXT(vXi17~31 to vXi32))
53638   // else
53639   //   SINT_TO_FP(vXi1~31) -> SINT_TO_FP(ZEXT(vXi1~31 to vXi32))
53640   // SINT_TO_FP(vXi33~63) -> SINT_TO_FP(SEXT(vXi33~63 to vXi64))
53641   if (InVT.isVector() && VT.getVectorElementType() == MVT::f16) {
53642     unsigned ScalarSize = InVT.getScalarSizeInBits();
53643     if ((ScalarSize == 16 && Subtarget.hasFP16()) || ScalarSize == 32 ||
53644         ScalarSize >= 64)
53645       return SDValue();
53646     SDLoc dl(N);
53647     EVT DstVT =
53648         EVT::getVectorVT(*DAG.getContext(),
53649                          (Subtarget.hasFP16() && ScalarSize < 16) ? MVT::i16
53650                          : ScalarSize < 32                        ? MVT::i32
53651                                                                   : MVT::i64,
53652                          InVT.getVectorNumElements());
53653     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
53654     if (IsStrict)
53655       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
53656                          {N->getOperand(0), P});
53657     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
53658   }
53659 
53660   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
53661   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
53662   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
53663   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32 &&
53664       VT.getScalarType() != MVT::f16) {
53665     SDLoc dl(N);
53666     EVT DstVT = InVT.changeVectorElementType(MVT::i32);
53667     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
53668     if (IsStrict)
53669       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
53670                          {N->getOperand(0), P});
53671     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
53672   }
53673 
53674   // Without AVX512DQ we only support i64 to float scalar conversion. For both
53675   // vectors and scalars, see if we know that the upper bits are all the sign
53676   // bit, in which case we can truncate the input to i32 and convert from that.
53677   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
53678     unsigned BitWidth = InVT.getScalarSizeInBits();
53679     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
53680     if (NumSignBits >= (BitWidth - 31)) {
53681       EVT TruncVT = MVT::i32;
53682       if (InVT.isVector())
53683         TruncVT = InVT.changeVectorElementType(TruncVT);
53684       SDLoc dl(N);
53685       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
53686         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
53687         if (IsStrict)
53688           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
53689                              {N->getOperand(0), Trunc});
53690         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
53691       }
53692       // If we're after legalize and the type is v2i32 we need to shuffle and
53693       // use CVTSI2P.
53694       assert(InVT == MVT::v2i64 && "Unexpected VT!");
53695       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
53696       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
53697                                           { 0, 2, -1, -1 });
53698       if (IsStrict)
53699         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
53700                            {N->getOperand(0), Shuf});
53701       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
53702     }
53703   }
53704 
53705   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
53706   // a 32-bit target where SSE doesn't support i64->FP operations.
53707   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
53708       Op0.getOpcode() == ISD::LOAD) {
53709     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
53710 
53711     // This transformation is not supported if the result type is f16 or f128.
53712     if (VT == MVT::f16 || VT == MVT::f128)
53713       return SDValue();
53714 
53715     // If we have AVX512DQ we can use packed conversion instructions unless
53716     // the VT is f80.
53717     if (Subtarget.hasDQI() && VT != MVT::f80)
53718       return SDValue();
53719 
53720     if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
53721         Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
53722       std::pair<SDValue, SDValue> Tmp =
53723           Subtarget.getTargetLowering()->BuildFILD(
53724               VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
53725               Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
53726       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
53727       return Tmp.first;
53728     }
53729   }
53730 
53731   if (IsStrict)
53732     return SDValue();
53733 
53734   if (SDValue V = combineToFPTruncExtElt(N, DAG))
53735     return V;
53736 
53737   return SDValue();
53738 }
53739 
needCarryOrOverflowFlag(SDValue Flags)53740 static bool needCarryOrOverflowFlag(SDValue Flags) {
53741   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
53742 
53743   for (const SDNode *User : Flags->uses()) {
53744     X86::CondCode CC;
53745     switch (User->getOpcode()) {
53746     default:
53747       // Be conservative.
53748       return true;
53749     case X86ISD::SETCC:
53750     case X86ISD::SETCC_CARRY:
53751       CC = (X86::CondCode)User->getConstantOperandVal(0);
53752       break;
53753     case X86ISD::BRCOND:
53754     case X86ISD::CMOV:
53755       CC = (X86::CondCode)User->getConstantOperandVal(2);
53756       break;
53757     }
53758 
53759     switch (CC) {
53760     default: break;
53761     case X86::COND_A: case X86::COND_AE:
53762     case X86::COND_B: case X86::COND_BE:
53763     case X86::COND_O: case X86::COND_NO:
53764     case X86::COND_G: case X86::COND_GE:
53765     case X86::COND_L: case X86::COND_LE:
53766       return true;
53767     }
53768   }
53769 
53770   return false;
53771 }
53772 
onlyZeroFlagUsed(SDValue Flags)53773 static bool onlyZeroFlagUsed(SDValue Flags) {
53774   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
53775 
53776   for (const SDNode *User : Flags->uses()) {
53777     unsigned CCOpNo;
53778     switch (User->getOpcode()) {
53779     default:
53780       // Be conservative.
53781       return false;
53782     case X86ISD::SETCC:
53783     case X86ISD::SETCC_CARRY:
53784       CCOpNo = 0;
53785       break;
53786     case X86ISD::BRCOND:
53787     case X86ISD::CMOV:
53788       CCOpNo = 2;
53789       break;
53790     }
53791 
53792     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
53793     if (CC != X86::COND_E && CC != X86::COND_NE)
53794       return false;
53795   }
53796 
53797   return true;
53798 }
53799 
combineCMP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)53800 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG,
53801                           const X86Subtarget &Subtarget) {
53802   // Only handle test patterns.
53803   if (!isNullConstant(N->getOperand(1)))
53804     return SDValue();
53805 
53806   // If we have a CMP of a truncated binop, see if we can make a smaller binop
53807   // and use its flags directly.
53808   // TODO: Maybe we should try promoting compares that only use the zero flag
53809   // first if we can prove the upper bits with computeKnownBits?
53810   SDLoc dl(N);
53811   SDValue Op = N->getOperand(0);
53812   EVT VT = Op.getValueType();
53813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
53814 
53815   // If we have a constant logical shift that's only used in a comparison
53816   // against zero turn it into an equivalent AND. This allows turning it into
53817   // a TEST instruction later.
53818   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
53819       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
53820       onlyZeroFlagUsed(SDValue(N, 0))) {
53821     unsigned BitWidth = VT.getSizeInBits();
53822     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
53823     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
53824       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
53825       APInt Mask = Op.getOpcode() == ISD::SRL
53826                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
53827                        : APInt::getLowBitsSet(BitWidth, MaskBits);
53828       if (Mask.isSignedIntN(32)) {
53829         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
53830                          DAG.getConstant(Mask, dl, VT));
53831         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53832                            DAG.getConstant(0, dl, VT));
53833       }
53834     }
53835   }
53836 
53837   // If we're extracting from a avx512 bool vector and comparing against zero,
53838   // then try to just bitcast the vector to an integer to use TEST/BT directly.
53839   // (and (extract_elt (kshiftr vXi1, C), 0), 1) -> (and (bc vXi1), 1<<C)
53840   if (Op.getOpcode() == ISD::AND && isOneConstant(Op.getOperand(1)) &&
53841       Op.hasOneUse() && onlyZeroFlagUsed(SDValue(N, 0))) {
53842     SDValue Src = Op.getOperand(0);
53843     if (Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
53844         isNullConstant(Src.getOperand(1)) &&
53845         Src.getOperand(0).getValueType().getScalarType() == MVT::i1) {
53846       SDValue BoolVec = Src.getOperand(0);
53847       unsigned ShAmt = 0;
53848       if (BoolVec.getOpcode() == X86ISD::KSHIFTR) {
53849         ShAmt = BoolVec.getConstantOperandVal(1);
53850         BoolVec = BoolVec.getOperand(0);
53851       }
53852       BoolVec = widenMaskVector(BoolVec, false, Subtarget, DAG, dl);
53853       EVT VecVT = BoolVec.getValueType();
53854       unsigned BitWidth = VecVT.getVectorNumElements();
53855       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), BitWidth);
53856       if (TLI.isTypeLegal(VecVT) && TLI.isTypeLegal(BCVT)) {
53857         APInt Mask = APInt::getOneBitSet(BitWidth, ShAmt);
53858         Op = DAG.getBitcast(BCVT, BoolVec);
53859         Op = DAG.getNode(ISD::AND, dl, BCVT, Op,
53860                          DAG.getConstant(Mask, dl, BCVT));
53861         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53862                            DAG.getConstant(0, dl, BCVT));
53863       }
53864     }
53865   }
53866 
53867   // Peek through any zero-extend if we're only testing for a zero result.
53868   if (Op.getOpcode() == ISD::ZERO_EXTEND && onlyZeroFlagUsed(SDValue(N, 0))) {
53869     SDValue Src = Op.getOperand(0);
53870     EVT SrcVT = Src.getValueType();
53871     if (SrcVT.getScalarSizeInBits() >= 8 && TLI.isTypeLegal(SrcVT))
53872       return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Src,
53873                          DAG.getConstant(0, dl, SrcVT));
53874   }
53875 
53876   // Look for a truncate.
53877   if (Op.getOpcode() != ISD::TRUNCATE)
53878     return SDValue();
53879 
53880   SDValue Trunc = Op;
53881   Op = Op.getOperand(0);
53882 
53883   // See if we can compare with zero against the truncation source,
53884   // which should help using the Z flag from many ops. Only do this for
53885   // i32 truncated op to prevent partial-reg compares of promoted ops.
53886   EVT OpVT = Op.getValueType();
53887   APInt UpperBits =
53888       APInt::getBitsSetFrom(OpVT.getSizeInBits(), VT.getSizeInBits());
53889   if (OpVT == MVT::i32 && DAG.MaskedValueIsZero(Op, UpperBits) &&
53890       onlyZeroFlagUsed(SDValue(N, 0))) {
53891     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53892                        DAG.getConstant(0, dl, OpVT));
53893   }
53894 
53895   // After this the truncate and arithmetic op must have a single use.
53896   if (!Trunc.hasOneUse() || !Op.hasOneUse())
53897       return SDValue();
53898 
53899   unsigned NewOpc;
53900   switch (Op.getOpcode()) {
53901   default: return SDValue();
53902   case ISD::AND:
53903     // Skip and with constant. We have special handling for and with immediate
53904     // during isel to generate test instructions.
53905     if (isa<ConstantSDNode>(Op.getOperand(1)))
53906       return SDValue();
53907     NewOpc = X86ISD::AND;
53908     break;
53909   case ISD::OR:  NewOpc = X86ISD::OR;  break;
53910   case ISD::XOR: NewOpc = X86ISD::XOR; break;
53911   case ISD::ADD:
53912     // If the carry or overflow flag is used, we can't truncate.
53913     if (needCarryOrOverflowFlag(SDValue(N, 0)))
53914       return SDValue();
53915     NewOpc = X86ISD::ADD;
53916     break;
53917   case ISD::SUB:
53918     // If the carry or overflow flag is used, we can't truncate.
53919     if (needCarryOrOverflowFlag(SDValue(N, 0)))
53920       return SDValue();
53921     NewOpc = X86ISD::SUB;
53922     break;
53923   }
53924 
53925   // We found an op we can narrow. Truncate its inputs.
53926   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
53927   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
53928 
53929   // Use a X86 specific opcode to avoid DAG combine messing with it.
53930   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
53931   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
53932 
53933   // For AND, keep a CMP so that we can match the test pattern.
53934   if (NewOpc == X86ISD::AND)
53935     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
53936                        DAG.getConstant(0, dl, VT));
53937 
53938   // Return the flags.
53939   return Op.getValue(1);
53940 }
53941 
combineX86AddSub(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)53942 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
53943                                 TargetLowering::DAGCombinerInfo &DCI) {
53944   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
53945          "Expected X86ISD::ADD or X86ISD::SUB");
53946 
53947   SDLoc DL(N);
53948   SDValue LHS = N->getOperand(0);
53949   SDValue RHS = N->getOperand(1);
53950   MVT VT = LHS.getSimpleValueType();
53951   bool IsSub = X86ISD::SUB == N->getOpcode();
53952   unsigned GenericOpc = IsSub ? ISD::SUB : ISD::ADD;
53953 
53954   // If we don't use the flag result, simplify back to a generic ADD/SUB.
53955   if (!N->hasAnyUseOfValue(1)) {
53956     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
53957     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
53958   }
53959 
53960   // Fold any similar generic ADD/SUB opcodes to reuse this node.
53961   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
53962     SDValue Ops[] = {N0, N1};
53963     SDVTList VTs = DAG.getVTList(N->getValueType(0));
53964     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
53965       SDValue Op(N, 0);
53966       if (Negate)
53967         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
53968       DCI.CombineTo(GenericAddSub, Op);
53969     }
53970   };
53971   MatchGeneric(LHS, RHS, false);
53972   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
53973 
53974   // TODO: Can we drop the ZeroSecondOpOnly limit? This is to guarantee that the
53975   // EFLAGS result doesn't change.
53976   return combineAddOrSubToADCOrSBB(IsSub, DL, VT, LHS, RHS, DAG,
53977                                    /*ZeroSecondOpOnly*/ true);
53978 }
53979 
combineSBB(SDNode * N,SelectionDAG & DAG)53980 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
53981   SDValue LHS = N->getOperand(0);
53982   SDValue RHS = N->getOperand(1);
53983   SDValue BorrowIn = N->getOperand(2);
53984 
53985   if (SDValue Flags = combineCarryThroughADD(BorrowIn, DAG)) {
53986     MVT VT = N->getSimpleValueType(0);
53987     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
53988     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs, LHS, RHS, Flags);
53989   }
53990 
53991   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
53992   // iff the flag result is dead.
53993   if (LHS.getOpcode() == ISD::SUB && isNullConstant(RHS) &&
53994       !N->hasAnyUseOfValue(1))
53995     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), LHS.getOperand(0),
53996                        LHS.getOperand(1), BorrowIn);
53997 
53998   return SDValue();
53999 }
54000 
54001 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
combineADC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)54002 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
54003                           TargetLowering::DAGCombinerInfo &DCI) {
54004   SDValue LHS = N->getOperand(0);
54005   SDValue RHS = N->getOperand(1);
54006   SDValue CarryIn = N->getOperand(2);
54007   auto *LHSC = dyn_cast<ConstantSDNode>(LHS);
54008   auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
54009 
54010   // Canonicalize constant to RHS.
54011   if (LHSC && !RHSC)
54012     return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), RHS, LHS,
54013                        CarryIn);
54014 
54015   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
54016   // the result is either zero or one (depending on the input carry bit).
54017   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
54018   if (LHSC && RHSC && LHSC->isZero() && RHSC->isZero() &&
54019       // We don't have a good way to replace an EFLAGS use, so only do this when
54020       // dead right now.
54021       SDValue(N, 1).use_empty()) {
54022     SDLoc DL(N);
54023     EVT VT = N->getValueType(0);
54024     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
54025     SDValue Res1 = DAG.getNode(
54026         ISD::AND, DL, VT,
54027         DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
54028                     DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), CarryIn),
54029         DAG.getConstant(1, DL, VT));
54030     return DCI.CombineTo(N, Res1, CarryOut);
54031   }
54032 
54033   // Fold ADC(C1,C2,Carry) -> ADC(0,C1+C2,Carry)
54034   // iff the flag result is dead.
54035   // TODO: Allow flag result if C1+C2 doesn't signed/unsigned overflow.
54036   if (LHSC && RHSC && !LHSC->isZero() && !N->hasAnyUseOfValue(1)) {
54037     SDLoc DL(N);
54038     APInt Sum = LHSC->getAPIntValue() + RHSC->getAPIntValue();
54039     return DAG.getNode(X86ISD::ADC, DL, N->getVTList(),
54040                        DAG.getConstant(0, DL, LHS.getValueType()),
54041                        DAG.getConstant(Sum, DL, LHS.getValueType()), CarryIn);
54042   }
54043 
54044   if (SDValue Flags = combineCarryThroughADD(CarryIn, DAG)) {
54045     MVT VT = N->getSimpleValueType(0);
54046     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
54047     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs, LHS, RHS, Flags);
54048   }
54049 
54050   // Fold ADC(ADD(X,Y),0,Carry) -> ADC(X,Y,Carry)
54051   // iff the flag result is dead.
54052   if (LHS.getOpcode() == ISD::ADD && RHSC && RHSC->isZero() &&
54053       !N->hasAnyUseOfValue(1))
54054     return DAG.getNode(X86ISD::ADC, SDLoc(N), N->getVTList(), LHS.getOperand(0),
54055                        LHS.getOperand(1), CarryIn);
54056 
54057   return SDValue();
54058 }
54059 
matchPMADDWD(SelectionDAG & DAG,SDValue Op0,SDValue Op1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)54060 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
54061                             const SDLoc &DL, EVT VT,
54062                             const X86Subtarget &Subtarget) {
54063   // Example of pattern we try to detect:
54064   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
54065   //(add (build_vector (extract_elt t, 0),
54066   //                   (extract_elt t, 2),
54067   //                   (extract_elt t, 4),
54068   //                   (extract_elt t, 6)),
54069   //     (build_vector (extract_elt t, 1),
54070   //                   (extract_elt t, 3),
54071   //                   (extract_elt t, 5),
54072   //                   (extract_elt t, 7)))
54073 
54074   if (!Subtarget.hasSSE2())
54075     return SDValue();
54076 
54077   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
54078       Op1.getOpcode() != ISD::BUILD_VECTOR)
54079     return SDValue();
54080 
54081   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
54082       VT.getVectorNumElements() < 4 ||
54083       !isPowerOf2_32(VT.getVectorNumElements()))
54084     return SDValue();
54085 
54086   // Check if one of Op0,Op1 is of the form:
54087   // (build_vector (extract_elt Mul, 0),
54088   //               (extract_elt Mul, 2),
54089   //               (extract_elt Mul, 4),
54090   //                   ...
54091   // the other is of the form:
54092   // (build_vector (extract_elt Mul, 1),
54093   //               (extract_elt Mul, 3),
54094   //               (extract_elt Mul, 5),
54095   //                   ...
54096   // and identify Mul.
54097   SDValue Mul;
54098   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
54099     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
54100             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
54101     // TODO: Be more tolerant to undefs.
54102     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
54103         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
54104         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
54105         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
54106       return SDValue();
54107     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
54108     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
54109     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
54110     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
54111     if (!Const0L || !Const1L || !Const0H || !Const1H)
54112       return SDValue();
54113     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
54114              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
54115     // Commutativity of mul allows factors of a product to reorder.
54116     if (Idx0L > Idx1L)
54117       std::swap(Idx0L, Idx1L);
54118     if (Idx0H > Idx1H)
54119       std::swap(Idx0H, Idx1H);
54120     // Commutativity of add allows pairs of factors to reorder.
54121     if (Idx0L > Idx0H) {
54122       std::swap(Idx0L, Idx0H);
54123       std::swap(Idx1L, Idx1H);
54124     }
54125     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
54126         Idx1H != 2 * i + 3)
54127       return SDValue();
54128     if (!Mul) {
54129       // First time an extract_elt's source vector is visited. Must be a MUL
54130       // with 2X number of vector elements than the BUILD_VECTOR.
54131       // Both extracts must be from same MUL.
54132       Mul = Op0L->getOperand(0);
54133       if (Mul->getOpcode() != ISD::MUL ||
54134           Mul.getValueType().getVectorNumElements() != 2 * e)
54135         return SDValue();
54136     }
54137     // Check that the extract is from the same MUL previously seen.
54138     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
54139         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
54140       return SDValue();
54141   }
54142 
54143   // Check if the Mul source can be safely shrunk.
54144   ShrinkMode Mode;
54145   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
54146       Mode == ShrinkMode::MULU16)
54147     return SDValue();
54148 
54149   EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
54150                                  VT.getVectorNumElements() * 2);
54151   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
54152   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
54153 
54154   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
54155                          ArrayRef<SDValue> Ops) {
54156     EVT InVT = Ops[0].getValueType();
54157     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
54158     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
54159                                  InVT.getVectorNumElements() / 2);
54160     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
54161   };
54162   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
54163 }
54164 
54165 // Attempt to turn this pattern into PMADDWD.
54166 // (add (mul (sext (build_vector)), (sext (build_vector))),
54167 //      (mul (sext (build_vector)), (sext (build_vector)))
matchPMADDWD_2(SelectionDAG & DAG,SDValue N0,SDValue N1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)54168 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
54169                               const SDLoc &DL, EVT VT,
54170                               const X86Subtarget &Subtarget) {
54171   if (!Subtarget.hasSSE2())
54172     return SDValue();
54173 
54174   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
54175     return SDValue();
54176 
54177   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
54178       VT.getVectorNumElements() < 4 ||
54179       !isPowerOf2_32(VT.getVectorNumElements()))
54180     return SDValue();
54181 
54182   SDValue N00 = N0.getOperand(0);
54183   SDValue N01 = N0.getOperand(1);
54184   SDValue N10 = N1.getOperand(0);
54185   SDValue N11 = N1.getOperand(1);
54186 
54187   // All inputs need to be sign extends.
54188   // TODO: Support ZERO_EXTEND from known positive?
54189   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
54190       N01.getOpcode() != ISD::SIGN_EXTEND ||
54191       N10.getOpcode() != ISD::SIGN_EXTEND ||
54192       N11.getOpcode() != ISD::SIGN_EXTEND)
54193     return SDValue();
54194 
54195   // Peek through the extends.
54196   N00 = N00.getOperand(0);
54197   N01 = N01.getOperand(0);
54198   N10 = N10.getOperand(0);
54199   N11 = N11.getOperand(0);
54200 
54201   // Must be extending from vXi16.
54202   EVT InVT = N00.getValueType();
54203   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
54204       N10.getValueType() != InVT || N11.getValueType() != InVT)
54205     return SDValue();
54206 
54207   // All inputs should be build_vectors.
54208   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
54209       N01.getOpcode() != ISD::BUILD_VECTOR ||
54210       N10.getOpcode() != ISD::BUILD_VECTOR ||
54211       N11.getOpcode() != ISD::BUILD_VECTOR)
54212     return SDValue();
54213 
54214   // For each element, we need to ensure we have an odd element from one vector
54215   // multiplied by the odd element of another vector and the even element from
54216   // one of the same vectors being multiplied by the even element from the
54217   // other vector. So we need to make sure for each element i, this operator
54218   // is being performed:
54219   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
54220   SDValue In0, In1;
54221   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
54222     SDValue N00Elt = N00.getOperand(i);
54223     SDValue N01Elt = N01.getOperand(i);
54224     SDValue N10Elt = N10.getOperand(i);
54225     SDValue N11Elt = N11.getOperand(i);
54226     // TODO: Be more tolerant to undefs.
54227     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
54228         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
54229         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
54230         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
54231       return SDValue();
54232     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
54233     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
54234     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
54235     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
54236     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
54237       return SDValue();
54238     unsigned IdxN00 = ConstN00Elt->getZExtValue();
54239     unsigned IdxN01 = ConstN01Elt->getZExtValue();
54240     unsigned IdxN10 = ConstN10Elt->getZExtValue();
54241     unsigned IdxN11 = ConstN11Elt->getZExtValue();
54242     // Add is commutative so indices can be reordered.
54243     if (IdxN00 > IdxN10) {
54244       std::swap(IdxN00, IdxN10);
54245       std::swap(IdxN01, IdxN11);
54246     }
54247     // N0 indices be the even element. N1 indices must be the next odd element.
54248     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
54249         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
54250       return SDValue();
54251     SDValue N00In = N00Elt.getOperand(0);
54252     SDValue N01In = N01Elt.getOperand(0);
54253     SDValue N10In = N10Elt.getOperand(0);
54254     SDValue N11In = N11Elt.getOperand(0);
54255 
54256     // First time we find an input capture it.
54257     if (!In0) {
54258       In0 = N00In;
54259       In1 = N01In;
54260 
54261       // The input vectors must be at least as wide as the output.
54262       // If they are larger than the output, we extract subvector below.
54263       if (In0.getValueSizeInBits() < VT.getSizeInBits() ||
54264           In1.getValueSizeInBits() < VT.getSizeInBits())
54265         return SDValue();
54266     }
54267     // Mul is commutative so the input vectors can be in any order.
54268     // Canonicalize to make the compares easier.
54269     if (In0 != N00In)
54270       std::swap(N00In, N01In);
54271     if (In0 != N10In)
54272       std::swap(N10In, N11In);
54273     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
54274       return SDValue();
54275   }
54276 
54277   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
54278                          ArrayRef<SDValue> Ops) {
54279     EVT OpVT = Ops[0].getValueType();
54280     assert(OpVT.getScalarType() == MVT::i16 &&
54281            "Unexpected scalar element type");
54282     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
54283     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
54284                                  OpVT.getVectorNumElements() / 2);
54285     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
54286   };
54287 
54288   // If the output is narrower than an input, extract the low part of the input
54289   // vector.
54290   EVT OutVT16 = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
54291                                VT.getVectorNumElements() * 2);
54292   if (OutVT16.bitsLT(In0.getValueType())) {
54293     In0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In0,
54294                       DAG.getIntPtrConstant(0, DL));
54295   }
54296   if (OutVT16.bitsLT(In1.getValueType())) {
54297     In1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT16, In1,
54298                       DAG.getIntPtrConstant(0, DL));
54299   }
54300   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
54301                           PMADDBuilder);
54302 }
54303 
54304 // ADD(VPMADDWD(X,Y),VPMADDWD(Z,W)) -> VPMADDWD(SHUFFLE(X,Z), SHUFFLE(Y,W))
54305 // If upper element in each pair of both VPMADDWD are zero then we can merge
54306 // the operand elements and use the implicit add of VPMADDWD.
54307 // TODO: Add support for VPMADDUBSW (which isn't commutable).
combineAddOfPMADDWD(SelectionDAG & DAG,SDValue N0,SDValue N1,const SDLoc & DL,EVT VT)54308 static SDValue combineAddOfPMADDWD(SelectionDAG &DAG, SDValue N0, SDValue N1,
54309                                    const SDLoc &DL, EVT VT) {
54310   if (N0.getOpcode() != N1.getOpcode() || N0.getOpcode() != X86ISD::VPMADDWD)
54311     return SDValue();
54312 
54313   // TODO: Add 256/512-bit support once VPMADDWD combines with shuffles.
54314   if (VT.getSizeInBits() > 128)
54315     return SDValue();
54316 
54317   unsigned NumElts = VT.getVectorNumElements();
54318   MVT OpVT = N0.getOperand(0).getSimpleValueType();
54319   APInt DemandedBits = APInt::getAllOnes(OpVT.getScalarSizeInBits());
54320   APInt DemandedHiElts = APInt::getSplat(2 * NumElts, APInt(2, 2));
54321 
54322   bool Op0HiZero =
54323       DAG.MaskedValueIsZero(N0.getOperand(0), DemandedBits, DemandedHiElts) ||
54324       DAG.MaskedValueIsZero(N0.getOperand(1), DemandedBits, DemandedHiElts);
54325   bool Op1HiZero =
54326       DAG.MaskedValueIsZero(N1.getOperand(0), DemandedBits, DemandedHiElts) ||
54327       DAG.MaskedValueIsZero(N1.getOperand(1), DemandedBits, DemandedHiElts);
54328 
54329   // TODO: Check for zero lower elements once we have actual codegen that
54330   // creates them.
54331   if (!Op0HiZero || !Op1HiZero)
54332     return SDValue();
54333 
54334   // Create a shuffle mask packing the lower elements from each VPMADDWD.
54335   SmallVector<int> Mask;
54336   for (int i = 0; i != (int)NumElts; ++i) {
54337     Mask.push_back(2 * i);
54338     Mask.push_back(2 * (i + NumElts));
54339   }
54340 
54341   SDValue LHS =
54342       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(0), N1.getOperand(0), Mask);
54343   SDValue RHS =
54344       DAG.getVectorShuffle(OpVT, DL, N0.getOperand(1), N1.getOperand(1), Mask);
54345   return DAG.getNode(X86ISD::VPMADDWD, DL, VT, LHS, RHS);
54346 }
54347 
54348 /// CMOV of constants requires materializing constant operands in registers.
54349 /// Try to fold those constants into an 'add' instruction to reduce instruction
54350 /// count. We do this with CMOV rather the generic 'select' because there are
54351 /// earlier folds that may be used to turn select-of-constants into logic hacks.
pushAddIntoCmovOfConsts(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)54352 static SDValue pushAddIntoCmovOfConsts(SDNode *N, SelectionDAG &DAG,
54353                                        const X86Subtarget &Subtarget) {
54354   // If an operand is zero, add-of-0 gets simplified away, so that's clearly
54355   // better because we eliminate 1-2 instructions. This transform is still
54356   // an improvement without zero operands because we trade 2 move constants and
54357   // 1 add for 2 adds (LEA) as long as the constants can be represented as
54358   // immediate asm operands (fit in 32-bits).
54359   auto isSuitableCmov = [](SDValue V) {
54360     if (V.getOpcode() != X86ISD::CMOV || !V.hasOneUse())
54361       return false;
54362     if (!isa<ConstantSDNode>(V.getOperand(0)) ||
54363         !isa<ConstantSDNode>(V.getOperand(1)))
54364       return false;
54365     return isNullConstant(V.getOperand(0)) || isNullConstant(V.getOperand(1)) ||
54366            (V.getConstantOperandAPInt(0).isSignedIntN(32) &&
54367             V.getConstantOperandAPInt(1).isSignedIntN(32));
54368   };
54369 
54370   // Match an appropriate CMOV as the first operand of the add.
54371   SDValue Cmov = N->getOperand(0);
54372   SDValue OtherOp = N->getOperand(1);
54373   if (!isSuitableCmov(Cmov))
54374     std::swap(Cmov, OtherOp);
54375   if (!isSuitableCmov(Cmov))
54376     return SDValue();
54377 
54378   // Don't remove a load folding opportunity for the add. That would neutralize
54379   // any improvements from removing constant materializations.
54380   if (X86::mayFoldLoad(OtherOp, Subtarget))
54381     return SDValue();
54382 
54383   EVT VT = N->getValueType(0);
54384   SDLoc DL(N);
54385   SDValue FalseOp = Cmov.getOperand(0);
54386   SDValue TrueOp = Cmov.getOperand(1);
54387 
54388   // We will push the add through the select, but we can potentially do better
54389   // if we know there is another add in the sequence and this is pointer math.
54390   // In that case, we can absorb an add into the trailing memory op and avoid
54391   // a 3-operand LEA which is likely slower than a 2-operand LEA.
54392   // TODO: If target has "slow3OpsLEA", do this even without the trailing memop?
54393   if (OtherOp.getOpcode() == ISD::ADD && OtherOp.hasOneUse() &&
54394       !isa<ConstantSDNode>(OtherOp.getOperand(0)) &&
54395       all_of(N->uses(), [&](SDNode *Use) {
54396         auto *MemNode = dyn_cast<MemSDNode>(Use);
54397         return MemNode && MemNode->getBasePtr().getNode() == N;
54398       })) {
54399     // add (cmov C1, C2), add (X, Y) --> add (cmov (add X, C1), (add X, C2)), Y
54400     // TODO: We are arbitrarily choosing op0 as the 1st piece of the sum, but
54401     //       it is possible that choosing op1 might be better.
54402     SDValue X = OtherOp.getOperand(0), Y = OtherOp.getOperand(1);
54403     FalseOp = DAG.getNode(ISD::ADD, DL, VT, X, FalseOp);
54404     TrueOp = DAG.getNode(ISD::ADD, DL, VT, X, TrueOp);
54405     Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp,
54406                        Cmov.getOperand(2), Cmov.getOperand(3));
54407     return DAG.getNode(ISD::ADD, DL, VT, Cmov, Y);
54408   }
54409 
54410   // add (cmov C1, C2), OtherOp --> cmov (add OtherOp, C1), (add OtherOp, C2)
54411   FalseOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, FalseOp);
54412   TrueOp = DAG.getNode(ISD::ADD, DL, VT, OtherOp, TrueOp);
54413   return DAG.getNode(X86ISD::CMOV, DL, VT, FalseOp, TrueOp, Cmov.getOperand(2),
54414                      Cmov.getOperand(3));
54415 }
54416 
combineAdd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)54417 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
54418                           TargetLowering::DAGCombinerInfo &DCI,
54419                           const X86Subtarget &Subtarget) {
54420   EVT VT = N->getValueType(0);
54421   SDValue Op0 = N->getOperand(0);
54422   SDValue Op1 = N->getOperand(1);
54423   SDLoc DL(N);
54424 
54425   if (SDValue Select = pushAddIntoCmovOfConsts(N, DAG, Subtarget))
54426     return Select;
54427 
54428   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, DL, VT, Subtarget))
54429     return MAdd;
54430   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, DL, VT, Subtarget))
54431     return MAdd;
54432   if (SDValue MAdd = combineAddOfPMADDWD(DAG, Op0, Op1, DL, VT))
54433     return MAdd;
54434 
54435   // Try to synthesize horizontal adds from adds of shuffles.
54436   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
54437     return V;
54438 
54439   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
54440   // (sub Y, (sext (vXi1 X))).
54441   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
54442   // generic DAG combine without a legal type check, but adding this there
54443   // caused regressions.
54444   if (VT.isVector()) {
54445     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54446     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
54447         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
54448         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
54449       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
54450       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
54451     }
54452 
54453     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
54454         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
54455         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
54456       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
54457       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
54458     }
54459   }
54460 
54461   // Fold ADD(ADC(Y,0,W),X) -> ADC(X,Y,W)
54462   if (Op0.getOpcode() == X86ISD::ADC && Op0->hasOneUse() &&
54463       X86::isZeroNode(Op0.getOperand(1))) {
54464     assert(!Op0->hasAnyUseOfValue(1) && "Overflow bit in use");
54465     return DAG.getNode(X86ISD::ADC, SDLoc(Op0), Op0->getVTList(), Op1,
54466                        Op0.getOperand(0), Op0.getOperand(2));
54467   }
54468 
54469   return combineAddOrSubToADCOrSBB(N, DAG);
54470 }
54471 
54472 // Try to fold (sub Y, cmovns X, -X) -> (add Y, cmovns -X, X) if the cmov
54473 // condition comes from the subtract node that produced -X. This matches the
54474 // cmov expansion for absolute value. By swapping the operands we convert abs
54475 // to nabs.
combineSubABS(SDNode * N,SelectionDAG & DAG)54476 static SDValue combineSubABS(SDNode *N, SelectionDAG &DAG) {
54477   SDValue N0 = N->getOperand(0);
54478   SDValue N1 = N->getOperand(1);
54479 
54480   if (N1.getOpcode() != X86ISD::CMOV || !N1.hasOneUse())
54481     return SDValue();
54482 
54483   X86::CondCode CC = (X86::CondCode)N1.getConstantOperandVal(2);
54484   if (CC != X86::COND_S && CC != X86::COND_NS)
54485     return SDValue();
54486 
54487   // Condition should come from a negate operation.
54488   SDValue Cond = N1.getOperand(3);
54489   if (Cond.getOpcode() != X86ISD::SUB || !isNullConstant(Cond.getOperand(0)))
54490     return SDValue();
54491   assert(Cond.getResNo() == 1 && "Unexpected result number");
54492 
54493   // Get the X and -X from the negate.
54494   SDValue NegX = Cond.getValue(0);
54495   SDValue X = Cond.getOperand(1);
54496 
54497   SDValue FalseOp = N1.getOperand(0);
54498   SDValue TrueOp = N1.getOperand(1);
54499 
54500   // Cmov operands should be X and NegX. Order doesn't matter.
54501   if (!(TrueOp == X && FalseOp == NegX) && !(TrueOp == NegX && FalseOp == X))
54502     return SDValue();
54503 
54504   // Build a new CMOV with the operands swapped.
54505   SDLoc DL(N);
54506   MVT VT = N->getSimpleValueType(0);
54507   SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VT, TrueOp, FalseOp,
54508                              N1.getOperand(2), Cond);
54509   // Convert sub to add.
54510   return DAG.getNode(ISD::ADD, DL, VT, N0, Cmov);
54511 }
54512 
combineSubSetcc(SDNode * N,SelectionDAG & DAG)54513 static SDValue combineSubSetcc(SDNode *N, SelectionDAG &DAG) {
54514   SDValue Op0 = N->getOperand(0);
54515   SDValue Op1 = N->getOperand(1);
54516 
54517   // (sub C (zero_extend (setcc)))
54518   // =>
54519   // (add (zero_extend (setcc inverted) C-1))   if C is a nonzero immediate
54520   // Don't disturb (sub 0 setcc), which is easily done with neg.
54521   EVT VT = N->getValueType(0);
54522   auto *Op0C = dyn_cast<ConstantSDNode>(Op0);
54523   if (Op1.getOpcode() == ISD::ZERO_EXTEND && Op1.hasOneUse() && Op0C &&
54524       !Op0C->isZero() && Op1.getOperand(0).getOpcode() == X86ISD::SETCC &&
54525       Op1.getOperand(0).hasOneUse()) {
54526     SDValue SetCC = Op1.getOperand(0);
54527     X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
54528     X86::CondCode NewCC = X86::GetOppositeBranchCondition(CC);
54529     APInt NewImm = Op0C->getAPIntValue() - 1;
54530     SDLoc DL(Op1);
54531     SDValue NewSetCC = getSETCC(NewCC, SetCC.getOperand(1), DL, DAG);
54532     NewSetCC = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NewSetCC);
54533     return DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(VT, VT), NewSetCC,
54534                        DAG.getConstant(NewImm, DL, VT));
54535   }
54536 
54537   return SDValue();
54538 }
54539 
combineSub(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)54540 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
54541                           TargetLowering::DAGCombinerInfo &DCI,
54542                           const X86Subtarget &Subtarget) {
54543   SDValue Op0 = N->getOperand(0);
54544   SDValue Op1 = N->getOperand(1);
54545 
54546   // TODO: Add NoOpaque handling to isConstantIntBuildVectorOrConstantInt.
54547   auto IsNonOpaqueConstant = [&](SDValue Op) {
54548     if (SDNode *C = DAG.isConstantIntBuildVectorOrConstantInt(Op)) {
54549       if (auto *Cst = dyn_cast<ConstantSDNode>(C))
54550         return !Cst->isOpaque();
54551       return true;
54552     }
54553     return false;
54554   };
54555 
54556   // X86 can't encode an immediate LHS of a sub. See if we can push the
54557   // negation into a preceding instruction. If the RHS of the sub is a XOR with
54558   // one use and a constant, invert the immediate, saving one register.
54559   // However, ignore cases where C1 is 0, as those will become a NEG.
54560   // sub(C1, xor(X, C2)) -> add(xor(X, ~C2), C1+1)
54561   if (Op1.getOpcode() == ISD::XOR && IsNonOpaqueConstant(Op0) &&
54562       !isNullConstant(Op0) && IsNonOpaqueConstant(Op1.getOperand(1)) &&
54563       Op1->hasOneUse()) {
54564     SDLoc DL(N);
54565     EVT VT = Op0.getValueType();
54566     SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT, Op1.getOperand(0),
54567                                  DAG.getNOT(SDLoc(Op1), Op1.getOperand(1), VT));
54568     SDValue NewAdd =
54569         DAG.getNode(ISD::ADD, DL, VT, Op0, DAG.getConstant(1, DL, VT));
54570     return DAG.getNode(ISD::ADD, DL, VT, NewXor, NewAdd);
54571   }
54572 
54573   if (SDValue V = combineSubABS(N, DAG))
54574     return V;
54575 
54576   // Try to synthesize horizontal subs from subs of shuffles.
54577   if (SDValue V = combineToHorizontalAddSub(N, DAG, Subtarget))
54578     return V;
54579 
54580   // Fold SUB(X,ADC(Y,0,W)) -> SBB(X,Y,W)
54581   if (Op1.getOpcode() == X86ISD::ADC && Op1->hasOneUse() &&
54582       X86::isZeroNode(Op1.getOperand(1))) {
54583     assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
54584     return DAG.getNode(X86ISD::SBB, SDLoc(Op1), Op1->getVTList(), Op0,
54585                        Op1.getOperand(0), Op1.getOperand(2));
54586   }
54587 
54588   // Fold SUB(X,SBB(Y,Z,W)) -> SUB(ADC(X,Z,W),Y)
54589   // Don't fold to ADC(0,0,W)/SETCC_CARRY pattern which will prevent more folds.
54590   if (Op1.getOpcode() == X86ISD::SBB && Op1->hasOneUse() &&
54591       !(X86::isZeroNode(Op0) && X86::isZeroNode(Op1.getOperand(1)))) {
54592     assert(!Op1->hasAnyUseOfValue(1) && "Overflow bit in use");
54593     SDValue ADC = DAG.getNode(X86ISD::ADC, SDLoc(Op1), Op1->getVTList(), Op0,
54594                               Op1.getOperand(1), Op1.getOperand(2));
54595     return DAG.getNode(ISD::SUB, SDLoc(N), Op0.getValueType(), ADC.getValue(0),
54596                        Op1.getOperand(0));
54597   }
54598 
54599   if (SDValue V = combineXorSubCTLZ(N, DAG, Subtarget))
54600     return V;
54601 
54602   if (SDValue V = combineAddOrSubToADCOrSBB(N, DAG))
54603     return V;
54604 
54605   return combineSubSetcc(N, DAG);
54606 }
54607 
combineVectorCompare(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)54608 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
54609                                     const X86Subtarget &Subtarget) {
54610   MVT VT = N->getSimpleValueType(0);
54611   SDLoc DL(N);
54612 
54613   if (N->getOperand(0) == N->getOperand(1)) {
54614     if (N->getOpcode() == X86ISD::PCMPEQ)
54615       return DAG.getConstant(-1, DL, VT);
54616     if (N->getOpcode() == X86ISD::PCMPGT)
54617       return DAG.getConstant(0, DL, VT);
54618   }
54619 
54620   return SDValue();
54621 }
54622 
54623 /// Helper that combines an array of subvector ops as if they were the operands
54624 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
54625 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
combineConcatVectorOps(const SDLoc & DL,MVT VT,ArrayRef<SDValue> Ops,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)54626 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
54627                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
54628                                       TargetLowering::DAGCombinerInfo &DCI,
54629                                       const X86Subtarget &Subtarget) {
54630   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
54631   unsigned EltSizeInBits = VT.getScalarSizeInBits();
54632 
54633   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
54634     return DAG.getUNDEF(VT);
54635 
54636   if (llvm::all_of(Ops, [](SDValue Op) {
54637         return ISD::isBuildVectorAllZeros(Op.getNode());
54638       }))
54639     return getZeroVector(VT, Subtarget, DAG, DL);
54640 
54641   SDValue Op0 = Ops[0];
54642   bool IsSplat = llvm::all_equal(Ops);
54643   unsigned NumOps = Ops.size();
54644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
54645   LLVMContext &Ctx = *DAG.getContext();
54646 
54647   // Repeated subvectors.
54648   if (IsSplat &&
54649       (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
54650     // If this broadcast is inserted into both halves, use a larger broadcast.
54651     if (Op0.getOpcode() == X86ISD::VBROADCAST)
54652       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
54653 
54654     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
54655     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
54656         (Subtarget.hasAVX2() ||
54657          X86::mayFoldLoadIntoBroadcastFromMem(Op0.getOperand(0),
54658                                               VT.getScalarType(), Subtarget)))
54659       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
54660                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
54661                                      Op0.getOperand(0),
54662                                      DAG.getIntPtrConstant(0, DL)));
54663 
54664     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
54665     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
54666         (Subtarget.hasAVX2() ||
54667          (EltSizeInBits >= 32 &&
54668           X86::mayFoldLoad(Op0.getOperand(0), Subtarget))) &&
54669         Op0.getOperand(0).getValueType() == VT.getScalarType())
54670       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
54671 
54672     // concat_vectors(extract_subvector(broadcast(x)),
54673     //                extract_subvector(broadcast(x))) -> broadcast(x)
54674     // concat_vectors(extract_subvector(subv_broadcast(x)),
54675     //                extract_subvector(subv_broadcast(x))) -> subv_broadcast(x)
54676     if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
54677         Op0.getOperand(0).getValueType() == VT) {
54678       SDValue SrcVec = Op0.getOperand(0);
54679       if (SrcVec.getOpcode() == X86ISD::VBROADCAST ||
54680           SrcVec.getOpcode() == X86ISD::VBROADCAST_LOAD)
54681         return Op0.getOperand(0);
54682       if (SrcVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
54683           Op0.getValueType() == cast<MemSDNode>(SrcVec)->getMemoryVT())
54684         return Op0.getOperand(0);
54685     }
54686 
54687     // concat_vectors(permq(x),permq(x)) -> permq(concat_vectors(x,x))
54688     if (Op0.getOpcode() == X86ISD::VPERMI && Subtarget.useAVX512Regs() &&
54689         !X86::mayFoldLoad(Op0.getOperand(0), Subtarget))
54690       return DAG.getNode(Op0.getOpcode(), DL, VT,
54691                          DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
54692                                      Op0.getOperand(0), Op0.getOperand(0)),
54693                          Op0.getOperand(1));
54694   }
54695 
54696   // concat(extract_subvector(v0,c0), extract_subvector(v1,c1)) -> vperm2x128.
54697   // Only concat of subvector high halves which vperm2x128 is best at.
54698   // TODO: This should go in combineX86ShufflesRecursively eventually.
54699   if (VT.is256BitVector() && NumOps == 2) {
54700     SDValue Src0 = peekThroughBitcasts(Ops[0]);
54701     SDValue Src1 = peekThroughBitcasts(Ops[1]);
54702     if (Src0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
54703         Src1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
54704       EVT SrcVT0 = Src0.getOperand(0).getValueType();
54705       EVT SrcVT1 = Src1.getOperand(0).getValueType();
54706       unsigned NumSrcElts0 = SrcVT0.getVectorNumElements();
54707       unsigned NumSrcElts1 = SrcVT1.getVectorNumElements();
54708       if (SrcVT0.is256BitVector() && SrcVT1.is256BitVector() &&
54709           Src0.getConstantOperandAPInt(1) == (NumSrcElts0 / 2) &&
54710           Src1.getConstantOperandAPInt(1) == (NumSrcElts1 / 2)) {
54711         return DAG.getNode(X86ISD::VPERM2X128, DL, VT,
54712                            DAG.getBitcast(VT, Src0.getOperand(0)),
54713                            DAG.getBitcast(VT, Src1.getOperand(0)),
54714                            DAG.getTargetConstant(0x31, DL, MVT::i8));
54715       }
54716     }
54717   }
54718 
54719   // Repeated opcode.
54720   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
54721   // but it currently struggles with different vector widths.
54722   if (llvm::all_of(Ops, [Op0](SDValue Op) {
54723         return Op.getOpcode() == Op0.getOpcode() && Op.hasOneUse();
54724       })) {
54725     auto ConcatSubOperand = [&](EVT VT, ArrayRef<SDValue> SubOps, unsigned I) {
54726       SmallVector<SDValue> Subs;
54727       for (SDValue SubOp : SubOps)
54728         Subs.push_back(SubOp.getOperand(I));
54729       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
54730     };
54731     auto IsConcatFree = [](MVT VT, ArrayRef<SDValue> SubOps, unsigned Op) {
54732       bool AllConstants = true;
54733       bool AllSubVectors = true;
54734       for (unsigned I = 0, E = SubOps.size(); I != E; ++I) {
54735         SDValue Sub = SubOps[I].getOperand(Op);
54736         unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
54737         SDValue BC = peekThroughBitcasts(Sub);
54738         AllConstants &= ISD::isBuildVectorOfConstantSDNodes(BC.getNode()) ||
54739                         ISD::isBuildVectorOfConstantFPSDNodes(BC.getNode());
54740         AllSubVectors &= Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
54741                          Sub.getOperand(0).getValueType() == VT &&
54742                          Sub.getConstantOperandAPInt(1) == (I * NumSubElts);
54743       }
54744       return AllConstants || AllSubVectors;
54745     };
54746 
54747     switch (Op0.getOpcode()) {
54748     case X86ISD::VBROADCAST: {
54749       if (!IsSplat && llvm::all_of(Ops, [](SDValue Op) {
54750             return Op.getOperand(0).getValueType().is128BitVector();
54751           })) {
54752         if (VT == MVT::v4f64 || VT == MVT::v4i64)
54753           return DAG.getNode(X86ISD::UNPCKL, DL, VT,
54754                              ConcatSubOperand(VT, Ops, 0),
54755                              ConcatSubOperand(VT, Ops, 0));
54756         // TODO: Add pseudo v8i32 PSHUFD handling to AVX1Only targets.
54757         if (VT == MVT::v8f32 || (VT == MVT::v8i32 && Subtarget.hasInt256()))
54758           return DAG.getNode(VT == MVT::v8f32 ? X86ISD::VPERMILPI
54759                                               : X86ISD::PSHUFD,
54760                              DL, VT, ConcatSubOperand(VT, Ops, 0),
54761                              getV4X86ShuffleImm8ForMask({0, 0, 0, 0}, DL, DAG));
54762       }
54763       break;
54764     }
54765     case X86ISD::MOVDDUP:
54766     case X86ISD::MOVSHDUP:
54767     case X86ISD::MOVSLDUP: {
54768       if (!IsSplat)
54769         return DAG.getNode(Op0.getOpcode(), DL, VT,
54770                            ConcatSubOperand(VT, Ops, 0));
54771       break;
54772     }
54773     case X86ISD::SHUFP: {
54774       // Add SHUFPD support if/when necessary.
54775       if (!IsSplat && VT.getScalarType() == MVT::f32 &&
54776           llvm::all_of(Ops, [Op0](SDValue Op) {
54777             return Op.getOperand(2) == Op0.getOperand(2);
54778           })) {
54779         return DAG.getNode(Op0.getOpcode(), DL, VT,
54780                            ConcatSubOperand(VT, Ops, 0),
54781                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
54782       }
54783       break;
54784     }
54785     case X86ISD::UNPCKH:
54786     case X86ISD::UNPCKL: {
54787       // Don't concatenate build_vector patterns.
54788       if (!IsSplat && EltSizeInBits >= 32 &&
54789           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
54790            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
54791           none_of(Ops, [](SDValue Op) {
54792             return peekThroughBitcasts(Op.getOperand(0)).getOpcode() ==
54793                        ISD::SCALAR_TO_VECTOR ||
54794                    peekThroughBitcasts(Op.getOperand(1)).getOpcode() ==
54795                        ISD::SCALAR_TO_VECTOR;
54796           })) {
54797         return DAG.getNode(Op0.getOpcode(), DL, VT,
54798                            ConcatSubOperand(VT, Ops, 0),
54799                            ConcatSubOperand(VT, Ops, 1));
54800       }
54801       break;
54802     }
54803     case X86ISD::PSHUFHW:
54804     case X86ISD::PSHUFLW:
54805     case X86ISD::PSHUFD:
54806       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
54807           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
54808         return DAG.getNode(Op0.getOpcode(), DL, VT,
54809                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
54810       }
54811       [[fallthrough]];
54812     case X86ISD::VPERMILPI:
54813       if (!IsSplat && EltSizeInBits == 32 &&
54814           (VT.is256BitVector() ||
54815            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
54816           all_of(Ops, [&Op0](SDValue Op) {
54817             return Op0.getOperand(1) == Op.getOperand(1);
54818           })) {
54819         MVT FloatVT = VT.changeVectorElementType(MVT::f32);
54820         SDValue Res = DAG.getBitcast(FloatVT, ConcatSubOperand(VT, Ops, 0));
54821         Res =
54822             DAG.getNode(X86ISD::VPERMILPI, DL, FloatVT, Res, Op0.getOperand(1));
54823         return DAG.getBitcast(VT, Res);
54824       }
54825       if (!IsSplat && NumOps == 2 && VT == MVT::v4f64) {
54826         uint64_t Idx0 = Ops[0].getConstantOperandVal(1);
54827         uint64_t Idx1 = Ops[1].getConstantOperandVal(1);
54828         uint64_t Idx = ((Idx1 & 3) << 2) | (Idx0 & 3);
54829         return DAG.getNode(Op0.getOpcode(), DL, VT,
54830                            ConcatSubOperand(VT, Ops, 0),
54831                            DAG.getTargetConstant(Idx, DL, MVT::i8));
54832       }
54833       break;
54834     case X86ISD::PSHUFB:
54835     case X86ISD::PSADBW:
54836       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
54837                        (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
54838         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
54839         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
54840                                  NumOps * SrcVT.getVectorNumElements());
54841         return DAG.getNode(Op0.getOpcode(), DL, VT,
54842                            ConcatSubOperand(SrcVT, Ops, 0),
54843                            ConcatSubOperand(SrcVT, Ops, 1));
54844       }
54845       break;
54846     case X86ISD::VPERMV:
54847       if (!IsSplat && NumOps == 2 &&
54848           (VT.is512BitVector() && Subtarget.useAVX512Regs())) {
54849         MVT OpVT = Op0.getSimpleValueType();
54850         int NumSrcElts = OpVT.getVectorNumElements();
54851         SmallVector<int, 64> ConcatMask;
54852         for (unsigned i = 0; i != NumOps; ++i) {
54853           SmallVector<int, 64> SubMask;
54854           SmallVector<SDValue, 2> SubOps;
54855           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
54856                                     SubMask))
54857             break;
54858           for (int M : SubMask) {
54859             if (0 <= M)
54860               M += i * NumSrcElts;
54861             ConcatMask.push_back(M);
54862           }
54863         }
54864         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
54865           SDValue Src = concatSubVectors(Ops[0].getOperand(1),
54866                                          Ops[1].getOperand(1), DAG, DL);
54867           MVT IntMaskSVT = MVT::getIntegerVT(EltSizeInBits);
54868           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
54869           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
54870           return DAG.getNode(X86ISD::VPERMV, DL, VT, Mask, Src);
54871         }
54872       }
54873       break;
54874     case X86ISD::VPERMV3:
54875       if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
54876         MVT OpVT = Op0.getSimpleValueType();
54877         int NumSrcElts = OpVT.getVectorNumElements();
54878         SmallVector<int, 64> ConcatMask;
54879         for (unsigned i = 0; i != NumOps; ++i) {
54880           SmallVector<int, 64> SubMask;
54881           SmallVector<SDValue, 2> SubOps;
54882           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
54883                                     SubMask))
54884             break;
54885           for (int M : SubMask) {
54886             if (0 <= M) {
54887               M += M < NumSrcElts ? 0 : NumSrcElts;
54888               M += i * NumSrcElts;
54889             }
54890             ConcatMask.push_back(M);
54891           }
54892         }
54893         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
54894           SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
54895                                           Ops[1].getOperand(0), DAG, DL);
54896           SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
54897                                           Ops[1].getOperand(2), DAG, DL);
54898           MVT IntMaskSVT = MVT::getIntegerVT(EltSizeInBits);
54899           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
54900           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
54901           return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
54902         }
54903       }
54904       break;
54905     case X86ISD::VPERM2X128: {
54906       if (!IsSplat && VT.is512BitVector() && Subtarget.useAVX512Regs()) {
54907         assert(NumOps == 2 && "Bad concat_vectors operands");
54908         unsigned Imm0 = Ops[0].getConstantOperandVal(2);
54909         unsigned Imm1 = Ops[1].getConstantOperandVal(2);
54910         // TODO: Handle zero'd subvectors.
54911         if ((Imm0 & 0x88) == 0 && (Imm1 & 0x88) == 0) {
54912           int Mask[4] = {(int)(Imm0 & 0x03), (int)((Imm0 >> 4) & 0x3), (int)(Imm1 & 0x03),
54913                          (int)((Imm1 >> 4) & 0x3)};
54914           MVT ShuffleVT = VT.isFloatingPoint() ? MVT::v8f64 : MVT::v8i64;
54915           SDValue LHS = concatSubVectors(Ops[0].getOperand(0),
54916                                          Ops[0].getOperand(1), DAG, DL);
54917           SDValue RHS = concatSubVectors(Ops[1].getOperand(0),
54918                                          Ops[1].getOperand(1), DAG, DL);
54919           SDValue Res = DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
54920                                     DAG.getBitcast(ShuffleVT, LHS),
54921                                     DAG.getBitcast(ShuffleVT, RHS),
54922                                     getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
54923           return DAG.getBitcast(VT, Res);
54924         }
54925       }
54926       break;
54927     }
54928     case X86ISD::SHUF128: {
54929       if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
54930         unsigned Imm0 = Ops[0].getConstantOperandVal(2);
54931         unsigned Imm1 = Ops[1].getConstantOperandVal(2);
54932         unsigned Imm = ((Imm0 & 1) << 0) | ((Imm0 & 2) << 1) | 0x08 |
54933                        ((Imm1 & 1) << 4) | ((Imm1 & 2) << 5) | 0x80;
54934         SDValue LHS = concatSubVectors(Ops[0].getOperand(0),
54935                                        Ops[0].getOperand(1), DAG, DL);
54936         SDValue RHS = concatSubVectors(Ops[1].getOperand(0),
54937                                        Ops[1].getOperand(1), DAG, DL);
54938         return DAG.getNode(X86ISD::SHUF128, DL, VT, LHS, RHS,
54939                            DAG.getTargetConstant(Imm, DL, MVT::i8));
54940       }
54941       break;
54942     }
54943     case ISD::TRUNCATE:
54944       if (!IsSplat && NumOps == 2 && VT.is256BitVector()) {
54945         EVT SrcVT = Ops[0].getOperand(0).getValueType();
54946         if (SrcVT.is256BitVector() && SrcVT.isSimple() &&
54947             SrcVT == Ops[1].getOperand(0).getValueType() &&
54948             Subtarget.useAVX512Regs() &&
54949             Subtarget.getPreferVectorWidth() >= 512 &&
54950             (SrcVT.getScalarSizeInBits() > 16 || Subtarget.useBWIRegs())) {
54951           EVT NewSrcVT = SrcVT.getDoubleNumVectorElementsVT(Ctx);
54952           return DAG.getNode(ISD::TRUNCATE, DL, VT,
54953                              ConcatSubOperand(NewSrcVT, Ops, 0));
54954         }
54955       }
54956       break;
54957     case X86ISD::VSHLI:
54958     case X86ISD::VSRLI:
54959       // Special case: SHL/SRL AVX1 V4i64 by 32-bits can lower as a shuffle.
54960       // TODO: Move this to LowerShiftByScalarImmediate?
54961       if (VT == MVT::v4i64 && !Subtarget.hasInt256() &&
54962           llvm::all_of(Ops, [](SDValue Op) {
54963             return Op.getConstantOperandAPInt(1) == 32;
54964           })) {
54965         SDValue Res = DAG.getBitcast(MVT::v8i32, ConcatSubOperand(VT, Ops, 0));
54966         SDValue Zero = getZeroVector(MVT::v8i32, Subtarget, DAG, DL);
54967         if (Op0.getOpcode() == X86ISD::VSHLI) {
54968           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
54969                                      {8, 0, 8, 2, 8, 4, 8, 6});
54970         } else {
54971           Res = DAG.getVectorShuffle(MVT::v8i32, DL, Res, Zero,
54972                                      {1, 8, 3, 8, 5, 8, 7, 8});
54973         }
54974         return DAG.getBitcast(VT, Res);
54975       }
54976       [[fallthrough]];
54977     case X86ISD::VSRAI:
54978     case X86ISD::VSHL:
54979     case X86ISD::VSRL:
54980     case X86ISD::VSRA:
54981       if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
54982            (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
54983             (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
54984           llvm::all_of(Ops, [Op0](SDValue Op) {
54985             return Op0.getOperand(1) == Op.getOperand(1);
54986           })) {
54987         return DAG.getNode(Op0.getOpcode(), DL, VT,
54988                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
54989       }
54990       break;
54991     case X86ISD::VPERMI:
54992     case X86ISD::VROTLI:
54993     case X86ISD::VROTRI:
54994       if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
54995           llvm::all_of(Ops, [Op0](SDValue Op) {
54996             return Op0.getOperand(1) == Op.getOperand(1);
54997           })) {
54998         return DAG.getNode(Op0.getOpcode(), DL, VT,
54999                            ConcatSubOperand(VT, Ops, 0), Op0.getOperand(1));
55000       }
55001       break;
55002     case ISD::AND:
55003     case ISD::OR:
55004     case ISD::XOR:
55005     case X86ISD::ANDNP:
55006       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
55007                        (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
55008         return DAG.getNode(Op0.getOpcode(), DL, VT,
55009                            ConcatSubOperand(VT, Ops, 0),
55010                            ConcatSubOperand(VT, Ops, 1));
55011       }
55012       break;
55013     case X86ISD::PCMPEQ:
55014     case X86ISD::PCMPGT:
55015       if (!IsSplat && VT.is256BitVector() && Subtarget.hasInt256() &&
55016           (IsConcatFree(VT, Ops, 0) || IsConcatFree(VT, Ops, 1))) {
55017         return DAG.getNode(Op0.getOpcode(), DL, VT,
55018                            ConcatSubOperand(VT, Ops, 0),
55019                            ConcatSubOperand(VT, Ops, 1));
55020       }
55021       break;
55022     case ISD::CTPOP:
55023     case ISD::CTTZ:
55024     case ISD::CTLZ:
55025     case ISD::CTTZ_ZERO_UNDEF:
55026     case ISD::CTLZ_ZERO_UNDEF:
55027       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
55028                        (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
55029         return DAG.getNode(Op0.getOpcode(), DL, VT,
55030                            ConcatSubOperand(VT, Ops, 0));
55031       }
55032       break;
55033     case X86ISD::GF2P8AFFINEQB:
55034       if (!IsSplat &&
55035           (VT.is256BitVector() ||
55036            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
55037           llvm::all_of(Ops, [Op0](SDValue Op) {
55038             return Op0.getOperand(2) == Op.getOperand(2);
55039           })) {
55040         return DAG.getNode(Op0.getOpcode(), DL, VT,
55041                            ConcatSubOperand(VT, Ops, 0),
55042                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
55043       }
55044       break;
55045     case ISD::ADD:
55046     case ISD::SUB:
55047     case ISD::MUL:
55048       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
55049                        (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
55050                         (EltSizeInBits >= 32 || Subtarget.useBWIRegs())))) {
55051         return DAG.getNode(Op0.getOpcode(), DL, VT,
55052                            ConcatSubOperand(VT, Ops, 0),
55053                            ConcatSubOperand(VT, Ops, 1));
55054       }
55055       break;
55056     // Due to VADD, VSUB, VMUL can executed on more ports than VINSERT and
55057     // their latency are short, so here we don't replace them.
55058     case ISD::FDIV:
55059       if (!IsSplat && (VT.is256BitVector() ||
55060                        (VT.is512BitVector() && Subtarget.useAVX512Regs()))) {
55061         return DAG.getNode(Op0.getOpcode(), DL, VT,
55062                            ConcatSubOperand(VT, Ops, 0),
55063                            ConcatSubOperand(VT, Ops, 1));
55064       }
55065       break;
55066     case X86ISD::HADD:
55067     case X86ISD::HSUB:
55068     case X86ISD::FHADD:
55069     case X86ISD::FHSUB:
55070       if (!IsSplat && VT.is256BitVector() &&
55071           (VT.isFloatingPoint() || Subtarget.hasInt256())) {
55072         return DAG.getNode(Op0.getOpcode(), DL, VT,
55073                            ConcatSubOperand(VT, Ops, 0),
55074                            ConcatSubOperand(VT, Ops, 1));
55075       }
55076       break;
55077     case X86ISD::PACKSS:
55078     case X86ISD::PACKUS:
55079       if (!IsSplat && ((VT.is256BitVector() && Subtarget.hasInt256()) ||
55080                        (VT.is512BitVector() && Subtarget.useBWIRegs()))) {
55081         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
55082         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
55083                                  NumOps * SrcVT.getVectorNumElements());
55084         return DAG.getNode(Op0.getOpcode(), DL, VT,
55085                            ConcatSubOperand(SrcVT, Ops, 0),
55086                            ConcatSubOperand(SrcVT, Ops, 1));
55087       }
55088       break;
55089     case X86ISD::PALIGNR:
55090       if (!IsSplat &&
55091           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
55092            (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
55093           llvm::all_of(Ops, [Op0](SDValue Op) {
55094             return Op0.getOperand(2) == Op.getOperand(2);
55095           })) {
55096         return DAG.getNode(Op0.getOpcode(), DL, VT,
55097                            ConcatSubOperand(VT, Ops, 0),
55098                            ConcatSubOperand(VT, Ops, 1), Op0.getOperand(2));
55099       }
55100       break;
55101     case X86ISD::BLENDI:
55102       if (NumOps == 2 && VT.is512BitVector() && Subtarget.useBWIRegs()) {
55103         uint64_t Mask0 = Ops[0].getConstantOperandVal(2);
55104         uint64_t Mask1 = Ops[1].getConstantOperandVal(2);
55105         uint64_t Mask = (Mask1 << (VT.getVectorNumElements() / 2)) | Mask0;
55106         MVT MaskSVT = MVT::getIntegerVT(VT.getVectorNumElements());
55107         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
55108         SDValue Sel =
55109             DAG.getBitcast(MaskVT, DAG.getConstant(Mask, DL, MaskSVT));
55110         return DAG.getSelect(DL, VT, Sel, ConcatSubOperand(VT, Ops, 1),
55111                              ConcatSubOperand(VT, Ops, 0));
55112       }
55113       break;
55114     case ISD::VSELECT:
55115       if (!IsSplat && Subtarget.hasAVX512() &&
55116           (VT.is256BitVector() ||
55117            (VT.is512BitVector() && Subtarget.useAVX512Regs())) &&
55118           (EltSizeInBits >= 32 || Subtarget.hasBWI())) {
55119         EVT SelVT = Ops[0].getOperand(0).getValueType();
55120         if (SelVT.getVectorElementType() == MVT::i1) {
55121           SelVT = EVT::getVectorVT(Ctx, MVT::i1,
55122                                    NumOps * SelVT.getVectorNumElements());
55123           if (TLI.isTypeLegal(SelVT))
55124             return DAG.getNode(Op0.getOpcode(), DL, VT,
55125                                ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
55126                                ConcatSubOperand(VT, Ops, 1),
55127                                ConcatSubOperand(VT, Ops, 2));
55128         }
55129       }
55130       [[fallthrough]];
55131     case X86ISD::BLENDV:
55132       if (!IsSplat && VT.is256BitVector() && NumOps == 2 &&
55133           (EltSizeInBits >= 32 || Subtarget.hasInt256()) &&
55134           IsConcatFree(VT, Ops, 1) && IsConcatFree(VT, Ops, 2)) {
55135         EVT SelVT = Ops[0].getOperand(0).getValueType();
55136         SelVT = SelVT.getDoubleNumVectorElementsVT(Ctx);
55137         if (TLI.isTypeLegal(SelVT))
55138           return DAG.getNode(Op0.getOpcode(), DL, VT,
55139                              ConcatSubOperand(SelVT.getSimpleVT(), Ops, 0),
55140                              ConcatSubOperand(VT, Ops, 1),
55141                              ConcatSubOperand(VT, Ops, 2));
55142       }
55143       break;
55144     }
55145   }
55146 
55147   // Fold subvector loads into one.
55148   // If needed, look through bitcasts to get to the load.
55149   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
55150     unsigned Fast;
55151     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
55152     if (TLI->allowsMemoryAccess(Ctx, DAG.getDataLayout(), VT,
55153                                 *FirstLd->getMemOperand(), &Fast) &&
55154         Fast) {
55155       if (SDValue Ld =
55156               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
55157         return Ld;
55158     }
55159   }
55160 
55161   // Attempt to fold target constant loads.
55162   if (all_of(Ops, [](SDValue Op) { return getTargetConstantFromNode(Op); })) {
55163     SmallVector<APInt> EltBits;
55164     APInt UndefElts = APInt::getZero(VT.getVectorNumElements());
55165     for (unsigned I = 0; I != NumOps; ++I) {
55166       APInt OpUndefElts;
55167       SmallVector<APInt> OpEltBits;
55168       if (!getTargetConstantBitsFromNode(Ops[I], EltSizeInBits, OpUndefElts,
55169                                          OpEltBits, true, false))
55170         break;
55171       EltBits.append(OpEltBits);
55172       UndefElts.insertBits(OpUndefElts, I * OpUndefElts.getBitWidth());
55173     }
55174     if (EltBits.size() == VT.getVectorNumElements()) {
55175       Constant *C = getConstantVector(VT, EltBits, UndefElts, Ctx);
55176       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
55177       SDValue CV = DAG.getConstantPool(C, PVT);
55178       MachineFunction &MF = DAG.getMachineFunction();
55179       MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
55180       SDValue Ld = DAG.getLoad(VT, DL, DAG.getEntryNode(), CV, MPI);
55181       SDValue Sub = extractSubVector(Ld, 0, DAG, DL, Op0.getValueSizeInBits());
55182       DAG.ReplaceAllUsesOfValueWith(Op0, Sub);
55183       return Ld;
55184     }
55185   }
55186 
55187   // If this simple subvector or scalar/subvector broadcast_load is inserted
55188   // into both halves, use a larger broadcast_load. Update other uses to use
55189   // an extracted subvector.
55190   if (IsSplat &&
55191       (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
55192     if (ISD::isNormalLoad(Op0.getNode()) ||
55193         Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
55194         Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
55195       auto *Mem = cast<MemSDNode>(Op0);
55196       unsigned Opc = Op0.getOpcode() == X86ISD::VBROADCAST_LOAD
55197                          ? X86ISD::VBROADCAST_LOAD
55198                          : X86ISD::SUBV_BROADCAST_LOAD;
55199       if (SDValue BcastLd =
55200               getBROADCAST_LOAD(Opc, DL, VT, Mem->getMemoryVT(), Mem, 0, DAG)) {
55201         SDValue BcastSrc =
55202             extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits());
55203         DAG.ReplaceAllUsesOfValueWith(Op0, BcastSrc);
55204         return BcastLd;
55205       }
55206     }
55207   }
55208 
55209   // If we're splatting a 128-bit subvector to 512-bits, use SHUF128 directly.
55210   if (IsSplat && NumOps == 4 && VT.is512BitVector() &&
55211       Subtarget.useAVX512Regs()) {
55212     MVT ShuffleVT = VT.isFloatingPoint() ? MVT::v8f64 : MVT::v8i64;
55213     SDValue Res = widenSubVector(Op0, false, Subtarget, DAG, DL, 512);
55214     Res = DAG.getBitcast(ShuffleVT, Res);
55215     Res = DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT, Res, Res,
55216                       getV4X86ShuffleImm8ForMask({0, 0, 0, 0}, DL, DAG));
55217     return DAG.getBitcast(VT, Res);
55218   }
55219 
55220   return SDValue();
55221 }
55222 
combineCONCAT_VECTORS(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)55223 static SDValue combineCONCAT_VECTORS(SDNode *N, SelectionDAG &DAG,
55224                                      TargetLowering::DAGCombinerInfo &DCI,
55225                                      const X86Subtarget &Subtarget) {
55226   EVT VT = N->getValueType(0);
55227   EVT SrcVT = N->getOperand(0).getValueType();
55228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55229   SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
55230 
55231   if (VT.getVectorElementType() == MVT::i1) {
55232     // Attempt to constant fold.
55233     unsigned SubSizeInBits = SrcVT.getSizeInBits();
55234     APInt Constant = APInt::getZero(VT.getSizeInBits());
55235     for (unsigned I = 0, E = Ops.size(); I != E; ++I) {
55236       auto *C = dyn_cast<ConstantSDNode>(peekThroughBitcasts(Ops[I]));
55237       if (!C) break;
55238       Constant.insertBits(C->getAPIntValue(), I * SubSizeInBits);
55239       if (I == (E - 1)) {
55240         EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
55241         if (TLI.isTypeLegal(IntVT))
55242           return DAG.getBitcast(VT, DAG.getConstant(Constant, SDLoc(N), IntVT));
55243       }
55244     }
55245 
55246     // Don't do anything else for i1 vectors.
55247     return SDValue();
55248   }
55249 
55250   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
55251     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
55252                                            DCI, Subtarget))
55253       return R;
55254   }
55255 
55256   return SDValue();
55257 }
55258 
combineINSERT_SUBVECTOR(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)55259 static SDValue combineINSERT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
55260                                        TargetLowering::DAGCombinerInfo &DCI,
55261                                        const X86Subtarget &Subtarget) {
55262   if (DCI.isBeforeLegalizeOps())
55263     return SDValue();
55264 
55265   MVT OpVT = N->getSimpleValueType(0);
55266 
55267   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
55268 
55269   SDLoc dl(N);
55270   SDValue Vec = N->getOperand(0);
55271   SDValue SubVec = N->getOperand(1);
55272 
55273   uint64_t IdxVal = N->getConstantOperandVal(2);
55274   MVT SubVecVT = SubVec.getSimpleValueType();
55275 
55276   if (Vec.isUndef() && SubVec.isUndef())
55277     return DAG.getUNDEF(OpVT);
55278 
55279   // Inserting undefs/zeros into zeros/undefs is a zero vector.
55280   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
55281       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
55282     return getZeroVector(OpVT, Subtarget, DAG, dl);
55283 
55284   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
55285     // If we're inserting into a zero vector and then into a larger zero vector,
55286     // just insert into the larger zero vector directly.
55287     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
55288         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
55289       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
55290       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
55291                          getZeroVector(OpVT, Subtarget, DAG, dl),
55292                          SubVec.getOperand(1),
55293                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
55294     }
55295 
55296     // If we're inserting into a zero vector and our input was extracted from an
55297     // insert into a zero vector of the same type and the extraction was at
55298     // least as large as the original insertion. Just insert the original
55299     // subvector into a zero vector.
55300     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
55301         isNullConstant(SubVec.getOperand(1)) &&
55302         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
55303       SDValue Ins = SubVec.getOperand(0);
55304       if (isNullConstant(Ins.getOperand(2)) &&
55305           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
55306           Ins.getOperand(1).getValueSizeInBits().getFixedValue() <=
55307               SubVecVT.getFixedSizeInBits())
55308           return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
55309                              getZeroVector(OpVT, Subtarget, DAG, dl),
55310                              Ins.getOperand(1), N->getOperand(2));
55311     }
55312   }
55313 
55314   // Stop here if this is an i1 vector.
55315   if (IsI1Vector)
55316     return SDValue();
55317 
55318   // Eliminate an intermediate vector widening:
55319   // insert_subvector X, (insert_subvector undef, Y, 0), Idx -->
55320   // insert_subvector X, Y, Idx
55321   // TODO: This is a more general version of a DAGCombiner fold, can we move it
55322   // there?
55323   if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
55324       SubVec.getOperand(0).isUndef() && isNullConstant(SubVec.getOperand(2)))
55325     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Vec,
55326                        SubVec.getOperand(1), N->getOperand(2));
55327 
55328   // If this is an insert of an extract, combine to a shuffle. Don't do this
55329   // if the insert or extract can be represented with a subregister operation.
55330   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
55331       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
55332       (IdxVal != 0 ||
55333        !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
55334     int ExtIdxVal = SubVec.getConstantOperandVal(1);
55335     if (ExtIdxVal != 0) {
55336       int VecNumElts = OpVT.getVectorNumElements();
55337       int SubVecNumElts = SubVecVT.getVectorNumElements();
55338       SmallVector<int, 64> Mask(VecNumElts);
55339       // First create an identity shuffle mask.
55340       for (int i = 0; i != VecNumElts; ++i)
55341         Mask[i] = i;
55342       // Now insert the extracted portion.
55343       for (int i = 0; i != SubVecNumElts; ++i)
55344         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
55345 
55346       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
55347     }
55348   }
55349 
55350   // Match concat_vector style patterns.
55351   SmallVector<SDValue, 2> SubVectorOps;
55352   if (collectConcatOps(N, SubVectorOps, DAG)) {
55353     if (SDValue Fold =
55354             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
55355       return Fold;
55356 
55357     // If we're inserting all zeros into the upper half, change this to
55358     // a concat with zero. We will match this to a move
55359     // with implicit upper bit zeroing during isel.
55360     // We do this here because we don't want combineConcatVectorOps to
55361     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
55362     if (SubVectorOps.size() == 2 &&
55363         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
55364       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
55365                          getZeroVector(OpVT, Subtarget, DAG, dl),
55366                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
55367 
55368     // Attempt to recursively combine to a shuffle.
55369     if (all_of(SubVectorOps, [](SDValue SubOp) {
55370           return isTargetShuffle(SubOp.getOpcode());
55371         })) {
55372       SDValue Op(N, 0);
55373       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
55374         return Res;
55375     }
55376   }
55377 
55378   // If this is a broadcast insert into an upper undef, use a larger broadcast.
55379   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
55380     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
55381 
55382   // If this is a broadcast load inserted into an upper undef, use a larger
55383   // broadcast load.
55384   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
55385       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
55386     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
55387     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
55388     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
55389     SDValue BcastLd =
55390         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
55391                                 MemIntr->getMemoryVT(),
55392                                 MemIntr->getMemOperand());
55393     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
55394     return BcastLd;
55395   }
55396 
55397   // If we're splatting the lower half subvector of a full vector load into the
55398   // upper half, attempt to create a subvector broadcast.
55399   if (IdxVal == (OpVT.getVectorNumElements() / 2) && SubVec.hasOneUse() &&
55400       Vec.getValueSizeInBits() == (2 * SubVec.getValueSizeInBits())) {
55401     auto *VecLd = dyn_cast<LoadSDNode>(Vec);
55402     auto *SubLd = dyn_cast<LoadSDNode>(SubVec);
55403     if (VecLd && SubLd &&
55404         DAG.areNonVolatileConsecutiveLoads(SubLd, VecLd,
55405                                            SubVec.getValueSizeInBits() / 8, 0))
55406       return getBROADCAST_LOAD(X86ISD::SUBV_BROADCAST_LOAD, dl, OpVT, SubVecVT,
55407                                SubLd, 0, DAG);
55408   }
55409 
55410   return SDValue();
55411 }
55412 
55413 /// If we are extracting a subvector of a vector select and the select condition
55414 /// is composed of concatenated vectors, try to narrow the select width. This
55415 /// is a common pattern for AVX1 integer code because 256-bit selects may be
55416 /// legal, but there is almost no integer math/logic available for 256-bit.
55417 /// This function should only be called with legal types (otherwise, the calls
55418 /// to get simple value types will assert).
narrowExtractedVectorSelect(SDNode * Ext,SelectionDAG & DAG)55419 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
55420   SDValue Sel = Ext->getOperand(0);
55421   if (Sel.getOpcode() != ISD::VSELECT ||
55422       !isFreeToSplitVector(Sel.getOperand(0).getNode(), DAG))
55423     return SDValue();
55424 
55425   // Note: We assume simple value types because this should only be called with
55426   //       legal operations/types.
55427   // TODO: This can be extended to handle extraction to 256-bits.
55428   MVT VT = Ext->getSimpleValueType(0);
55429   if (!VT.is128BitVector())
55430     return SDValue();
55431 
55432   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
55433   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
55434     return SDValue();
55435 
55436   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
55437   MVT SelVT = Sel.getSimpleValueType();
55438   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
55439          "Unexpected vector type with legal operations");
55440 
55441   unsigned SelElts = SelVT.getVectorNumElements();
55442   unsigned CastedElts = WideVT.getVectorNumElements();
55443   unsigned ExtIdx = Ext->getConstantOperandVal(1);
55444   if (SelElts % CastedElts == 0) {
55445     // The select has the same or more (narrower) elements than the extract
55446     // operand. The extraction index gets scaled by that factor.
55447     ExtIdx *= (SelElts / CastedElts);
55448   } else if (CastedElts % SelElts == 0) {
55449     // The select has less (wider) elements than the extract operand. Make sure
55450     // that the extraction index can be divided evenly.
55451     unsigned IndexDivisor = CastedElts / SelElts;
55452     if (ExtIdx % IndexDivisor != 0)
55453       return SDValue();
55454     ExtIdx /= IndexDivisor;
55455   } else {
55456     llvm_unreachable("Element count of simple vector types are not divisible?");
55457   }
55458 
55459   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
55460   unsigned NarrowElts = SelElts / NarrowingFactor;
55461   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
55462   SDLoc DL(Ext);
55463   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
55464   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
55465   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
55466   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
55467   return DAG.getBitcast(VT, NarrowSel);
55468 }
55469 
combineEXTRACT_SUBVECTOR(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)55470 static SDValue combineEXTRACT_SUBVECTOR(SDNode *N, SelectionDAG &DAG,
55471                                         TargetLowering::DAGCombinerInfo &DCI,
55472                                         const X86Subtarget &Subtarget) {
55473   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
55474   // eventually get combined/lowered into ANDNP) with a concatenated operand,
55475   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
55476   // We let generic combining take over from there to simplify the
55477   // insert/extract and 'not'.
55478   // This pattern emerges during AVX1 legalization. We handle it before lowering
55479   // to avoid complications like splitting constant vector loads.
55480 
55481   // Capture the original wide type in the likely case that we need to bitcast
55482   // back to this type.
55483   if (!N->getValueType(0).isSimple())
55484     return SDValue();
55485 
55486   MVT VT = N->getSimpleValueType(0);
55487   SDValue InVec = N->getOperand(0);
55488   unsigned IdxVal = N->getConstantOperandVal(1);
55489   SDValue InVecBC = peekThroughBitcasts(InVec);
55490   EVT InVecVT = InVec.getValueType();
55491   unsigned SizeInBits = VT.getSizeInBits();
55492   unsigned InSizeInBits = InVecVT.getSizeInBits();
55493   unsigned NumSubElts = VT.getVectorNumElements();
55494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55495 
55496   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
55497       TLI.isTypeLegal(InVecVT) &&
55498       InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
55499     auto isConcatenatedNot = [](SDValue V) {
55500       V = peekThroughBitcasts(V);
55501       if (!isBitwiseNot(V))
55502         return false;
55503       SDValue NotOp = V->getOperand(0);
55504       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
55505     };
55506     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
55507         isConcatenatedNot(InVecBC.getOperand(1))) {
55508       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
55509       SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
55510       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
55511                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
55512     }
55513   }
55514 
55515   if (DCI.isBeforeLegalizeOps())
55516     return SDValue();
55517 
55518   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
55519     return V;
55520 
55521   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
55522     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
55523 
55524   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
55525     if (VT.getScalarType() == MVT::i1)
55526       return DAG.getConstant(1, SDLoc(N), VT);
55527     return getOnesVector(VT, DAG, SDLoc(N));
55528   }
55529 
55530   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
55531     return DAG.getBuildVector(VT, SDLoc(N),
55532                               InVec->ops().slice(IdxVal, NumSubElts));
55533 
55534   // If we are extracting from an insert into a larger vector, replace with a
55535   // smaller insert if we don't access less than the original subvector. Don't
55536   // do this for i1 vectors.
55537   // TODO: Relax the matching indices requirement?
55538   if (VT.getVectorElementType() != MVT::i1 &&
55539       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && InVec.hasOneUse() &&
55540       IdxVal == InVec.getConstantOperandVal(2) &&
55541       InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
55542     SDLoc DL(N);
55543     SDValue NewExt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT,
55544                                  InVec.getOperand(0), N->getOperand(1));
55545     unsigned NewIdxVal = InVec.getConstantOperandVal(2) - IdxVal;
55546     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, NewExt,
55547                        InVec.getOperand(1),
55548                        DAG.getVectorIdxConstant(NewIdxVal, DL));
55549   }
55550 
55551   // If we're extracting an upper subvector from a broadcast we should just
55552   // extract the lowest subvector instead which should allow
55553   // SimplifyDemandedVectorElts do more simplifications.
55554   if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
55555                       InVec.getOpcode() == X86ISD::VBROADCAST_LOAD ||
55556                       DAG.isSplatValue(InVec, /*AllowUndefs*/ false)))
55557     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
55558 
55559   // If we're extracting a broadcasted subvector, just use the lowest subvector.
55560   if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
55561       cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
55562     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
55563 
55564   // Attempt to extract from the source of a shuffle vector.
55565   if ((InSizeInBits % SizeInBits) == 0 && (IdxVal % NumSubElts) == 0) {
55566     SmallVector<int, 32> ShuffleMask;
55567     SmallVector<int, 32> ScaledMask;
55568     SmallVector<SDValue, 2> ShuffleInputs;
55569     unsigned NumSubVecs = InSizeInBits / SizeInBits;
55570     // Decode the shuffle mask and scale it so its shuffling subvectors.
55571     if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
55572         scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
55573       unsigned SubVecIdx = IdxVal / NumSubElts;
55574       if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
55575         return DAG.getUNDEF(VT);
55576       if (ScaledMask[SubVecIdx] == SM_SentinelZero)
55577         return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
55578       SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
55579       if (Src.getValueSizeInBits() == InSizeInBits) {
55580         unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
55581         unsigned SrcEltIdx = SrcSubVecIdx * NumSubElts;
55582         return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
55583                                 SDLoc(N), SizeInBits);
55584       }
55585     }
55586   }
55587 
55588   // If we're extracting the lowest subvector and we're the only user,
55589   // we may be able to perform this with a smaller vector width.
55590   unsigned InOpcode = InVec.getOpcode();
55591   if (InVec.hasOneUse()) {
55592     if (IdxVal == 0 && VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
55593       // v2f64 CVTDQ2PD(v4i32).
55594       if (InOpcode == ISD::SINT_TO_FP &&
55595           InVec.getOperand(0).getValueType() == MVT::v4i32) {
55596         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
55597       }
55598       // v2f64 CVTUDQ2PD(v4i32).
55599       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
55600           InVec.getOperand(0).getValueType() == MVT::v4i32) {
55601         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
55602       }
55603       // v2f64 CVTPS2PD(v4f32).
55604       if (InOpcode == ISD::FP_EXTEND &&
55605           InVec.getOperand(0).getValueType() == MVT::v4f32) {
55606         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
55607       }
55608     }
55609     if (IdxVal == 0 &&
55610         (ISD::isExtOpcode(InOpcode) || ISD::isExtVecInRegOpcode(InOpcode)) &&
55611         (SizeInBits == 128 || SizeInBits == 256) &&
55612         InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
55613       SDLoc DL(N);
55614       SDValue Ext = InVec.getOperand(0);
55615       if (Ext.getValueSizeInBits() > SizeInBits)
55616         Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
55617       unsigned ExtOp = DAG.getOpcode_EXTEND_VECTOR_INREG(InOpcode);
55618       return DAG.getNode(ExtOp, DL, VT, Ext);
55619     }
55620     if (IdxVal == 0 && InOpcode == ISD::VSELECT &&
55621         InVec.getOperand(0).getValueType().is256BitVector() &&
55622         InVec.getOperand(1).getValueType().is256BitVector() &&
55623         InVec.getOperand(2).getValueType().is256BitVector()) {
55624       SDLoc DL(N);
55625       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
55626       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
55627       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
55628       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
55629     }
55630     if (IdxVal == 0 && InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
55631         (VT.is128BitVector() || VT.is256BitVector())) {
55632       SDLoc DL(N);
55633       SDValue InVecSrc = InVec.getOperand(0);
55634       unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
55635       SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
55636       return DAG.getNode(InOpcode, DL, VT, Ext);
55637     }
55638     if (InOpcode == X86ISD::MOVDDUP &&
55639         (VT.is128BitVector() || VT.is256BitVector())) {
55640       SDLoc DL(N);
55641       SDValue Ext0 =
55642           extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
55643       return DAG.getNode(InOpcode, DL, VT, Ext0);
55644     }
55645   }
55646 
55647   // Always split vXi64 logical shifts where we're extracting the upper 32-bits
55648   // as this is very likely to fold into a shuffle/truncation.
55649   if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
55650       InVecVT.getScalarSizeInBits() == 64 &&
55651       InVec.getConstantOperandAPInt(1) == 32) {
55652     SDLoc DL(N);
55653     SDValue Ext =
55654         extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
55655     return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
55656   }
55657 
55658   return SDValue();
55659 }
55660 
combineScalarToVector(SDNode * N,SelectionDAG & DAG)55661 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
55662   EVT VT = N->getValueType(0);
55663   SDValue Src = N->getOperand(0);
55664   SDLoc DL(N);
55665 
55666   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
55667   // This occurs frequently in our masked scalar intrinsic code and our
55668   // floating point select lowering with AVX512.
55669   // TODO: SimplifyDemandedBits instead?
55670   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse() &&
55671       isOneConstant(Src.getOperand(1)))
55672     return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Src.getOperand(0));
55673 
55674   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
55675   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
55676       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
55677       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
55678       isNullConstant(Src.getOperand(1)))
55679     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
55680                        Src.getOperand(1));
55681 
55682   // Reduce v2i64 to v4i32 if we don't need the upper bits or are known zero.
55683   // TODO: Move to DAGCombine/SimplifyDemandedBits?
55684   if ((VT == MVT::v2i64 || VT == MVT::v2f64) && Src.hasOneUse()) {
55685     auto IsExt64 = [&DAG](SDValue Op, bool IsZeroExt) {
55686       if (Op.getValueType() != MVT::i64)
55687         return SDValue();
55688       unsigned Opc = IsZeroExt ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND;
55689       if (Op.getOpcode() == Opc &&
55690           Op.getOperand(0).getScalarValueSizeInBits() <= 32)
55691         return Op.getOperand(0);
55692       unsigned Ext = IsZeroExt ? ISD::ZEXTLOAD : ISD::EXTLOAD;
55693       if (auto *Ld = dyn_cast<LoadSDNode>(Op))
55694         if (Ld->getExtensionType() == Ext &&
55695             Ld->getMemoryVT().getScalarSizeInBits() <= 32)
55696           return Op;
55697       if (IsZeroExt) {
55698         KnownBits Known = DAG.computeKnownBits(Op);
55699         if (!Known.isConstant() && Known.countMinLeadingZeros() >= 32)
55700           return Op;
55701       }
55702       return SDValue();
55703     };
55704 
55705     if (SDValue AnyExt = IsExt64(peekThroughOneUseBitcasts(Src), false))
55706       return DAG.getBitcast(
55707           VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
55708                           DAG.getAnyExtOrTrunc(AnyExt, DL, MVT::i32)));
55709 
55710     if (SDValue ZeroExt = IsExt64(peekThroughOneUseBitcasts(Src), true))
55711       return DAG.getBitcast(
55712           VT,
55713           DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v4i32,
55714                       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
55715                                   DAG.getZExtOrTrunc(ZeroExt, DL, MVT::i32))));
55716   }
55717 
55718   // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
55719   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
55720       Src.getOperand(0).getValueType() == MVT::x86mmx)
55721     return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
55722 
55723   // See if we're broadcasting the scalar value, in which case just reuse that.
55724   // Ensure the same SDValue from the SDNode use is being used.
55725   if (VT.getScalarType() == Src.getValueType())
55726     for (SDNode *User : Src->uses())
55727       if (User->getOpcode() == X86ISD::VBROADCAST &&
55728           Src == User->getOperand(0)) {
55729         unsigned SizeInBits = VT.getFixedSizeInBits();
55730         unsigned BroadcastSizeInBits =
55731             User->getValueSizeInBits(0).getFixedValue();
55732         if (BroadcastSizeInBits == SizeInBits)
55733           return SDValue(User, 0);
55734         if (BroadcastSizeInBits > SizeInBits)
55735           return extractSubVector(SDValue(User, 0), 0, DAG, DL, SizeInBits);
55736         // TODO: Handle BroadcastSizeInBits < SizeInBits when we have test
55737         // coverage.
55738       }
55739 
55740   return SDValue();
55741 }
55742 
55743 // Simplify PMULDQ and PMULUDQ operations.
combinePMULDQ(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)55744 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
55745                              TargetLowering::DAGCombinerInfo &DCI,
55746                              const X86Subtarget &Subtarget) {
55747   SDValue LHS = N->getOperand(0);
55748   SDValue RHS = N->getOperand(1);
55749 
55750   // Canonicalize constant to RHS.
55751   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
55752       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
55753     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
55754 
55755   // Multiply by zero.
55756   // Don't return RHS as it may contain UNDEFs.
55757   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
55758     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
55759 
55760   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
55761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55762   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(64), DCI))
55763     return SDValue(N, 0);
55764 
55765   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
55766   // convert it to any_extend_invec, due to the LegalOperations check, do the
55767   // conversion directly to a vector shuffle manually. This exposes combine
55768   // opportunities missed by combineEXTEND_VECTOR_INREG not calling
55769   // combineX86ShufflesRecursively on SSE4.1 targets.
55770   // FIXME: This is basically a hack around several other issues related to
55771   // ANY_EXTEND_VECTOR_INREG.
55772   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
55773       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
55774        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
55775       LHS.getOperand(0).getValueType() == MVT::v4i32) {
55776     SDLoc dl(N);
55777     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
55778                                LHS.getOperand(0), { 0, -1, 1, -1 });
55779     LHS = DAG.getBitcast(MVT::v2i64, LHS);
55780     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
55781   }
55782   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
55783       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
55784        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
55785       RHS.getOperand(0).getValueType() == MVT::v4i32) {
55786     SDLoc dl(N);
55787     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
55788                                RHS.getOperand(0), { 0, -1, 1, -1 });
55789     RHS = DAG.getBitcast(MVT::v2i64, RHS);
55790     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
55791   }
55792 
55793   return SDValue();
55794 }
55795 
55796 // Simplify VPMADDUBSW/VPMADDWD operations.
combineVPMADD(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)55797 static SDValue combineVPMADD(SDNode *N, SelectionDAG &DAG,
55798                              TargetLowering::DAGCombinerInfo &DCI) {
55799   EVT VT = N->getValueType(0);
55800   SDValue LHS = N->getOperand(0);
55801   SDValue RHS = N->getOperand(1);
55802 
55803   // Multiply by zero.
55804   // Don't return LHS/RHS as it may contain UNDEFs.
55805   if (ISD::isBuildVectorAllZeros(LHS.getNode()) ||
55806       ISD::isBuildVectorAllZeros(RHS.getNode()))
55807     return DAG.getConstant(0, SDLoc(N), VT);
55808 
55809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55810   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
55811   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
55812     return SDValue(N, 0);
55813 
55814   return SDValue();
55815 }
55816 
combineEXTEND_VECTOR_INREG(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)55817 static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
55818                                           TargetLowering::DAGCombinerInfo &DCI,
55819                                           const X86Subtarget &Subtarget) {
55820   EVT VT = N->getValueType(0);
55821   SDValue In = N->getOperand(0);
55822   unsigned Opcode = N->getOpcode();
55823   unsigned InOpcode = In.getOpcode();
55824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55825   SDLoc DL(N);
55826 
55827   // Try to merge vector loads and extend_inreg to an extload.
55828   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
55829       In.hasOneUse()) {
55830     auto *Ld = cast<LoadSDNode>(In);
55831     if (Ld->isSimple()) {
55832       MVT SVT = In.getSimpleValueType().getVectorElementType();
55833       ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
55834                                  ? ISD::SEXTLOAD
55835                                  : ISD::ZEXTLOAD;
55836       EVT MemVT = VT.changeVectorElementType(SVT);
55837       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
55838         SDValue Load = DAG.getExtLoad(
55839             Ext, DL, VT, Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
55840             MemVT, Ld->getOriginalAlign(), Ld->getMemOperand()->getFlags());
55841         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
55842         return Load;
55843       }
55844     }
55845   }
55846 
55847   // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
55848   if (Opcode == InOpcode)
55849     return DAG.getNode(Opcode, DL, VT, In.getOperand(0));
55850 
55851   // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
55852   // -> EXTEND_VECTOR_INREG(X).
55853   // TODO: Handle non-zero subvector indices.
55854   if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
55855       In.getOperand(0).getOpcode() == DAG.getOpcode_EXTEND(Opcode) &&
55856       In.getOperand(0).getOperand(0).getValueSizeInBits() ==
55857           In.getValueSizeInBits())
55858     return DAG.getNode(Opcode, DL, VT, In.getOperand(0).getOperand(0));
55859 
55860   // Fold EXTEND_VECTOR_INREG(BUILD_VECTOR(X,Y,?,?)) -> BUILD_VECTOR(X,0,Y,0).
55861   // TODO: Move to DAGCombine?
55862   if (!DCI.isBeforeLegalizeOps() && Opcode == ISD::ZERO_EXTEND_VECTOR_INREG &&
55863       In.getOpcode() == ISD::BUILD_VECTOR && In.hasOneUse() &&
55864       In.getValueSizeInBits() == VT.getSizeInBits()) {
55865     unsigned NumElts = VT.getVectorNumElements();
55866     unsigned Scale = VT.getScalarSizeInBits() / In.getScalarValueSizeInBits();
55867     EVT EltVT = In.getOperand(0).getValueType();
55868     SmallVector<SDValue> Elts(Scale * NumElts, DAG.getConstant(0, DL, EltVT));
55869     for (unsigned I = 0; I != NumElts; ++I)
55870       Elts[I * Scale] = In.getOperand(I);
55871     return DAG.getBitcast(VT, DAG.getBuildVector(In.getValueType(), DL, Elts));
55872   }
55873 
55874   // Attempt to combine as a shuffle on SSE41+ targets.
55875   if (Subtarget.hasSSE41()) {
55876     SDValue Op(N, 0);
55877     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
55878       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
55879         return Res;
55880   }
55881 
55882   return SDValue();
55883 }
55884 
combineKSHIFT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)55885 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
55886                              TargetLowering::DAGCombinerInfo &DCI) {
55887   EVT VT = N->getValueType(0);
55888 
55889   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
55890     return DAG.getConstant(0, SDLoc(N), VT);
55891 
55892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
55893   APInt DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
55894   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, DCI))
55895     return SDValue(N, 0);
55896 
55897   return SDValue();
55898 }
55899 
55900 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
55901 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
55902 // extra instructions between the conversion due to going to scalar and back.
combineFP16_TO_FP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)55903 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
55904                                  const X86Subtarget &Subtarget) {
55905   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
55906     return SDValue();
55907 
55908   if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
55909     return SDValue();
55910 
55911   if (N->getValueType(0) != MVT::f32 ||
55912       N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
55913     return SDValue();
55914 
55915   SDLoc dl(N);
55916   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
55917                             N->getOperand(0).getOperand(0));
55918   Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
55919                     DAG.getTargetConstant(4, dl, MVT::i32));
55920   Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
55921   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
55922                      DAG.getIntPtrConstant(0, dl));
55923 }
55924 
combineFP_EXTEND(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)55925 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
55926                                 const X86Subtarget &Subtarget) {
55927   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
55928     return SDValue();
55929 
55930   if (Subtarget.hasFP16())
55931     return SDValue();
55932 
55933   bool IsStrict = N->isStrictFPOpcode();
55934   EVT VT = N->getValueType(0);
55935   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
55936   EVT SrcVT = Src.getValueType();
55937 
55938   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
55939     return SDValue();
55940 
55941   if (VT.getVectorElementType() != MVT::f32 &&
55942       VT.getVectorElementType() != MVT::f64)
55943     return SDValue();
55944 
55945   unsigned NumElts = VT.getVectorNumElements();
55946   if (NumElts == 1 || !isPowerOf2_32(NumElts))
55947     return SDValue();
55948 
55949   SDLoc dl(N);
55950 
55951   // Convert the input to vXi16.
55952   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
55953   Src = DAG.getBitcast(IntVT, Src);
55954 
55955   // Widen to at least 8 input elements.
55956   if (NumElts < 8) {
55957     unsigned NumConcats = 8 / NumElts;
55958     SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
55959                                 : DAG.getConstant(0, dl, IntVT);
55960     SmallVector<SDValue, 4> Ops(NumConcats, Fill);
55961     Ops[0] = Src;
55962     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
55963   }
55964 
55965   // Destination is vXf32 with at least 4 elements.
55966   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
55967                                std::max(4U, NumElts));
55968   SDValue Cvt, Chain;
55969   if (IsStrict) {
55970     Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
55971                       {N->getOperand(0), Src});
55972     Chain = Cvt.getValue(1);
55973   } else {
55974     Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
55975   }
55976 
55977   if (NumElts < 4) {
55978     assert(NumElts == 2 && "Unexpected size");
55979     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
55980                       DAG.getIntPtrConstant(0, dl));
55981   }
55982 
55983   if (IsStrict) {
55984     // Extend to the original VT if necessary.
55985     if (Cvt.getValueType() != VT) {
55986       Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
55987                         {Chain, Cvt});
55988       Chain = Cvt.getValue(1);
55989     }
55990     return DAG.getMergeValues({Cvt, Chain}, dl);
55991   }
55992 
55993   // Extend to the original VT if necessary.
55994   return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
55995 }
55996 
55997 // Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
55998 // from. Limit this to cases where the loads have the same input chain and the
55999 // output chains are unused. This avoids any memory ordering issues.
combineBROADCAST_LOAD(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)56000 static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
56001                                      TargetLowering::DAGCombinerInfo &DCI) {
56002   assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||
56003           N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
56004          "Unknown broadcast load type");
56005 
56006   // Only do this if the chain result is unused.
56007   if (N->hasAnyUseOfValue(1))
56008     return SDValue();
56009 
56010   auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
56011 
56012   SDValue Ptr = MemIntrin->getBasePtr();
56013   SDValue Chain = MemIntrin->getChain();
56014   EVT VT = N->getSimpleValueType(0);
56015   EVT MemVT = MemIntrin->getMemoryVT();
56016 
56017   // Look at other users of our base pointer and try to find a wider broadcast.
56018   // The input chain and the size of the memory VT must match.
56019   for (SDNode *User : Ptr->uses())
56020     if (User != N && User->getOpcode() == N->getOpcode() &&
56021         cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
56022         cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
56023         cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
56024             MemVT.getSizeInBits() &&
56025         !User->hasAnyUseOfValue(1) &&
56026         User->getValueSizeInBits(0).getFixedValue() > VT.getFixedSizeInBits()) {
56027       SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
56028                                          VT.getSizeInBits());
56029       Extract = DAG.getBitcast(VT, Extract);
56030       return DCI.CombineTo(N, Extract, SDValue(User, 1));
56031     }
56032 
56033   return SDValue();
56034 }
56035 
combineFP_ROUND(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)56036 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
56037                                const X86Subtarget &Subtarget) {
56038   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
56039     return SDValue();
56040 
56041   bool IsStrict = N->isStrictFPOpcode();
56042   EVT VT = N->getValueType(0);
56043   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
56044   EVT SrcVT = Src.getValueType();
56045 
56046   if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
56047       SrcVT.getVectorElementType() != MVT::f32)
56048     return SDValue();
56049 
56050   SDLoc dl(N);
56051 
56052   SDValue Cvt, Chain;
56053   unsigned NumElts = VT.getVectorNumElements();
56054   if (Subtarget.hasFP16()) {
56055     // Combine (v8f16 fp_round(concat_vectors(v4f32 (xint_to_fp v4i64), ..)))
56056     // into (v8f16 vector_shuffle(v8f16 (CVTXI2P v4i64), ..))
56057     if (NumElts == 8 && Src.getOpcode() == ISD::CONCAT_VECTORS) {
56058       SDValue Cvt0, Cvt1;
56059       SDValue Op0 = Src.getOperand(0);
56060       SDValue Op1 = Src.getOperand(1);
56061       bool IsOp0Strict = Op0->isStrictFPOpcode();
56062       if (Op0.getOpcode() != Op1.getOpcode() ||
56063           Op0.getOperand(IsOp0Strict ? 1 : 0).getValueType() != MVT::v4i64 ||
56064           Op1.getOperand(IsOp0Strict ? 1 : 0).getValueType() != MVT::v4i64) {
56065         return SDValue();
56066       }
56067       int Mask[8] = {0, 1, 2, 3, 8, 9, 10, 11};
56068       if (IsStrict) {
56069         assert(IsOp0Strict && "Op0 must be strict node");
56070         unsigned Opc = Op0.getOpcode() == ISD::STRICT_SINT_TO_FP
56071                            ? X86ISD::STRICT_CVTSI2P
56072                            : X86ISD::STRICT_CVTUI2P;
56073         Cvt0 = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
56074                            {Op0.getOperand(0), Op0.getOperand(1)});
56075         Cvt1 = DAG.getNode(Opc, dl, {MVT::v8f16, MVT::Other},
56076                            {Op1.getOperand(0), Op1.getOperand(1)});
56077         Cvt = DAG.getVectorShuffle(MVT::v8f16, dl, Cvt0, Cvt1, Mask);
56078         return DAG.getMergeValues({Cvt, Cvt0.getValue(1)}, dl);
56079       }
56080       unsigned Opc = Op0.getOpcode() == ISD::SINT_TO_FP ? X86ISD::CVTSI2P
56081                                                         : X86ISD::CVTUI2P;
56082       Cvt0 = DAG.getNode(Opc, dl, MVT::v8f16, Op0.getOperand(0));
56083       Cvt1 = DAG.getNode(Opc, dl, MVT::v8f16, Op1.getOperand(0));
56084       return Cvt = DAG.getVectorShuffle(MVT::v8f16, dl, Cvt0, Cvt1, Mask);
56085     }
56086     return SDValue();
56087   }
56088 
56089   if (NumElts == 1 || !isPowerOf2_32(NumElts))
56090     return SDValue();
56091 
56092   // Widen to at least 4 input elements.
56093   if (NumElts < 4)
56094     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
56095                       DAG.getConstantFP(0.0, dl, SrcVT));
56096 
56097   // Destination is v8i16 with at least 8 elements.
56098   EVT CvtVT =
56099       EVT::getVectorVT(*DAG.getContext(), MVT::i16, std::max(8U, NumElts));
56100   SDValue Rnd = DAG.getTargetConstant(4, dl, MVT::i32);
56101   if (IsStrict) {
56102     Cvt = DAG.getNode(X86ISD::STRICT_CVTPS2PH, dl, {CvtVT, MVT::Other},
56103                       {N->getOperand(0), Src, Rnd});
56104     Chain = Cvt.getValue(1);
56105   } else {
56106     Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src, Rnd);
56107   }
56108 
56109   // Extract down to real number of elements.
56110   if (NumElts < 8) {
56111     EVT IntVT = VT.changeVectorElementTypeToInteger();
56112     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
56113                       DAG.getIntPtrConstant(0, dl));
56114   }
56115 
56116   Cvt = DAG.getBitcast(VT, Cvt);
56117 
56118   if (IsStrict)
56119     return DAG.getMergeValues({Cvt, Chain}, dl);
56120 
56121   return Cvt;
56122 }
56123 
combineMOVDQ2Q(SDNode * N,SelectionDAG & DAG)56124 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
56125   SDValue Src = N->getOperand(0);
56126 
56127   // Turn MOVDQ2Q+simple_load into an mmx load.
56128   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
56129     LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
56130 
56131     if (LN->isSimple()) {
56132       SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
56133                                   LN->getBasePtr(),
56134                                   LN->getPointerInfo(),
56135                                   LN->getOriginalAlign(),
56136                                   LN->getMemOperand()->getFlags());
56137       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
56138       return NewLd;
56139     }
56140   }
56141 
56142   return SDValue();
56143 }
56144 
combinePDEP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)56145 static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
56146                            TargetLowering::DAGCombinerInfo &DCI) {
56147   unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
56148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
56149   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnes(NumBits), DCI))
56150     return SDValue(N, 0);
56151 
56152   return SDValue();
56153 }
56154 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const56155 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
56156                                              DAGCombinerInfo &DCI) const {
56157   SelectionDAG &DAG = DCI.DAG;
56158   switch (N->getOpcode()) {
56159   default: break;
56160   case ISD::SCALAR_TO_VECTOR:
56161     return combineScalarToVector(N, DAG);
56162   case ISD::EXTRACT_VECTOR_ELT:
56163   case X86ISD::PEXTRW:
56164   case X86ISD::PEXTRB:
56165     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
56166   case ISD::CONCAT_VECTORS:
56167     return combineCONCAT_VECTORS(N, DAG, DCI, Subtarget);
56168   case ISD::INSERT_SUBVECTOR:
56169     return combineINSERT_SUBVECTOR(N, DAG, DCI, Subtarget);
56170   case ISD::EXTRACT_SUBVECTOR:
56171     return combineEXTRACT_SUBVECTOR(N, DAG, DCI, Subtarget);
56172   case ISD::VSELECT:
56173   case ISD::SELECT:
56174   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
56175   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
56176   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
56177   case X86ISD::CMP:         return combineCMP(N, DAG, Subtarget);
56178   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
56179   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
56180   case X86ISD::ADD:
56181   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
56182   case X86ISD::SBB:         return combineSBB(N, DAG);
56183   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
56184   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
56185   case ISD::SHL:            return combineShiftLeft(N, DAG);
56186   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG, Subtarget);
56187   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI, Subtarget);
56188   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
56189   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
56190   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
56191   case ISD::BITREVERSE:     return combineBITREVERSE(N, DAG, DCI, Subtarget);
56192   case X86ISD::BEXTR:
56193   case X86ISD::BEXTRI:      return combineBEXTR(N, DAG, DCI, Subtarget);
56194   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
56195   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
56196   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
56197   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
56198   case X86ISD::VEXTRACT_STORE:
56199     return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
56200   case ISD::SINT_TO_FP:
56201   case ISD::STRICT_SINT_TO_FP:
56202     return combineSIntToFP(N, DAG, DCI, Subtarget);
56203   case ISD::UINT_TO_FP:
56204   case ISD::STRICT_UINT_TO_FP:
56205     return combineUIntToFP(N, DAG, Subtarget);
56206   case ISD::FADD:
56207   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
56208   case X86ISD::VFCMULC:
56209   case X86ISD::VFMULC:      return combineFMulcFCMulc(N, DAG, Subtarget);
56210   case ISD::FNEG:           return combineFneg(N, DAG, DCI, Subtarget);
56211   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
56212   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG, DCI);
56213   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
56214   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
56215   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
56216   case X86ISD::FXOR:
56217   case X86ISD::FOR:         return combineFOr(N, DAG, DCI, Subtarget);
56218   case X86ISD::FMIN:
56219   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
56220   case ISD::FMINNUM:
56221   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
56222   case X86ISD::CVTSI2P:
56223   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
56224   case X86ISD::CVTP2SI:
56225   case X86ISD::CVTP2UI:
56226   case X86ISD::STRICT_CVTTP2SI:
56227   case X86ISD::CVTTP2SI:
56228   case X86ISD::STRICT_CVTTP2UI:
56229   case X86ISD::CVTTP2UI:
56230                             return combineCVTP2I_CVTTP2I(N, DAG, DCI);
56231   case X86ISD::STRICT_CVTPH2PS:
56232   case X86ISD::CVTPH2PS:    return combineCVTPH2PS(N, DAG, DCI);
56233   case X86ISD::BT:          return combineBT(N, DAG, DCI);
56234   case ISD::ANY_EXTEND:
56235   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
56236   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
56237   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
56238   case ISD::ANY_EXTEND_VECTOR_INREG:
56239   case ISD::SIGN_EXTEND_VECTOR_INREG:
56240   case ISD::ZERO_EXTEND_VECTOR_INREG:
56241     return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
56242   case ISD::SETCC:          return combineSetCC(N, DAG, DCI, Subtarget);
56243   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
56244   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
56245   case X86ISD::PACKSS:
56246   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
56247   case X86ISD::HADD:
56248   case X86ISD::HSUB:
56249   case X86ISD::FHADD:
56250   case X86ISD::FHSUB:       return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
56251   case X86ISD::VSHL:
56252   case X86ISD::VSRA:
56253   case X86ISD::VSRL:
56254     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
56255   case X86ISD::VSHLI:
56256   case X86ISD::VSRAI:
56257   case X86ISD::VSRLI:
56258     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
56259   case ISD::INSERT_VECTOR_ELT:
56260   case X86ISD::PINSRB:
56261   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
56262   case X86ISD::SHUFP:       // Handle all target specific shuffles
56263   case X86ISD::INSERTPS:
56264   case X86ISD::EXTRQI:
56265   case X86ISD::INSERTQI:
56266   case X86ISD::VALIGN:
56267   case X86ISD::PALIGNR:
56268   case X86ISD::VSHLDQ:
56269   case X86ISD::VSRLDQ:
56270   case X86ISD::BLENDI:
56271   case X86ISD::UNPCKH:
56272   case X86ISD::UNPCKL:
56273   case X86ISD::MOVHLPS:
56274   case X86ISD::MOVLHPS:
56275   case X86ISD::PSHUFB:
56276   case X86ISD::PSHUFD:
56277   case X86ISD::PSHUFHW:
56278   case X86ISD::PSHUFLW:
56279   case X86ISD::MOVSHDUP:
56280   case X86ISD::MOVSLDUP:
56281   case X86ISD::MOVDDUP:
56282   case X86ISD::MOVSS:
56283   case X86ISD::MOVSD:
56284   case X86ISD::MOVSH:
56285   case X86ISD::VBROADCAST:
56286   case X86ISD::VPPERM:
56287   case X86ISD::VPERMI:
56288   case X86ISD::VPERMV:
56289   case X86ISD::VPERMV3:
56290   case X86ISD::VPERMIL2:
56291   case X86ISD::VPERMILPI:
56292   case X86ISD::VPERMILPV:
56293   case X86ISD::VPERM2X128:
56294   case X86ISD::SHUF128:
56295   case X86ISD::VZEXT_MOVL:
56296   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
56297   case X86ISD::FMADD_RND:
56298   case X86ISD::FMSUB:
56299   case X86ISD::STRICT_FMSUB:
56300   case X86ISD::FMSUB_RND:
56301   case X86ISD::FNMADD:
56302   case X86ISD::STRICT_FNMADD:
56303   case X86ISD::FNMADD_RND:
56304   case X86ISD::FNMSUB:
56305   case X86ISD::STRICT_FNMSUB:
56306   case X86ISD::FNMSUB_RND:
56307   case ISD::FMA:
56308   case ISD::STRICT_FMA:     return combineFMA(N, DAG, DCI, Subtarget);
56309   case X86ISD::FMADDSUB_RND:
56310   case X86ISD::FMSUBADD_RND:
56311   case X86ISD::FMADDSUB:
56312   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
56313   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
56314   case X86ISD::TESTP:       return combineTESTP(N, DAG, DCI, Subtarget);
56315   case X86ISD::MGATHER:
56316   case X86ISD::MSCATTER:    return combineX86GatherScatter(N, DAG, DCI);
56317   case ISD::MGATHER:
56318   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
56319   case X86ISD::PCMPEQ:
56320   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
56321   case X86ISD::PMULDQ:
56322   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
56323   case X86ISD::VPMADDUBSW:
56324   case X86ISD::VPMADDWD:    return combineVPMADD(N, DAG, DCI);
56325   case X86ISD::KSHIFTL:
56326   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
56327   case ISD::FP16_TO_FP:     return combineFP16_TO_FP(N, DAG, Subtarget);
56328   case ISD::STRICT_FP_EXTEND:
56329   case ISD::FP_EXTEND:      return combineFP_EXTEND(N, DAG, Subtarget);
56330   case ISD::STRICT_FP_ROUND:
56331   case ISD::FP_ROUND:       return combineFP_ROUND(N, DAG, Subtarget);
56332   case X86ISD::VBROADCAST_LOAD:
56333   case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
56334   case X86ISD::MOVDQ2Q:     return combineMOVDQ2Q(N, DAG);
56335   case X86ISD::PDEP:        return combinePDEP(N, DAG, DCI);
56336   }
56337 
56338   return SDValue();
56339 }
56340 
preferABDSToABSWithNSW(EVT VT) const56341 bool X86TargetLowering::preferABDSToABSWithNSW(EVT VT) const {
56342   return false;
56343 }
56344 
56345 // Prefer (non-AVX512) vector TRUNCATE(SIGN_EXTEND_INREG(X)) to use of PACKSS.
preferSextInRegOfTruncate(EVT TruncVT,EVT VT,EVT ExtVT) const56346 bool X86TargetLowering::preferSextInRegOfTruncate(EVT TruncVT, EVT VT,
56347                                                   EVT ExtVT) const {
56348   return Subtarget.hasAVX512() || !VT.isVector();
56349 }
56350 
isTypeDesirableForOp(unsigned Opc,EVT VT) const56351 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
56352   if (!isTypeLegal(VT))
56353     return false;
56354 
56355   // There are no vXi8 shifts.
56356   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
56357     return false;
56358 
56359   // TODO: Almost no 8-bit ops are desirable because they have no actual
56360   //       size/speed advantages vs. 32-bit ops, but they do have a major
56361   //       potential disadvantage by causing partial register stalls.
56362   //
56363   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
56364   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
56365   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
56366   // check for a constant operand to the multiply.
56367   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
56368     return false;
56369 
56370   // i16 instruction encodings are longer and some i16 instructions are slow,
56371   // so those are not desirable.
56372   if (VT == MVT::i16) {
56373     switch (Opc) {
56374     default:
56375       break;
56376     case ISD::LOAD:
56377     case ISD::SIGN_EXTEND:
56378     case ISD::ZERO_EXTEND:
56379     case ISD::ANY_EXTEND:
56380     case ISD::SHL:
56381     case ISD::SRA:
56382     case ISD::SRL:
56383     case ISD::SUB:
56384     case ISD::ADD:
56385     case ISD::MUL:
56386     case ISD::AND:
56387     case ISD::OR:
56388     case ISD::XOR:
56389       return false;
56390     }
56391   }
56392 
56393   // Any legal type not explicitly accounted for above here is desirable.
56394   return true;
56395 }
56396 
expandIndirectJTBranch(const SDLoc & dl,SDValue Value,SDValue Addr,int JTI,SelectionDAG & DAG) const56397 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc &dl,
56398                                                   SDValue Value, SDValue Addr,
56399                                                   int JTI,
56400                                                   SelectionDAG &DAG) const {
56401   const Module *M = DAG.getMachineFunction().getMMI().getModule();
56402   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
56403   if (IsCFProtectionSupported) {
56404     // In case control-flow branch protection is enabled, we need to add
56405     // notrack prefix to the indirect branch.
56406     // In order to do that we create NT_BRIND SDNode.
56407     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
56408     SDValue JTInfo = DAG.getJumpTableDebugInfo(JTI, Value, dl);
56409     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, JTInfo, Addr);
56410   }
56411 
56412   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, JTI, DAG);
56413 }
56414 
56415 TargetLowering::AndOrSETCCFoldKind
isDesirableToCombineLogicOpOfSETCC(const SDNode * LogicOp,const SDNode * SETCC0,const SDNode * SETCC1) const56416 X86TargetLowering::isDesirableToCombineLogicOpOfSETCC(
56417     const SDNode *LogicOp, const SDNode *SETCC0, const SDNode *SETCC1) const {
56418   using AndOrSETCCFoldKind = TargetLowering::AndOrSETCCFoldKind;
56419   EVT VT = LogicOp->getValueType(0);
56420   EVT OpVT = SETCC0->getOperand(0).getValueType();
56421   if (!VT.isInteger())
56422     return AndOrSETCCFoldKind::None;
56423 
56424   if (VT.isVector())
56425     return AndOrSETCCFoldKind(AndOrSETCCFoldKind::NotAnd |
56426                               (isOperationLegal(ISD::ABS, OpVT)
56427                                    ? AndOrSETCCFoldKind::ABS
56428                                    : AndOrSETCCFoldKind::None));
56429 
56430   // Don't use `NotAnd` as even though `not` is generally shorter code size than
56431   // `add`, `add` can lower to LEA which can save moves / spills. Any case where
56432   // `NotAnd` applies, `AddAnd` does as well.
56433   // TODO: Currently we lower (icmp eq/ne (and ~X, Y), 0) -> `test (not X), Y`,
56434   // if we change that to `andn Y, X` it may be worth prefering `NotAnd` here.
56435   return AndOrSETCCFoldKind::AddAnd;
56436 }
56437 
IsDesirableToPromoteOp(SDValue Op,EVT & PVT) const56438 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
56439   EVT VT = Op.getValueType();
56440   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
56441                              isa<ConstantSDNode>(Op.getOperand(1));
56442 
56443   // i16 is legal, but undesirable since i16 instruction encodings are longer
56444   // and some i16 instructions are slow.
56445   // 8-bit multiply-by-constant can usually be expanded to something cheaper
56446   // using LEA and/or other ALU ops.
56447   if (VT != MVT::i16 && !Is8BitMulByConstant)
56448     return false;
56449 
56450   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
56451     if (!Op.hasOneUse())
56452       return false;
56453     SDNode *User = *Op->use_begin();
56454     if (!ISD::isNormalStore(User))
56455       return false;
56456     auto *Ld = cast<LoadSDNode>(Load);
56457     auto *St = cast<StoreSDNode>(User);
56458     return Ld->getBasePtr() == St->getBasePtr();
56459   };
56460 
56461   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
56462     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
56463       return false;
56464     if (!Op.hasOneUse())
56465       return false;
56466     SDNode *User = *Op->use_begin();
56467     if (User->getOpcode() != ISD::ATOMIC_STORE)
56468       return false;
56469     auto *Ld = cast<AtomicSDNode>(Load);
56470     auto *St = cast<AtomicSDNode>(User);
56471     return Ld->getBasePtr() == St->getBasePtr();
56472   };
56473 
56474   bool Commute = false;
56475   switch (Op.getOpcode()) {
56476   default: return false;
56477   case ISD::SIGN_EXTEND:
56478   case ISD::ZERO_EXTEND:
56479   case ISD::ANY_EXTEND:
56480     break;
56481   case ISD::SHL:
56482   case ISD::SRA:
56483   case ISD::SRL: {
56484     SDValue N0 = Op.getOperand(0);
56485     // Look out for (store (shl (load), x)).
56486     if (X86::mayFoldLoad(N0, Subtarget) && IsFoldableRMW(N0, Op))
56487       return false;
56488     break;
56489   }
56490   case ISD::ADD:
56491   case ISD::MUL:
56492   case ISD::AND:
56493   case ISD::OR:
56494   case ISD::XOR:
56495     Commute = true;
56496     [[fallthrough]];
56497   case ISD::SUB: {
56498     SDValue N0 = Op.getOperand(0);
56499     SDValue N1 = Op.getOperand(1);
56500     // Avoid disabling potential load folding opportunities.
56501     if (X86::mayFoldLoad(N1, Subtarget) &&
56502         (!Commute || !isa<ConstantSDNode>(N0) ||
56503          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
56504       return false;
56505     if (X86::mayFoldLoad(N0, Subtarget) &&
56506         ((Commute && !isa<ConstantSDNode>(N1)) ||
56507          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
56508       return false;
56509     if (IsFoldableAtomicRMW(N0, Op) ||
56510         (Commute && IsFoldableAtomicRMW(N1, Op)))
56511       return false;
56512   }
56513   }
56514 
56515   PVT = MVT::i32;
56516   return true;
56517 }
56518 
56519 //===----------------------------------------------------------------------===//
56520 //                           X86 Inline Assembly Support
56521 //===----------------------------------------------------------------------===//
56522 
56523 // Helper to match a string separated by whitespace.
matchAsm(StringRef S,ArrayRef<const char * > Pieces)56524 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
56525   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
56526 
56527   for (StringRef Piece : Pieces) {
56528     if (!S.starts_with(Piece)) // Check if the piece matches.
56529       return false;
56530 
56531     S = S.substr(Piece.size());
56532     StringRef::size_type Pos = S.find_first_not_of(" \t");
56533     if (Pos == 0) // We matched a prefix.
56534       return false;
56535 
56536     S = S.substr(Pos);
56537   }
56538 
56539   return S.empty();
56540 }
56541 
clobbersFlagRegisters(const SmallVector<StringRef,4> & AsmPieces)56542 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
56543 
56544   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
56545     if (llvm::is_contained(AsmPieces, "~{cc}") &&
56546         llvm::is_contained(AsmPieces, "~{flags}") &&
56547         llvm::is_contained(AsmPieces, "~{fpsr}")) {
56548 
56549       if (AsmPieces.size() == 3)
56550         return true;
56551       else if (llvm::is_contained(AsmPieces, "~{dirflag}"))
56552         return true;
56553     }
56554   }
56555   return false;
56556 }
56557 
ExpandInlineAsm(CallInst * CI) const56558 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
56559   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
56560 
56561   const std::string &AsmStr = IA->getAsmString();
56562 
56563   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
56564   if (!Ty || Ty->getBitWidth() % 16 != 0)
56565     return false;
56566 
56567   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
56568   SmallVector<StringRef, 4> AsmPieces;
56569   SplitString(AsmStr, AsmPieces, ";\n");
56570 
56571   switch (AsmPieces.size()) {
56572   default: return false;
56573   case 1:
56574     // FIXME: this should verify that we are targeting a 486 or better.  If not,
56575     // we will turn this bswap into something that will be lowered to logical
56576     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
56577     // lower so don't worry about this.
56578     // bswap $0
56579     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
56580         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
56581         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
56582         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
56583         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
56584         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
56585       // No need to check constraints, nothing other than the equivalent of
56586       // "=r,0" would be valid here.
56587       return IntrinsicLowering::LowerToByteSwap(CI);
56588     }
56589 
56590     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
56591     if (CI->getType()->isIntegerTy(16) &&
56592         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
56593         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
56594          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
56595       AsmPieces.clear();
56596       StringRef ConstraintsStr = IA->getConstraintString();
56597       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
56598       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
56599       if (clobbersFlagRegisters(AsmPieces))
56600         return IntrinsicLowering::LowerToByteSwap(CI);
56601     }
56602     break;
56603   case 3:
56604     if (CI->getType()->isIntegerTy(32) &&
56605         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
56606         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
56607         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
56608         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
56609       AsmPieces.clear();
56610       StringRef ConstraintsStr = IA->getConstraintString();
56611       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
56612       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
56613       if (clobbersFlagRegisters(AsmPieces))
56614         return IntrinsicLowering::LowerToByteSwap(CI);
56615     }
56616 
56617     if (CI->getType()->isIntegerTy(64)) {
56618       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
56619       if (Constraints.size() >= 2 &&
56620           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
56621           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
56622         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
56623         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
56624             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
56625             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
56626           return IntrinsicLowering::LowerToByteSwap(CI);
56627       }
56628     }
56629     break;
56630   }
56631   return false;
56632 }
56633 
parseConstraintCode(llvm::StringRef Constraint)56634 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
56635   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
56636                            .Case("{@cca}", X86::COND_A)
56637                            .Case("{@ccae}", X86::COND_AE)
56638                            .Case("{@ccb}", X86::COND_B)
56639                            .Case("{@ccbe}", X86::COND_BE)
56640                            .Case("{@ccc}", X86::COND_B)
56641                            .Case("{@cce}", X86::COND_E)
56642                            .Case("{@ccz}", X86::COND_E)
56643                            .Case("{@ccg}", X86::COND_G)
56644                            .Case("{@ccge}", X86::COND_GE)
56645                            .Case("{@ccl}", X86::COND_L)
56646                            .Case("{@ccle}", X86::COND_LE)
56647                            .Case("{@ccna}", X86::COND_BE)
56648                            .Case("{@ccnae}", X86::COND_B)
56649                            .Case("{@ccnb}", X86::COND_AE)
56650                            .Case("{@ccnbe}", X86::COND_A)
56651                            .Case("{@ccnc}", X86::COND_AE)
56652                            .Case("{@ccne}", X86::COND_NE)
56653                            .Case("{@ccnz}", X86::COND_NE)
56654                            .Case("{@ccng}", X86::COND_LE)
56655                            .Case("{@ccnge}", X86::COND_L)
56656                            .Case("{@ccnl}", X86::COND_GE)
56657                            .Case("{@ccnle}", X86::COND_G)
56658                            .Case("{@ccno}", X86::COND_NO)
56659                            .Case("{@ccnp}", X86::COND_NP)
56660                            .Case("{@ccns}", X86::COND_NS)
56661                            .Case("{@cco}", X86::COND_O)
56662                            .Case("{@ccp}", X86::COND_P)
56663                            .Case("{@ccs}", X86::COND_S)
56664                            .Default(X86::COND_INVALID);
56665   return Cond;
56666 }
56667 
56668 /// Given a constraint letter, return the type of constraint for this target.
56669 X86TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const56670 X86TargetLowering::getConstraintType(StringRef Constraint) const {
56671   if (Constraint.size() == 1) {
56672     switch (Constraint[0]) {
56673     case 'R':
56674     case 'q':
56675     case 'Q':
56676     case 'f':
56677     case 't':
56678     case 'u':
56679     case 'y':
56680     case 'x':
56681     case 'v':
56682     case 'l':
56683     case 'k': // AVX512 masking registers.
56684       return C_RegisterClass;
56685     case 'a':
56686     case 'b':
56687     case 'c':
56688     case 'd':
56689     case 'S':
56690     case 'D':
56691     case 'A':
56692       return C_Register;
56693     case 'I':
56694     case 'J':
56695     case 'K':
56696     case 'N':
56697     case 'G':
56698     case 'L':
56699     case 'M':
56700       return C_Immediate;
56701     case 'C':
56702     case 'e':
56703     case 'Z':
56704       return C_Other;
56705     default:
56706       break;
56707     }
56708   }
56709   else if (Constraint.size() == 2) {
56710     switch (Constraint[0]) {
56711     default:
56712       break;
56713     case 'W':
56714       if (Constraint[1] != 's')
56715         break;
56716       return C_Other;
56717     case 'Y':
56718       switch (Constraint[1]) {
56719       default:
56720         break;
56721       case 'z':
56722         return C_Register;
56723       case 'i':
56724       case 'm':
56725       case 'k':
56726       case 't':
56727       case '2':
56728         return C_RegisterClass;
56729       }
56730     }
56731   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
56732     return C_Other;
56733   return TargetLowering::getConstraintType(Constraint);
56734 }
56735 
56736 /// Examine constraint type and operand type and determine a weight value.
56737 /// This object must already have been set up with the operand type
56738 /// and the current alternative constraint selected.
56739 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & Info,const char * Constraint) const56740 X86TargetLowering::getSingleConstraintMatchWeight(
56741     AsmOperandInfo &Info, const char *Constraint) const {
56742   ConstraintWeight Wt = CW_Invalid;
56743   Value *CallOperandVal = Info.CallOperandVal;
56744   // If we don't have a value, we can't do a match,
56745   // but allow it at the lowest weight.
56746   if (!CallOperandVal)
56747     return CW_Default;
56748   Type *Ty = CallOperandVal->getType();
56749   // Look at the constraint type.
56750   switch (*Constraint) {
56751   default:
56752     Wt = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
56753     [[fallthrough]];
56754   case 'R':
56755   case 'q':
56756   case 'Q':
56757   case 'a':
56758   case 'b':
56759   case 'c':
56760   case 'd':
56761   case 'S':
56762   case 'D':
56763   case 'A':
56764     if (CallOperandVal->getType()->isIntegerTy())
56765       Wt = CW_SpecificReg;
56766     break;
56767   case 'f':
56768   case 't':
56769   case 'u':
56770     if (Ty->isFloatingPointTy())
56771       Wt = CW_SpecificReg;
56772     break;
56773   case 'y':
56774     if (Ty->isX86_MMXTy() && Subtarget.hasMMX())
56775       Wt = CW_SpecificReg;
56776     break;
56777   case 'Y':
56778     if (StringRef(Constraint).size() != 2)
56779       break;
56780     switch (Constraint[1]) {
56781     default:
56782       return CW_Invalid;
56783     // XMM0
56784     case 'z':
56785       if (((Ty->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
56786           ((Ty->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
56787           ((Ty->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
56788         return CW_SpecificReg;
56789       return CW_Invalid;
56790     // Conditional OpMask regs (AVX512)
56791     case 'k':
56792       if ((Ty->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
56793         return CW_Register;
56794       return CW_Invalid;
56795     // Any MMX reg
56796     case 'm':
56797       if (Ty->isX86_MMXTy() && Subtarget.hasMMX())
56798         return Wt;
56799       return CW_Invalid;
56800     // Any SSE reg when ISA >= SSE2, same as 'x'
56801     case 'i':
56802     case 't':
56803     case '2':
56804       if (!Subtarget.hasSSE2())
56805         return CW_Invalid;
56806       break;
56807     }
56808     break;
56809   case 'v':
56810     if ((Ty->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
56811       Wt = CW_Register;
56812     [[fallthrough]];
56813   case 'x':
56814     if (((Ty->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
56815         ((Ty->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
56816       Wt = CW_Register;
56817     break;
56818   case 'k':
56819     // Enable conditional vector operations using %k<#> registers.
56820     if ((Ty->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
56821       Wt = CW_Register;
56822     break;
56823   case 'I':
56824     if (auto *C = dyn_cast<ConstantInt>(Info.CallOperandVal))
56825       if (C->getZExtValue() <= 31)
56826         Wt = CW_Constant;
56827     break;
56828   case 'J':
56829     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56830       if (C->getZExtValue() <= 63)
56831         Wt = CW_Constant;
56832     break;
56833   case 'K':
56834     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56835       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
56836         Wt = CW_Constant;
56837     break;
56838   case 'L':
56839     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56840       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
56841         Wt = CW_Constant;
56842     break;
56843   case 'M':
56844     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56845       if (C->getZExtValue() <= 3)
56846         Wt = CW_Constant;
56847     break;
56848   case 'N':
56849     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56850       if (C->getZExtValue() <= 0xff)
56851         Wt = CW_Constant;
56852     break;
56853   case 'G':
56854   case 'C':
56855     if (isa<ConstantFP>(CallOperandVal))
56856       Wt = CW_Constant;
56857     break;
56858   case 'e':
56859     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56860       if ((C->getSExtValue() >= -0x80000000LL) &&
56861           (C->getSExtValue() <= 0x7fffffffLL))
56862         Wt = CW_Constant;
56863     break;
56864   case 'Z':
56865     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
56866       if (C->getZExtValue() <= 0xffffffff)
56867         Wt = CW_Constant;
56868     break;
56869   }
56870   return Wt;
56871 }
56872 
56873 /// Try to replace an X constraint, which matches anything, with another that
56874 /// has more specific requirements based on the type of the corresponding
56875 /// operand.
56876 const char *X86TargetLowering::
LowerXConstraint(EVT ConstraintVT) const56877 LowerXConstraint(EVT ConstraintVT) const {
56878   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
56879   // 'f' like normal targets.
56880   if (ConstraintVT.isFloatingPoint()) {
56881     if (Subtarget.hasSSE1())
56882       return "x";
56883   }
56884 
56885   return TargetLowering::LowerXConstraint(ConstraintVT);
56886 }
56887 
56888 // Lower @cc targets via setcc.
LowerAsmOutputForConstraint(SDValue & Chain,SDValue & Glue,const SDLoc & DL,const AsmOperandInfo & OpInfo,SelectionDAG & DAG) const56889 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
56890     SDValue &Chain, SDValue &Glue, const SDLoc &DL,
56891     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
56892   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
56893   if (Cond == X86::COND_INVALID)
56894     return SDValue();
56895   // Check that return type is valid.
56896   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
56897       OpInfo.ConstraintVT.getSizeInBits() < 8)
56898     report_fatal_error("Glue output operand is of invalid type");
56899 
56900   // Get EFLAGS register. Only update chain when copyfrom is glued.
56901   if (Glue.getNode()) {
56902     Glue = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Glue);
56903     Chain = Glue.getValue(1);
56904   } else
56905     Glue = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
56906   // Extract CC code.
56907   SDValue CC = getSETCC(Cond, Glue, DL, DAG);
56908   // Extend to 32-bits
56909   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
56910 
56911   return Result;
56912 }
56913 
56914 /// Lower the specified operand into the Ops vector.
56915 /// If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,StringRef Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const56916 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
56917                                                      StringRef Constraint,
56918                                                      std::vector<SDValue> &Ops,
56919                                                      SelectionDAG &DAG) const {
56920   SDValue Result;
56921   char ConstraintLetter = Constraint[0];
56922   switch (ConstraintLetter) {
56923   default: break;
56924   case 'I':
56925     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56926       if (C->getZExtValue() <= 31) {
56927         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
56928                                        Op.getValueType());
56929         break;
56930       }
56931     }
56932     return;
56933   case 'J':
56934     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56935       if (C->getZExtValue() <= 63) {
56936         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
56937                                        Op.getValueType());
56938         break;
56939       }
56940     }
56941     return;
56942   case 'K':
56943     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56944       if (isInt<8>(C->getSExtValue())) {
56945         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
56946                                        Op.getValueType());
56947         break;
56948       }
56949     }
56950     return;
56951   case 'L':
56952     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56953       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
56954           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
56955         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
56956                                        Op.getValueType());
56957         break;
56958       }
56959     }
56960     return;
56961   case 'M':
56962     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56963       if (C->getZExtValue() <= 3) {
56964         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
56965                                        Op.getValueType());
56966         break;
56967       }
56968     }
56969     return;
56970   case 'N':
56971     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56972       if (C->getZExtValue() <= 255) {
56973         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
56974                                        Op.getValueType());
56975         break;
56976       }
56977     }
56978     return;
56979   case 'O':
56980     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56981       if (C->getZExtValue() <= 127) {
56982         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
56983                                        Op.getValueType());
56984         break;
56985       }
56986     }
56987     return;
56988   case 'e': {
56989     // 32-bit signed value
56990     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
56991       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
56992                                            C->getSExtValue())) {
56993         // Widen to 64 bits here to get it sign extended.
56994         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
56995         break;
56996       }
56997     // FIXME gcc accepts some relocatable values here too, but only in certain
56998     // memory models; it's complicated.
56999     }
57000     return;
57001   }
57002   case 'W': {
57003     assert(Constraint[1] == 's');
57004     // Op is a BlockAddressSDNode or a GlobalAddressSDNode with an optional
57005     // offset.
57006     if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
57007       Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
57008                                               BA->getValueType(0)));
57009     } else {
57010       int64_t Offset = 0;
57011       if (Op->getOpcode() == ISD::ADD &&
57012           isa<ConstantSDNode>(Op->getOperand(1))) {
57013         Offset = cast<ConstantSDNode>(Op->getOperand(1))->getSExtValue();
57014         Op = Op->getOperand(0);
57015       }
57016       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
57017         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
57018                                                  GA->getValueType(0), Offset));
57019     }
57020     return;
57021   }
57022   case 'Z': {
57023     // 32-bit unsigned value
57024     if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
57025       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
57026                                            C->getZExtValue())) {
57027         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
57028                                        Op.getValueType());
57029         break;
57030       }
57031     }
57032     // FIXME gcc accepts some relocatable values here too, but only in certain
57033     // memory models; it's complicated.
57034     return;
57035   }
57036   case 'i': {
57037     // Literal immediates are always ok.
57038     if (auto *CST = dyn_cast<ConstantSDNode>(Op)) {
57039       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
57040       BooleanContent BCont = getBooleanContents(MVT::i64);
57041       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
57042                                     : ISD::SIGN_EXTEND;
57043       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
57044                                                   : CST->getSExtValue();
57045       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
57046       break;
57047     }
57048 
57049     // In any sort of PIC mode addresses need to be computed at runtime by
57050     // adding in a register or some sort of table lookup.  These can't
57051     // be used as immediates. BlockAddresses and BasicBlocks are fine though.
57052     if ((Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC()) &&
57053         !(isa<BlockAddressSDNode>(Op) || isa<BasicBlockSDNode>(Op)))
57054       return;
57055 
57056     // If we are in non-pic codegen mode, we allow the address of a global (with
57057     // an optional displacement) to be used with 'i'.
57058     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
57059       // If we require an extra load to get this address, as in PIC mode, we
57060       // can't accept it.
57061       if (isGlobalStubReference(
57062               Subtarget.classifyGlobalReference(GA->getGlobal())))
57063         return;
57064     break;
57065   }
57066   }
57067 
57068   if (Result.getNode()) {
57069     Ops.push_back(Result);
57070     return;
57071   }
57072   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
57073 }
57074 
57075 /// Check if \p RC is a general purpose register class.
57076 /// I.e., GR* or one of their variant.
isGRClass(const TargetRegisterClass & RC)57077 static bool isGRClass(const TargetRegisterClass &RC) {
57078   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
57079          RC.hasSuperClassEq(&X86::GR16RegClass) ||
57080          RC.hasSuperClassEq(&X86::GR32RegClass) ||
57081          RC.hasSuperClassEq(&X86::GR64RegClass) ||
57082          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
57083 }
57084 
57085 /// Check if \p RC is a vector register class.
57086 /// I.e., FR* / VR* or one of their variant.
isFRClass(const TargetRegisterClass & RC)57087 static bool isFRClass(const TargetRegisterClass &RC) {
57088   return RC.hasSuperClassEq(&X86::FR16XRegClass) ||
57089          RC.hasSuperClassEq(&X86::FR32XRegClass) ||
57090          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
57091          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
57092          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
57093          RC.hasSuperClassEq(&X86::VR512RegClass);
57094 }
57095 
57096 /// Check if \p RC is a mask register class.
57097 /// I.e., VK* or one of their variant.
isVKClass(const TargetRegisterClass & RC)57098 static bool isVKClass(const TargetRegisterClass &RC) {
57099   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
57100          RC.hasSuperClassEq(&X86::VK2RegClass) ||
57101          RC.hasSuperClassEq(&X86::VK4RegClass) ||
57102          RC.hasSuperClassEq(&X86::VK8RegClass) ||
57103          RC.hasSuperClassEq(&X86::VK16RegClass) ||
57104          RC.hasSuperClassEq(&X86::VK32RegClass) ||
57105          RC.hasSuperClassEq(&X86::VK64RegClass);
57106 }
57107 
57108 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const57109 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
57110                                                 StringRef Constraint,
57111                                                 MVT VT) const {
57112   // First, see if this is a constraint that directly corresponds to an LLVM
57113   // register class.
57114   if (Constraint.size() == 1) {
57115     // GCC Constraint Letters
57116     switch (Constraint[0]) {
57117     default: break;
57118     // 'A' means [ER]AX + [ER]DX.
57119     case 'A':
57120       if (Subtarget.is64Bit())
57121         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
57122       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
57123              "Expecting 64, 32 or 16 bit subtarget");
57124       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
57125 
57126       // TODO: Slight differences here in allocation order and leaving
57127       // RIP in the class. Do they matter any more here than they do
57128       // in the normal allocation?
57129     case 'k':
57130       if (Subtarget.hasAVX512()) {
57131         if (VT == MVT::v1i1 || VT == MVT::i1)
57132           return std::make_pair(0U, &X86::VK1RegClass);
57133         if (VT == MVT::v8i1 || VT == MVT::i8)
57134           return std::make_pair(0U, &X86::VK8RegClass);
57135         if (VT == MVT::v16i1 || VT == MVT::i16)
57136           return std::make_pair(0U, &X86::VK16RegClass);
57137       }
57138       if (Subtarget.hasBWI()) {
57139         if (VT == MVT::v32i1 || VT == MVT::i32)
57140           return std::make_pair(0U, &X86::VK32RegClass);
57141         if (VT == MVT::v64i1 || VT == MVT::i64)
57142           return std::make_pair(0U, &X86::VK64RegClass);
57143       }
57144       break;
57145     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
57146       if (Subtarget.is64Bit()) {
57147         if (VT == MVT::i8 || VT == MVT::i1)
57148           return std::make_pair(0U, &X86::GR8_NOREX2RegClass);
57149         if (VT == MVT::i16)
57150           return std::make_pair(0U, &X86::GR16_NOREX2RegClass);
57151         if (VT == MVT::i32 || VT == MVT::f32)
57152           return std::make_pair(0U, &X86::GR32_NOREX2RegClass);
57153         if (VT != MVT::f80 && !VT.isVector())
57154           return std::make_pair(0U, &X86::GR64_NOREX2RegClass);
57155         break;
57156       }
57157       [[fallthrough]];
57158       // 32-bit fallthrough
57159     case 'Q':   // Q_REGS
57160       if (VT == MVT::i8 || VT == MVT::i1)
57161         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
57162       if (VT == MVT::i16)
57163         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
57164       if (VT == MVT::i32 || VT == MVT::f32 ||
57165           (!VT.isVector() && !Subtarget.is64Bit()))
57166         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
57167       if (VT != MVT::f80 && !VT.isVector())
57168         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
57169       break;
57170     case 'r':   // GENERAL_REGS
57171     case 'l':   // INDEX_REGS
57172       if (VT == MVT::i8 || VT == MVT::i1)
57173         return std::make_pair(0U, &X86::GR8_NOREX2RegClass);
57174       if (VT == MVT::i16)
57175         return std::make_pair(0U, &X86::GR16_NOREX2RegClass);
57176       if (VT == MVT::i32 || VT == MVT::f32 ||
57177           (!VT.isVector() && !Subtarget.is64Bit()))
57178         return std::make_pair(0U, &X86::GR32_NOREX2RegClass);
57179       if (VT != MVT::f80 && !VT.isVector())
57180         return std::make_pair(0U, &X86::GR64_NOREX2RegClass);
57181       break;
57182     case 'R':   // LEGACY_REGS
57183       if (VT == MVT::i8 || VT == MVT::i1)
57184         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
57185       if (VT == MVT::i16)
57186         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
57187       if (VT == MVT::i32 || VT == MVT::f32 ||
57188           (!VT.isVector() && !Subtarget.is64Bit()))
57189         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
57190       if (VT != MVT::f80 && !VT.isVector())
57191         return std::make_pair(0U, &X86::GR64_NOREXRegClass);
57192       break;
57193     case 'f':  // FP Stack registers.
57194       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
57195       // value to the correct fpstack register class.
57196       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
57197         return std::make_pair(0U, &X86::RFP32RegClass);
57198       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
57199         return std::make_pair(0U, &X86::RFP64RegClass);
57200       if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
57201         return std::make_pair(0U, &X86::RFP80RegClass);
57202       break;
57203     case 'y':   // MMX_REGS if MMX allowed.
57204       if (!Subtarget.hasMMX()) break;
57205       return std::make_pair(0U, &X86::VR64RegClass);
57206     case 'v':
57207     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
57208       if (!Subtarget.hasSSE1()) break;
57209       bool VConstraint = (Constraint[0] == 'v');
57210 
57211       switch (VT.SimpleTy) {
57212       default: break;
57213       // Scalar SSE types.
57214       case MVT::f16:
57215         if (VConstraint && Subtarget.hasFP16())
57216           return std::make_pair(0U, &X86::FR16XRegClass);
57217         break;
57218       case MVT::f32:
57219       case MVT::i32:
57220         if (VConstraint && Subtarget.hasVLX())
57221           return std::make_pair(0U, &X86::FR32XRegClass);
57222         return std::make_pair(0U, &X86::FR32RegClass);
57223       case MVT::f64:
57224       case MVT::i64:
57225         if (VConstraint && Subtarget.hasVLX())
57226           return std::make_pair(0U, &X86::FR64XRegClass);
57227         return std::make_pair(0U, &X86::FR64RegClass);
57228       case MVT::i128:
57229         if (Subtarget.is64Bit()) {
57230           if (VConstraint && Subtarget.hasVLX())
57231             return std::make_pair(0U, &X86::VR128XRegClass);
57232           return std::make_pair(0U, &X86::VR128RegClass);
57233         }
57234         break;
57235       // Vector types and fp128.
57236       case MVT::v8f16:
57237         if (!Subtarget.hasFP16())
57238           break;
57239         if (VConstraint)
57240           return std::make_pair(0U, &X86::VR128XRegClass);
57241         return std::make_pair(0U, &X86::VR128RegClass);
57242       case MVT::v8bf16:
57243         if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
57244           break;
57245         if (VConstraint)
57246           return std::make_pair(0U, &X86::VR128XRegClass);
57247         return std::make_pair(0U, &X86::VR128RegClass);
57248       case MVT::f128:
57249       case MVT::v16i8:
57250       case MVT::v8i16:
57251       case MVT::v4i32:
57252       case MVT::v2i64:
57253       case MVT::v4f32:
57254       case MVT::v2f64:
57255         if (VConstraint && Subtarget.hasVLX())
57256           return std::make_pair(0U, &X86::VR128XRegClass);
57257         return std::make_pair(0U, &X86::VR128RegClass);
57258       // AVX types.
57259       case MVT::v16f16:
57260         if (!Subtarget.hasFP16())
57261           break;
57262         if (VConstraint)
57263           return std::make_pair(0U, &X86::VR256XRegClass);
57264         return std::make_pair(0U, &X86::VR256RegClass);
57265       case MVT::v16bf16:
57266         if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
57267           break;
57268         if (VConstraint)
57269           return std::make_pair(0U, &X86::VR256XRegClass);
57270         return std::make_pair(0U, &X86::VR256RegClass);
57271       case MVT::v32i8:
57272       case MVT::v16i16:
57273       case MVT::v8i32:
57274       case MVT::v4i64:
57275       case MVT::v8f32:
57276       case MVT::v4f64:
57277         if (VConstraint && Subtarget.hasVLX())
57278           return std::make_pair(0U, &X86::VR256XRegClass);
57279         if (Subtarget.hasAVX())
57280           return std::make_pair(0U, &X86::VR256RegClass);
57281         break;
57282       case MVT::v32f16:
57283         if (!Subtarget.hasFP16())
57284           break;
57285         if (VConstraint)
57286           return std::make_pair(0U, &X86::VR512RegClass);
57287         return std::make_pair(0U, &X86::VR512_0_15RegClass);
57288       case MVT::v32bf16:
57289         if (!Subtarget.hasBF16())
57290           break;
57291         if (VConstraint)
57292           return std::make_pair(0U, &X86::VR512RegClass);
57293         return std::make_pair(0U, &X86::VR512_0_15RegClass);
57294       case MVT::v64i8:
57295       case MVT::v32i16:
57296       case MVT::v8f64:
57297       case MVT::v16f32:
57298       case MVT::v16i32:
57299       case MVT::v8i64:
57300         if (!Subtarget.hasAVX512()) break;
57301         if (VConstraint)
57302           return std::make_pair(0U, &X86::VR512RegClass);
57303         return std::make_pair(0U, &X86::VR512_0_15RegClass);
57304       }
57305       break;
57306     }
57307   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
57308     switch (Constraint[1]) {
57309     default:
57310       break;
57311     case 'i':
57312     case 't':
57313     case '2':
57314       return getRegForInlineAsmConstraint(TRI, "x", VT);
57315     case 'm':
57316       if (!Subtarget.hasMMX()) break;
57317       return std::make_pair(0U, &X86::VR64RegClass);
57318     case 'z':
57319       if (!Subtarget.hasSSE1()) break;
57320       switch (VT.SimpleTy) {
57321       default: break;
57322       // Scalar SSE types.
57323       case MVT::f16:
57324         if (!Subtarget.hasFP16())
57325           break;
57326         return std::make_pair(X86::XMM0, &X86::FR16XRegClass);
57327       case MVT::f32:
57328       case MVT::i32:
57329         return std::make_pair(X86::XMM0, &X86::FR32RegClass);
57330       case MVT::f64:
57331       case MVT::i64:
57332         return std::make_pair(X86::XMM0, &X86::FR64RegClass);
57333       case MVT::v8f16:
57334         if (!Subtarget.hasFP16())
57335           break;
57336         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
57337       case MVT::v8bf16:
57338         if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
57339           break;
57340         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
57341       case MVT::f128:
57342       case MVT::v16i8:
57343       case MVT::v8i16:
57344       case MVT::v4i32:
57345       case MVT::v2i64:
57346       case MVT::v4f32:
57347       case MVT::v2f64:
57348         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
57349       // AVX types.
57350       case MVT::v16f16:
57351         if (!Subtarget.hasFP16())
57352           break;
57353         return std::make_pair(X86::YMM0, &X86::VR256RegClass);
57354       case MVT::v16bf16:
57355         if (!Subtarget.hasBF16() || !Subtarget.hasVLX())
57356           break;
57357         return std::make_pair(X86::YMM0, &X86::VR256RegClass);
57358       case MVT::v32i8:
57359       case MVT::v16i16:
57360       case MVT::v8i32:
57361       case MVT::v4i64:
57362       case MVT::v8f32:
57363       case MVT::v4f64:
57364         if (Subtarget.hasAVX())
57365           return std::make_pair(X86::YMM0, &X86::VR256RegClass);
57366         break;
57367       case MVT::v32f16:
57368         if (!Subtarget.hasFP16())
57369           break;
57370         return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
57371       case MVT::v32bf16:
57372         if (!Subtarget.hasBF16())
57373           break;
57374         return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
57375       case MVT::v64i8:
57376       case MVT::v32i16:
57377       case MVT::v8f64:
57378       case MVT::v16f32:
57379       case MVT::v16i32:
57380       case MVT::v8i64:
57381         if (Subtarget.hasAVX512())
57382           return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
57383         break;
57384       }
57385       break;
57386     case 'k':
57387       // This register class doesn't allocate k0 for masked vector operation.
57388       if (Subtarget.hasAVX512()) {
57389         if (VT == MVT::v1i1 || VT == MVT::i1)
57390           return std::make_pair(0U, &X86::VK1WMRegClass);
57391         if (VT == MVT::v8i1 || VT == MVT::i8)
57392           return std::make_pair(0U, &X86::VK8WMRegClass);
57393         if (VT == MVT::v16i1 || VT == MVT::i16)
57394           return std::make_pair(0U, &X86::VK16WMRegClass);
57395       }
57396       if (Subtarget.hasBWI()) {
57397         if (VT == MVT::v32i1 || VT == MVT::i32)
57398           return std::make_pair(0U, &X86::VK32WMRegClass);
57399         if (VT == MVT::v64i1 || VT == MVT::i64)
57400           return std::make_pair(0U, &X86::VK64WMRegClass);
57401       }
57402       break;
57403     }
57404   }
57405 
57406   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
57407     return std::make_pair(0U, &X86::GR32RegClass);
57408 
57409   // Use the default implementation in TargetLowering to convert the register
57410   // constraint into a member of a register class.
57411   std::pair<Register, const TargetRegisterClass*> Res;
57412   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
57413 
57414   // Not found as a standard register?
57415   if (!Res.second) {
57416     // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
57417     // to/from f80.
57418     if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
57419       // Map st(0) -> st(7) -> ST0
57420       if (Constraint.size() == 7 && Constraint[0] == '{' &&
57421           tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
57422           Constraint[3] == '(' &&
57423           (Constraint[4] >= '0' && Constraint[4] <= '7') &&
57424           Constraint[5] == ')' && Constraint[6] == '}') {
57425         // st(7) is not allocatable and thus not a member of RFP80. Return
57426         // singleton class in cases where we have a reference to it.
57427         if (Constraint[4] == '7')
57428           return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
57429         return std::make_pair(X86::FP0 + Constraint[4] - '0',
57430                               &X86::RFP80RegClass);
57431       }
57432 
57433       // GCC allows "st(0)" to be called just plain "st".
57434       if (StringRef("{st}").equals_insensitive(Constraint))
57435         return std::make_pair(X86::FP0, &X86::RFP80RegClass);
57436     }
57437 
57438     // flags -> EFLAGS
57439     if (StringRef("{flags}").equals_insensitive(Constraint))
57440       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
57441 
57442     // dirflag -> DF
57443     // Only allow for clobber.
57444     if (StringRef("{dirflag}").equals_insensitive(Constraint) &&
57445         VT == MVT::Other)
57446       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
57447 
57448     // fpsr -> FPSW
57449     // Only allow for clobber.
57450     if (StringRef("{fpsr}").equals_insensitive(Constraint) && VT == MVT::Other)
57451       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
57452 
57453     return Res;
57454   }
57455 
57456   // Make sure it isn't a register that requires 64-bit mode.
57457   if (!Subtarget.is64Bit() &&
57458       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
57459       TRI->getEncodingValue(Res.first) >= 8) {
57460     // Register requires REX prefix, but we're in 32-bit mode.
57461     return std::make_pair(0, nullptr);
57462   }
57463 
57464   // Make sure it isn't a register that requires AVX512.
57465   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
57466       TRI->getEncodingValue(Res.first) & 0x10) {
57467     // Register requires EVEX prefix.
57468     return std::make_pair(0, nullptr);
57469   }
57470 
57471   // Otherwise, check to see if this is a register class of the wrong value
57472   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
57473   // turn into {ax},{dx}.
57474   // MVT::Other is used to specify clobber names.
57475   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
57476     return Res;   // Correct type already, nothing to do.
57477 
57478   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
57479   // return "eax". This should even work for things like getting 64bit integer
57480   // registers when given an f64 type.
57481   const TargetRegisterClass *Class = Res.second;
57482   // The generic code will match the first register class that contains the
57483   // given register. Thus, based on the ordering of the tablegened file,
57484   // the "plain" GR classes might not come first.
57485   // Therefore, use a helper method.
57486   if (isGRClass(*Class)) {
57487     unsigned Size = VT.getSizeInBits();
57488     if (Size == 1) Size = 8;
57489     if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
57490       return std::make_pair(0, nullptr);
57491     Register DestReg = getX86SubSuperRegister(Res.first, Size);
57492     if (DestReg.isValid()) {
57493       bool is64Bit = Subtarget.is64Bit();
57494       const TargetRegisterClass *RC =
57495           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
57496         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
57497         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
57498         : /*Size == 64*/ (is64Bit ? &X86::GR64RegClass : nullptr);
57499       if (Size == 64 && !is64Bit) {
57500         // Model GCC's behavior here and select a fixed pair of 32-bit
57501         // registers.
57502         switch (DestReg) {
57503         case X86::RAX:
57504           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
57505         case X86::RDX:
57506           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
57507         case X86::RCX:
57508           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
57509         case X86::RBX:
57510           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
57511         case X86::RSI:
57512           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
57513         case X86::RDI:
57514           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
57515         case X86::RBP:
57516           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
57517         default:
57518           return std::make_pair(0, nullptr);
57519         }
57520       }
57521       if (RC && RC->contains(DestReg))
57522         return std::make_pair(DestReg, RC);
57523       return Res;
57524     }
57525     // No register found/type mismatch.
57526     return std::make_pair(0, nullptr);
57527   } else if (isFRClass(*Class)) {
57528     // Handle references to XMM physical registers that got mapped into the
57529     // wrong class.  This can happen with constraints like {xmm0} where the
57530     // target independent register mapper will just pick the first match it can
57531     // find, ignoring the required type.
57532 
57533     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
57534     if (VT == MVT::f16)
57535       Res.second = &X86::FR16XRegClass;
57536     else if (VT == MVT::f32 || VT == MVT::i32)
57537       Res.second = &X86::FR32XRegClass;
57538     else if (VT == MVT::f64 || VT == MVT::i64)
57539       Res.second = &X86::FR64XRegClass;
57540     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
57541       Res.second = &X86::VR128XRegClass;
57542     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
57543       Res.second = &X86::VR256XRegClass;
57544     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
57545       Res.second = &X86::VR512RegClass;
57546     else {
57547       // Type mismatch and not a clobber: Return an error;
57548       Res.first = 0;
57549       Res.second = nullptr;
57550     }
57551   } else if (isVKClass(*Class)) {
57552     if (VT == MVT::v1i1 || VT == MVT::i1)
57553       Res.second = &X86::VK1RegClass;
57554     else if (VT == MVT::v8i1 || VT == MVT::i8)
57555       Res.second = &X86::VK8RegClass;
57556     else if (VT == MVT::v16i1 || VT == MVT::i16)
57557       Res.second = &X86::VK16RegClass;
57558     else if (VT == MVT::v32i1 || VT == MVT::i32)
57559       Res.second = &X86::VK32RegClass;
57560     else if (VT == MVT::v64i1 || VT == MVT::i64)
57561       Res.second = &X86::VK64RegClass;
57562     else {
57563       // Type mismatch and not a clobber: Return an error;
57564       Res.first = 0;
57565       Res.second = nullptr;
57566     }
57567   }
57568 
57569   return Res;
57570 }
57571 
isIntDivCheap(EVT VT,AttributeList Attr) const57572 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
57573   // Integer division on x86 is expensive. However, when aggressively optimizing
57574   // for code size, we prefer to use a div instruction, as it is usually smaller
57575   // than the alternative sequence.
57576   // The exception to this is vector division. Since x86 doesn't have vector
57577   // integer division, leaving the division as-is is a loss even in terms of
57578   // size, because it will have to be scalarized, while the alternative code
57579   // sequence can be performed in vector form.
57580   bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
57581   return OptSize && !VT.isVector();
57582 }
57583 
initializeSplitCSR(MachineBasicBlock * Entry) const57584 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
57585   if (!Subtarget.is64Bit())
57586     return;
57587 
57588   // Update IsSplitCSR in X86MachineFunctionInfo.
57589   X86MachineFunctionInfo *AFI =
57590       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
57591   AFI->setIsSplitCSR(true);
57592 }
57593 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const57594 void X86TargetLowering::insertCopiesSplitCSR(
57595     MachineBasicBlock *Entry,
57596     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
57597   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
57598   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
57599   if (!IStart)
57600     return;
57601 
57602   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
57603   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
57604   MachineBasicBlock::iterator MBBI = Entry->begin();
57605   for (const MCPhysReg *I = IStart; *I; ++I) {
57606     const TargetRegisterClass *RC = nullptr;
57607     if (X86::GR64RegClass.contains(*I))
57608       RC = &X86::GR64RegClass;
57609     else
57610       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
57611 
57612     Register NewVR = MRI->createVirtualRegister(RC);
57613     // Create copy from CSR to a virtual register.
57614     // FIXME: this currently does not emit CFI pseudo-instructions, it works
57615     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
57616     // nounwind. If we want to generalize this later, we may need to emit
57617     // CFI pseudo-instructions.
57618     assert(
57619         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
57620         "Function should be nounwind in insertCopiesSplitCSR!");
57621     Entry->addLiveIn(*I);
57622     BuildMI(*Entry, MBBI, MIMetadata(), TII->get(TargetOpcode::COPY), NewVR)
57623         .addReg(*I);
57624 
57625     // Insert the copy-back instructions right before the terminator.
57626     for (auto *Exit : Exits)
57627       BuildMI(*Exit, Exit->getFirstTerminator(), MIMetadata(),
57628               TII->get(TargetOpcode::COPY), *I)
57629           .addReg(NewVR);
57630   }
57631 }
57632 
supportSwiftError() const57633 bool X86TargetLowering::supportSwiftError() const {
57634   return Subtarget.is64Bit();
57635 }
57636 
57637 MachineInstr *
EmitKCFICheck(MachineBasicBlock & MBB,MachineBasicBlock::instr_iterator & MBBI,const TargetInstrInfo * TII) const57638 X86TargetLowering::EmitKCFICheck(MachineBasicBlock &MBB,
57639                                  MachineBasicBlock::instr_iterator &MBBI,
57640                                  const TargetInstrInfo *TII) const {
57641   assert(MBBI->isCall() && MBBI->getCFIType() &&
57642          "Invalid call instruction for a KCFI check");
57643 
57644   MachineFunction &MF = *MBB.getParent();
57645   // If the call target is a memory operand, unfold it and use R11 for the
57646   // call, so KCFI_CHECK won't have to recompute the address.
57647   switch (MBBI->getOpcode()) {
57648   case X86::CALL64m:
57649   case X86::CALL64m_NT:
57650   case X86::TAILJMPm64:
57651   case X86::TAILJMPm64_REX: {
57652     MachineBasicBlock::instr_iterator OrigCall = MBBI;
57653     SmallVector<MachineInstr *, 2> NewMIs;
57654     if (!TII->unfoldMemoryOperand(MF, *OrigCall, X86::R11, /*UnfoldLoad=*/true,
57655                                   /*UnfoldStore=*/false, NewMIs))
57656       report_fatal_error("Failed to unfold memory operand for a KCFI check");
57657     for (auto *NewMI : NewMIs)
57658       MBBI = MBB.insert(OrigCall, NewMI);
57659     assert(MBBI->isCall() &&
57660            "Unexpected instruction after memory operand unfolding");
57661     if (OrigCall->shouldUpdateCallSiteInfo())
57662       MF.moveCallSiteInfo(&*OrigCall, &*MBBI);
57663     MBBI->setCFIType(MF, OrigCall->getCFIType());
57664     OrigCall->eraseFromParent();
57665     break;
57666   }
57667   default:
57668     break;
57669   }
57670 
57671   MachineOperand &Target = MBBI->getOperand(0);
57672   Register TargetReg;
57673   switch (MBBI->getOpcode()) {
57674   case X86::CALL64r:
57675   case X86::CALL64r_NT:
57676   case X86::TAILJMPr64:
57677   case X86::TAILJMPr64_REX:
57678     assert(Target.isReg() && "Unexpected target operand for an indirect call");
57679     Target.setIsRenamable(false);
57680     TargetReg = Target.getReg();
57681     break;
57682   case X86::CALL64pcrel32:
57683   case X86::TAILJMPd64:
57684     assert(Target.isSymbol() && "Unexpected target operand for a direct call");
57685     // X86TargetLowering::EmitLoweredIndirectThunk always uses r11 for
57686     // 64-bit indirect thunk calls.
57687     assert(StringRef(Target.getSymbolName()).ends_with("_r11") &&
57688            "Unexpected register for an indirect thunk call");
57689     TargetReg = X86::R11;
57690     break;
57691   default:
57692     llvm_unreachable("Unexpected CFI call opcode");
57693     break;
57694   }
57695 
57696   return BuildMI(MBB, MBBI, MIMetadata(*MBBI), TII->get(X86::KCFI_CHECK))
57697       .addReg(TargetReg)
57698       .addImm(MBBI->getCFIType())
57699       .getInstr();
57700 }
57701 
57702 /// Returns true if stack probing through a function call is requested.
hasStackProbeSymbol(const MachineFunction & MF) const57703 bool X86TargetLowering::hasStackProbeSymbol(const MachineFunction &MF) const {
57704   return !getStackProbeSymbolName(MF).empty();
57705 }
57706 
57707 /// Returns true if stack probing through inline assembly is requested.
hasInlineStackProbe(const MachineFunction & MF) const57708 bool X86TargetLowering::hasInlineStackProbe(const MachineFunction &MF) const {
57709 
57710   // No inline stack probe for Windows, they have their own mechanism.
57711   if (Subtarget.isOSWindows() ||
57712       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
57713     return false;
57714 
57715   // If the function specifically requests inline stack probes, emit them.
57716   if (MF.getFunction().hasFnAttribute("probe-stack"))
57717     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
57718            "inline-asm";
57719 
57720   return false;
57721 }
57722 
57723 /// Returns the name of the symbol used to emit stack probes or the empty
57724 /// string if not applicable.
57725 StringRef
getStackProbeSymbolName(const MachineFunction & MF) const57726 X86TargetLowering::getStackProbeSymbolName(const MachineFunction &MF) const {
57727   // Inline Stack probes disable stack probe call
57728   if (hasInlineStackProbe(MF))
57729     return "";
57730 
57731   // If the function specifically requests stack probes, emit them.
57732   if (MF.getFunction().hasFnAttribute("probe-stack"))
57733     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
57734 
57735   // Generally, if we aren't on Windows, the platform ABI does not include
57736   // support for stack probes, so don't emit them.
57737   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
57738       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
57739     return "";
57740 
57741   // We need a stack probe to conform to the Windows ABI. Choose the right
57742   // symbol.
57743   if (Subtarget.is64Bit())
57744     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
57745   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
57746 }
57747 
57748 unsigned
getStackProbeSize(const MachineFunction & MF) const57749 X86TargetLowering::getStackProbeSize(const MachineFunction &MF) const {
57750   // The default stack probe size is 4096 if the function has no stackprobesize
57751   // attribute.
57752   return MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size",
57753                                                         4096);
57754 }
57755 
getPrefLoopAlignment(MachineLoop * ML) const57756 Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
57757   if (ML && ML->isInnermost() &&
57758       ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
57759     return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
57760   return TargetLowering::getPrefLoopAlignment();
57761 }
57762