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/EHPersonalities.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/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/TargetLowering.h"
41 #include "llvm/CodeGen/WinEHFuncInfo.h"
42 #include "llvm/IR/CallingConv.h"
43 #include "llvm/IR/Constants.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/DiagnosticInfo.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/GlobalAlias.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCContext.h"
53 #include "llvm/MC/MCExpr.h"
54 #include "llvm/MC/MCSymbol.h"
55 #include "llvm/Support/CommandLine.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/KnownBits.h"
59 #include "llvm/Support/MathExtras.h"
60 #include "llvm/Target/TargetOptions.h"
61 #include <algorithm>
62 #include <bitset>
63 #include <cctype>
64 #include <numeric>
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "x86-isel"
68 
69 STATISTIC(NumTailCalls, "Number of tail calls");
70 
71 static cl::opt<int> ExperimentalPrefLoopAlignment(
72     "x86-experimental-pref-loop-alignment", cl::init(4),
73     cl::desc(
74         "Sets the preferable loop alignment for experiments (as log2 bytes)"
75         "(the last x86-experimental-pref-loop-alignment bits"
76         " of the loop header PC will be 0)."),
77     cl::Hidden);
78 
79 static cl::opt<bool> MulConstantOptimization(
80     "mul-constant-optimization", cl::init(true),
81     cl::desc("Replace 'mul x, Const' with more effective instructions like "
82              "SHIFT, LEA, etc."),
83     cl::Hidden);
84 
85 static cl::opt<bool> ExperimentalUnorderedISEL(
86     "x86-experimental-unordered-atomic-isel", cl::init(false),
87     cl::desc("Use LoadSDNode and StoreSDNode instead of "
88              "AtomicSDNode for unordered atomic loads and "
89              "stores respectively."),
90     cl::Hidden);
91 
92 /// Call this when the user attempts to do something unsupported, like
93 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
94 /// report_fatal_error, so calling code should attempt to recover without
95 /// crashing.
errorUnsupported(SelectionDAG & DAG,const SDLoc & dl,const char * Msg)96 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
97                              const char *Msg) {
98   MachineFunction &MF = DAG.getMachineFunction();
99   DAG.getContext()->diagnose(
100       DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
101 }
102 
X86TargetLowering(const X86TargetMachine & TM,const X86Subtarget & STI)103 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
104                                      const X86Subtarget &STI)
105     : TargetLowering(TM), Subtarget(STI) {
106   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
107   X86ScalarSSEf64 = Subtarget.hasSSE2();
108   X86ScalarSSEf32 = Subtarget.hasSSE1();
109   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
110 
111   // Set up the TargetLowering object.
112 
113   // X86 is weird. It always uses i8 for shift amounts and setcc results.
114   setBooleanContents(ZeroOrOneBooleanContent);
115   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
116   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
117 
118   // For 64-bit, since we have so many registers, use the ILP scheduler.
119   // For 32-bit, use the register pressure specific scheduling.
120   // For Atom, always use ILP scheduling.
121   if (Subtarget.isAtom())
122     setSchedulingPreference(Sched::ILP);
123   else if (Subtarget.is64Bit())
124     setSchedulingPreference(Sched::ILP);
125   else
126     setSchedulingPreference(Sched::RegPressure);
127   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
128   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
129 
130   // Bypass expensive divides and use cheaper ones.
131   if (TM.getOptLevel() >= CodeGenOpt::Default) {
132     if (Subtarget.hasSlowDivide32())
133       addBypassSlowDiv(32, 8);
134     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
135       addBypassSlowDiv(64, 32);
136   }
137 
138   if (Subtarget.isTargetWindowsMSVC() ||
139       Subtarget.isTargetWindowsItanium()) {
140     // Setup Windows compiler runtime calls.
141     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
142     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
143     setLibcallName(RTLIB::SREM_I64, "_allrem");
144     setLibcallName(RTLIB::UREM_I64, "_aullrem");
145     setLibcallName(RTLIB::MUL_I64, "_allmul");
146     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
147     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
148     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
149     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
150     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
151   }
152 
153   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
154     // MSVCRT doesn't have powi; fall back to pow
155     setLibcallName(RTLIB::POWI_F32, nullptr);
156     setLibcallName(RTLIB::POWI_F64, nullptr);
157   }
158 
159   // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
160   // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
161   // FIXME: Should we be limiting the atomic size on other configs? Default is
162   // 1024.
163   if (!Subtarget.hasCmpxchg8b())
164     setMaxAtomicSizeInBitsSupported(32);
165 
166   // Set up the register classes.
167   addRegisterClass(MVT::i8, &X86::GR8RegClass);
168   addRegisterClass(MVT::i16, &X86::GR16RegClass);
169   addRegisterClass(MVT::i32, &X86::GR32RegClass);
170   if (Subtarget.is64Bit())
171     addRegisterClass(MVT::i64, &X86::GR64RegClass);
172 
173   for (MVT VT : MVT::integer_valuetypes())
174     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
175 
176   // We don't accept any truncstore of integer registers.
177   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
178   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
179   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
180   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
181   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
182   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
183 
184   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
185 
186   // SETOEQ and SETUNE require checking two conditions.
187   for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
188     setCondCodeAction(ISD::SETOEQ, VT, Expand);
189     setCondCodeAction(ISD::SETUNE, VT, Expand);
190   }
191 
192   // Integer absolute.
193   if (Subtarget.hasCMov()) {
194     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
195     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
196   }
197   setOperationAction(ISD::ABS              , MVT::i64  , Custom);
198 
199   // Funnel shifts.
200   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
201     // For slow shld targets we only lower for code size.
202     LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
203 
204     setOperationAction(ShiftOp             , MVT::i8   , Custom);
205     setOperationAction(ShiftOp             , MVT::i16  , Custom);
206     setOperationAction(ShiftOp             , MVT::i32  , ShiftDoubleAction);
207     if (Subtarget.is64Bit())
208       setOperationAction(ShiftOp           , MVT::i64  , ShiftDoubleAction);
209   }
210 
211   if (!Subtarget.useSoftFloat()) {
212     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
213     // operation.
214     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
215     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
216     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
217     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
218     // We have an algorithm for SSE2, and we turn this into a 64-bit
219     // FILD or VCVTUSI2SS/SD for other targets.
220     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
221     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
222     // We have an algorithm for SSE2->double, and we turn this into a
223     // 64-bit FILD followed by conditional FADD for other targets.
224     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
225     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
226 
227     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
228     // this operation.
229     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
230     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
231     // SSE has no i16 to fp conversion, only i32. We promote in the handler
232     // to allow f80 to use i16 and f64 to use i16 with sse1 only
233     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
234     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
235     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
236     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
237     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
238     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
239     // are Legal, f80 is custom lowered.
240     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
241     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
242 
243     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
244     // this operation.
245     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
246     // FIXME: This doesn't generate invalid exception when it should. PR44019.
247     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
248     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
249     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
250     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
251     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
252     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
253     // are Legal, f80 is custom lowered.
254     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
255     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
256 
257     // Handle FP_TO_UINT by promoting the destination to a larger signed
258     // conversion.
259     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
260     // FIXME: This doesn't generate invalid exception when it should. PR44019.
261     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
262     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
263     // FIXME: This doesn't generate invalid exception when it should. PR44019.
264     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
265     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
266     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
267     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
268     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
269 
270     setOperationAction(ISD::LRINT,             MVT::f32, Custom);
271     setOperationAction(ISD::LRINT,             MVT::f64, Custom);
272     setOperationAction(ISD::LLRINT,            MVT::f32, Custom);
273     setOperationAction(ISD::LLRINT,            MVT::f64, Custom);
274 
275     if (!Subtarget.is64Bit()) {
276       setOperationAction(ISD::LRINT,  MVT::i64, Custom);
277       setOperationAction(ISD::LLRINT, MVT::i64, Custom);
278     }
279   }
280 
281   // Handle address space casts between mixed sized pointers.
282   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
283   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
284 
285   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
286   if (!X86ScalarSSEf64) {
287     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
288     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
289     if (Subtarget.is64Bit()) {
290       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
291       // Without SSE, i64->f64 goes through memory.
292       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
293     }
294   } else if (!Subtarget.is64Bit())
295     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
296 
297   // Scalar integer divide and remainder are lowered to use operations that
298   // produce two results, to match the available instructions. This exposes
299   // the two-result form to trivial CSE, which is able to combine x/y and x%y
300   // into a single instruction.
301   //
302   // Scalar integer multiply-high is also lowered to use two-result
303   // operations, to match the available instructions. However, plain multiply
304   // (low) operations are left as Legal, as there are single-result
305   // instructions for this in x86. Using the two-result multiply instructions
306   // when both high and low results are needed must be arranged by dagcombine.
307   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
308     setOperationAction(ISD::MULHS, VT, Expand);
309     setOperationAction(ISD::MULHU, VT, Expand);
310     setOperationAction(ISD::SDIV, VT, Expand);
311     setOperationAction(ISD::UDIV, VT, Expand);
312     setOperationAction(ISD::SREM, VT, Expand);
313     setOperationAction(ISD::UREM, VT, Expand);
314   }
315 
316   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
317   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
318   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
319                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
320     setOperationAction(ISD::BR_CC,     VT, Expand);
321     setOperationAction(ISD::SELECT_CC, VT, Expand);
322   }
323   if (Subtarget.is64Bit())
324     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
325   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
326   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
327   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
328 
329   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
330   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
331   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
332   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
333   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
334 
335   // Promote the i8 variants and force them on up to i32 which has a shorter
336   // encoding.
337   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
338   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
339   if (!Subtarget.hasBMI()) {
340     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
341     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
342     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Legal);
343     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
344     if (Subtarget.is64Bit()) {
345       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
346       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
347     }
348   }
349 
350   if (Subtarget.hasLZCNT()) {
351     // When promoting the i8 variants, force them to i32 for a shorter
352     // encoding.
353     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
354     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
355   } else {
356     for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
357       if (VT == MVT::i64 && !Subtarget.is64Bit())
358         continue;
359       setOperationAction(ISD::CTLZ           , VT, Custom);
360       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
361     }
362   }
363 
364   for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
365                   ISD::STRICT_FP_TO_FP16}) {
366     // Special handling for half-precision floating point conversions.
367     // If we don't have F16C support, then lower half float conversions
368     // into library calls.
369     setOperationAction(
370         Op, MVT::f32,
371         (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
372     // There's never any support for operations beyond MVT::f32.
373     setOperationAction(Op, MVT::f64, Expand);
374     setOperationAction(Op, MVT::f80, Expand);
375     setOperationAction(Op, MVT::f128, Expand);
376   }
377 
378   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
379   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
380   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
381   setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
382   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
383   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
384   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
385   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
386 
387   if (Subtarget.hasPOPCNT()) {
388     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
389   } else {
390     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
391     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
392     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
393     if (Subtarget.is64Bit())
394       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
395     else
396       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
397   }
398 
399   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
400 
401   if (!Subtarget.hasMOVBE())
402     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
403 
404   // X86 wants to expand cmov itself.
405   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
406     setOperationAction(ISD::SELECT, VT, Custom);
407     setOperationAction(ISD::SETCC, VT, Custom);
408     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
409     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
410   }
411   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
412     if (VT == MVT::i64 && !Subtarget.is64Bit())
413       continue;
414     setOperationAction(ISD::SELECT, VT, Custom);
415     setOperationAction(ISD::SETCC,  VT, Custom);
416   }
417 
418   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
419   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
420   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
421 
422   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
423   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
424   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
425   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
426   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
427   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
428   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
429     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
430 
431   // Darwin ABI issue.
432   for (auto VT : { MVT::i32, MVT::i64 }) {
433     if (VT == MVT::i64 && !Subtarget.is64Bit())
434       continue;
435     setOperationAction(ISD::ConstantPool    , VT, Custom);
436     setOperationAction(ISD::JumpTable       , VT, Custom);
437     setOperationAction(ISD::GlobalAddress   , VT, Custom);
438     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
439     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
440     setOperationAction(ISD::BlockAddress    , VT, Custom);
441   }
442 
443   // 64-bit shl, sra, srl (iff 32-bit x86)
444   for (auto VT : { MVT::i32, MVT::i64 }) {
445     if (VT == MVT::i64 && !Subtarget.is64Bit())
446       continue;
447     setOperationAction(ISD::SHL_PARTS, VT, Custom);
448     setOperationAction(ISD::SRA_PARTS, VT, Custom);
449     setOperationAction(ISD::SRL_PARTS, VT, Custom);
450   }
451 
452   if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
453     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
454 
455   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
456 
457   // Expand certain atomics
458   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
459     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
460     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
461     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
463     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
464     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
465     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
466   }
467 
468   if (!Subtarget.is64Bit())
469     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
470 
471   if (Subtarget.hasCmpxchg16b()) {
472     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
473   }
474 
475   // FIXME - use subtarget debug flags
476   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
477       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
478       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
479     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
480   }
481 
482   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
484 
485   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
486   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
487 
488   setOperationAction(ISD::TRAP, MVT::Other, Legal);
489   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
490 
491   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
492   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
493   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
494   bool Is64Bit = Subtarget.is64Bit();
495   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
496   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
497 
498   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
499   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
500 
501   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
502 
503   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
504   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
505   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
506 
507   if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
508     // f32 and f64 use SSE.
509     // Set up the FP register classes.
510     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
511                                                      : &X86::FR32RegClass);
512     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
513                                                      : &X86::FR64RegClass);
514 
515     // Disable f32->f64 extload as we can only generate this in one instruction
516     // under optsize. So its easier to pattern match (fpext (load)) for that
517     // case instead of needing to emit 2 instructions for extload in the
518     // non-optsize case.
519     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
520 
521     for (auto VT : { MVT::f32, MVT::f64 }) {
522       // Use ANDPD to simulate FABS.
523       setOperationAction(ISD::FABS, VT, Custom);
524 
525       // Use XORP to simulate FNEG.
526       setOperationAction(ISD::FNEG, VT, Custom);
527 
528       // Use ANDPD and ORPD to simulate FCOPYSIGN.
529       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
530 
531       // These might be better off as horizontal vector ops.
532       setOperationAction(ISD::FADD, VT, Custom);
533       setOperationAction(ISD::FSUB, VT, Custom);
534 
535       // We don't support sin/cos/fmod
536       setOperationAction(ISD::FSIN   , VT, Expand);
537       setOperationAction(ISD::FCOS   , VT, Expand);
538       setOperationAction(ISD::FSINCOS, VT, Expand);
539     }
540 
541     // Lower this to MOVMSK plus an AND.
542     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
543     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
544 
545   } else if (!Subtarget.useSoftFloat() && X86ScalarSSEf32 &&
546              (UseX87 || Is64Bit)) {
547     // Use SSE for f32, x87 for f64.
548     // Set up the FP register classes.
549     addRegisterClass(MVT::f32, &X86::FR32RegClass);
550     if (UseX87)
551       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
552 
553     // Use ANDPS to simulate FABS.
554     setOperationAction(ISD::FABS , MVT::f32, Custom);
555 
556     // Use XORP to simulate FNEG.
557     setOperationAction(ISD::FNEG , MVT::f32, Custom);
558 
559     if (UseX87)
560       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
561 
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     if (UseX87)
564       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
565     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566 
567     // We don't support sin/cos/fmod
568     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
569     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
570     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571 
572     if (UseX87) {
573       // Always expand sin/cos functions even though x87 has an instruction.
574       setOperationAction(ISD::FSIN, MVT::f64, Expand);
575       setOperationAction(ISD::FCOS, MVT::f64, Expand);
576       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
577     }
578   } else if (UseX87) {
579     // f32 and f64 in x87.
580     // Set up the FP register classes.
581     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
582     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
583 
584     for (auto VT : { MVT::f32, MVT::f64 }) {
585       setOperationAction(ISD::UNDEF,     VT, Expand);
586       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
587 
588       // Always expand sin/cos functions even though x87 has an instruction.
589       setOperationAction(ISD::FSIN   , VT, Expand);
590       setOperationAction(ISD::FCOS   , VT, Expand);
591       setOperationAction(ISD::FSINCOS, VT, Expand);
592     }
593   }
594 
595   // Expand FP32 immediates into loads from the stack, save special cases.
596   if (isTypeLegal(MVT::f32)) {
597     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
598       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
599       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
600       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
601       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
602     } else // SSE immediates.
603       addLegalFPImmediate(APFloat(+0.0f)); // xorps
604   }
605   // Expand FP64 immediates into loads from the stack, save special cases.
606   if (isTypeLegal(MVT::f64)) {
607     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
608       addLegalFPImmediate(APFloat(+0.0)); // FLD0
609       addLegalFPImmediate(APFloat(+1.0)); // FLD1
610       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
611       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
612     } else // SSE immediates.
613       addLegalFPImmediate(APFloat(+0.0)); // xorpd
614   }
615   // Handle constrained floating-point operations of scalar.
616   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
617   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
618   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
619   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
620   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
621   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
622   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
623   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
624   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
625   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
626   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
627   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
628   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
629 
630   // We don't support FMA.
631   setOperationAction(ISD::FMA, MVT::f64, Expand);
632   setOperationAction(ISD::FMA, MVT::f32, Expand);
633 
634   // f80 always uses X87.
635   if (UseX87) {
636     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
637     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
638     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
639     {
640       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
641       addLegalFPImmediate(TmpFlt);  // FLD0
642       TmpFlt.changeSign();
643       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
644 
645       bool ignored;
646       APFloat TmpFlt2(+1.0);
647       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
648                       &ignored);
649       addLegalFPImmediate(TmpFlt2);  // FLD1
650       TmpFlt2.changeSign();
651       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
652     }
653 
654     // Always expand sin/cos functions even though x87 has an instruction.
655     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
656     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
657     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
658 
659     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
660     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
661     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
662     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
663     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
664     setOperationAction(ISD::FMA, MVT::f80, Expand);
665     setOperationAction(ISD::LROUND, MVT::f80, Expand);
666     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
667     setOperationAction(ISD::LRINT, MVT::f80, Custom);
668     setOperationAction(ISD::LLRINT, MVT::f80, Custom);
669 
670     // Handle constrained floating-point operations of scalar.
671     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
672     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
673     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
674     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
675     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
676     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
677     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
678     // as Custom.
679     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
680   }
681 
682   // f128 uses xmm registers, but most operations require libcalls.
683   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
684     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
685                                                    : &X86::VR128RegClass);
686 
687     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
688 
689     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
690     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
691     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
692     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
693     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
694     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
695     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
696     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
697     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
698     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
699 
700     setOperationAction(ISD::FABS, MVT::f128, Custom);
701     setOperationAction(ISD::FNEG, MVT::f128, Custom);
702     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
703 
704     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
705     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
706     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
707     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
708     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
709     // No STRICT_FSINCOS
710     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
711     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
712 
713     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
714     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
715     // We need to custom handle any FP_ROUND with an f128 input, but
716     // LegalizeDAG uses the result type to know when to run a custom handler.
717     // So we have to list all legal floating point result types here.
718     if (isTypeLegal(MVT::f32)) {
719       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
720       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
721     }
722     if (isTypeLegal(MVT::f64)) {
723       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
724       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
725     }
726     if (isTypeLegal(MVT::f80)) {
727       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
728       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
729     }
730 
731     setOperationAction(ISD::SETCC, MVT::f128, Custom);
732 
733     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
734     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
735     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
736     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
737     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
738     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
739   }
740 
741   // Always use a library call for pow.
742   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
743   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
744   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
745   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
746 
747   setOperationAction(ISD::FLOG, MVT::f80, Expand);
748   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
749   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
750   setOperationAction(ISD::FEXP, MVT::f80, Expand);
751   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
752   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
753   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
754 
755   // Some FP actions are always expanded for vector types.
756   for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
757                    MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
758     setOperationAction(ISD::FSIN,      VT, Expand);
759     setOperationAction(ISD::FSINCOS,   VT, Expand);
760     setOperationAction(ISD::FCOS,      VT, Expand);
761     setOperationAction(ISD::FREM,      VT, Expand);
762     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
763     setOperationAction(ISD::FPOW,      VT, Expand);
764     setOperationAction(ISD::FLOG,      VT, Expand);
765     setOperationAction(ISD::FLOG2,     VT, Expand);
766     setOperationAction(ISD::FLOG10,    VT, Expand);
767     setOperationAction(ISD::FEXP,      VT, Expand);
768     setOperationAction(ISD::FEXP2,     VT, Expand);
769   }
770 
771   // First set operation action for all vector types to either promote
772   // (for widening) or expand (for scalarization). Then we will selectively
773   // turn on ones that can be effectively codegen'd.
774   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
775     setOperationAction(ISD::SDIV, VT, Expand);
776     setOperationAction(ISD::UDIV, VT, Expand);
777     setOperationAction(ISD::SREM, VT, Expand);
778     setOperationAction(ISD::UREM, VT, Expand);
779     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
780     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
781     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
782     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
783     setOperationAction(ISD::FMA,  VT, Expand);
784     setOperationAction(ISD::FFLOOR, VT, Expand);
785     setOperationAction(ISD::FCEIL, VT, Expand);
786     setOperationAction(ISD::FTRUNC, VT, Expand);
787     setOperationAction(ISD::FRINT, VT, Expand);
788     setOperationAction(ISD::FNEARBYINT, VT, Expand);
789     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
790     setOperationAction(ISD::MULHS, VT, Expand);
791     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
792     setOperationAction(ISD::MULHU, VT, Expand);
793     setOperationAction(ISD::SDIVREM, VT, Expand);
794     setOperationAction(ISD::UDIVREM, VT, Expand);
795     setOperationAction(ISD::CTPOP, VT, Expand);
796     setOperationAction(ISD::CTTZ, VT, Expand);
797     setOperationAction(ISD::CTLZ, VT, Expand);
798     setOperationAction(ISD::ROTL, VT, Expand);
799     setOperationAction(ISD::ROTR, VT, Expand);
800     setOperationAction(ISD::BSWAP, VT, Expand);
801     setOperationAction(ISD::SETCC, VT, Expand);
802     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
803     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
804     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
805     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
806     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
807     setOperationAction(ISD::TRUNCATE, VT, Expand);
808     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
809     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
810     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
811     setOperationAction(ISD::SELECT_CC, VT, Expand);
812     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
813       setTruncStoreAction(InnerVT, VT, Expand);
814 
815       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
816       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
817 
818       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
819       // types, we have to deal with them whether we ask for Expansion or not.
820       // Setting Expand causes its own optimisation problems though, so leave
821       // them legal.
822       if (VT.getVectorElementType() == MVT::i1)
823         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
824 
825       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
826       // split/scalarized right now.
827       if (VT.getVectorElementType() == MVT::f16)
828         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
829     }
830   }
831 
832   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
833   // with -msoft-float, disable use of MMX as well.
834   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
835     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
836     // No operations on x86mmx supported, everything uses intrinsics.
837   }
838 
839   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
840     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
841                                                     : &X86::VR128RegClass);
842 
843     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
844     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
845     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
846     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
847     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
848     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
849     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
850     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
851 
852     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
853     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
854 
855     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
856     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
857     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
858     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
859     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
860   }
861 
862   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
863     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
864                                                     : &X86::VR128RegClass);
865 
866     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
867     // registers cannot be used even for integer operations.
868     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
869                                                     : &X86::VR128RegClass);
870     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
871                                                     : &X86::VR128RegClass);
872     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
873                                                     : &X86::VR128RegClass);
874     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
875                                                     : &X86::VR128RegClass);
876 
877     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
878                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
879       setOperationAction(ISD::SDIV, VT, Custom);
880       setOperationAction(ISD::SREM, VT, Custom);
881       setOperationAction(ISD::UDIV, VT, Custom);
882       setOperationAction(ISD::UREM, VT, Custom);
883     }
884 
885     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
886     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
887     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
888 
889     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
890     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
891     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
892     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
893     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
894     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
895     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
896     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
897     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
898     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
899     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
900     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
901     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
902 
903     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
904       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
905       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
906       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
907       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
908     }
909 
910     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
911     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
912     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
913     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
914     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
915     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
916     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
917     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
918     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
919     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
920     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
921     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
922 
923     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
924     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
925     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
926 
927     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
928       setOperationAction(ISD::SETCC,              VT, Custom);
929       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
930       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
931       setOperationAction(ISD::CTPOP,              VT, Custom);
932       setOperationAction(ISD::ABS,                VT, Custom);
933 
934       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
935       // setcc all the way to isel and prefer SETGT in some isel patterns.
936       setCondCodeAction(ISD::SETLT, VT, Custom);
937       setCondCodeAction(ISD::SETLE, VT, Custom);
938     }
939 
940     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
941       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
942       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
943       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
944       setOperationAction(ISD::VSELECT,            VT, Custom);
945       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
946     }
947 
948     for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
949       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
950       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
951       setOperationAction(ISD::VSELECT,            VT, Custom);
952 
953       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
954         continue;
955 
956       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
957       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
958     }
959 
960     // Custom lower v2i64 and v2f64 selects.
961     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
962     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
963     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
964     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
965     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
966 
967     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
968     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
969     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Legal);
970     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
971 
972     // Custom legalize these to avoid over promotion or custom promotion.
973     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
974       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
975       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
976       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
977       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
978     }
979 
980     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
981     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Legal);
982     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
983     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
984 
985     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
986     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
987 
988     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
989     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
990 
991     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
992     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
993     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
994     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
995     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
996 
997     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
998     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
999     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1000     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1001 
1002     // We want to legalize this to an f64 load rather than an i64 load on
1003     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1004     // store.
1005     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1006     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1007     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1008     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1009     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1010     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1011 
1012     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1013     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1014     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1015     if (!Subtarget.hasAVX512())
1016       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1017 
1018     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1019     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1020     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1021 
1022     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1023 
1024     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1025     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1026     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1027     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1028     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1029     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1030 
1031     // In the customized shift lowering, the legal v4i32/v2i64 cases
1032     // in AVX2 will be recognized.
1033     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1034       setOperationAction(ISD::SRL,              VT, Custom);
1035       setOperationAction(ISD::SHL,              VT, Custom);
1036       setOperationAction(ISD::SRA,              VT, Custom);
1037     }
1038 
1039     setOperationAction(ISD::ROTL,               MVT::v4i32, Custom);
1040     setOperationAction(ISD::ROTL,               MVT::v8i16, Custom);
1041 
1042     // With 512-bit registers or AVX512VL+BW, expanding (and promoting the
1043     // shifts) is better.
1044     if (!Subtarget.useAVX512Regs() &&
1045         !(Subtarget.hasBWI() && Subtarget.hasVLX()))
1046       setOperationAction(ISD::ROTL,             MVT::v16i8, Custom);
1047 
1048     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1049     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1050     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1051     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1052     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1053   }
1054 
1055   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1056     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1057     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1058     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1059     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1060     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1061     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1062     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1063     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1064 
1065     // These might be better off as horizontal vector ops.
1066     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1067     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1068     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1069     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1070   }
1071 
1072   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1073     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1074       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1075       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1076       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1077       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1078       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1079       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1080       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1081       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1082       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1083       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1084 
1085       setOperationAction(ISD::FROUND,            RoundedTy,  Custom);
1086     }
1087 
1088     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1089     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1090     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1091     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1092     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1093     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1094     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1095     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1096 
1097     // FIXME: Do we need to handle scalar-to-vector here?
1098     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1099 
1100     // We directly match byte blends in the backend as they match the VSELECT
1101     // condition form.
1102     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1103 
1104     // SSE41 brings specific instructions for doing vector sign extend even in
1105     // cases where we don't have SRA.
1106     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1107       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1108       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1109     }
1110 
1111     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1112     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1113       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1114       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1115       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1116       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1117       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1118       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1119     }
1120 
1121     // i8 vectors are custom because the source register and source
1122     // source memory operand types are not the same width.
1123     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1124 
1125     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1126       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1127       // do the pre and post work in the vector domain.
1128       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1129       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1130       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1131       // so that DAG combine doesn't try to turn it into uint_to_fp.
1132       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1133       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1134     }
1135   }
1136 
1137   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1138     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1139                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1140       setOperationAction(ISD::ROTL, VT, Custom);
1141 
1142     // XOP can efficiently perform BITREVERSE with VPPERM.
1143     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1144       setOperationAction(ISD::BITREVERSE, VT, Custom);
1145 
1146     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1147                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1148       setOperationAction(ISD::BITREVERSE, VT, Custom);
1149   }
1150 
1151   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1152     bool HasInt256 = Subtarget.hasInt256();
1153 
1154     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1155                                                      : &X86::VR256RegClass);
1156     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1157                                                      : &X86::VR256RegClass);
1158     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1159                                                      : &X86::VR256RegClass);
1160     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1161                                                      : &X86::VR256RegClass);
1162     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1163                                                      : &X86::VR256RegClass);
1164     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1165                                                      : &X86::VR256RegClass);
1166 
1167     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1168       setOperationAction(ISD::FFLOOR,            VT, Legal);
1169       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1170       setOperationAction(ISD::FCEIL,             VT, Legal);
1171       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1172       setOperationAction(ISD::FTRUNC,            VT, Legal);
1173       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1174       setOperationAction(ISD::FRINT,             VT, Legal);
1175       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1176       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1177       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1178 
1179       setOperationAction(ISD::FROUND,            VT, Custom);
1180 
1181       setOperationAction(ISD::FNEG,              VT, Custom);
1182       setOperationAction(ISD::FABS,              VT, Custom);
1183       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1184     }
1185 
1186     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1187     // even though v8i16 is a legal type.
1188     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1189     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1190     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1191     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1192     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Legal);
1193     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Legal);
1194 
1195     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1196     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Legal);
1197 
1198     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1199     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1200     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1201     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1202     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1203     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1204     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1205     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1206     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1207     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
1208     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1209     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1210 
1211     if (!Subtarget.hasAVX512())
1212       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1213 
1214     // In the customized shift lowering, the legal v8i32/v4i64 cases
1215     // in AVX2 will be recognized.
1216     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1217       setOperationAction(ISD::SRL, VT, Custom);
1218       setOperationAction(ISD::SHL, VT, Custom);
1219       setOperationAction(ISD::SRA, VT, Custom);
1220     }
1221 
1222     // These types need custom splitting if their input is a 128-bit vector.
1223     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1224     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1225     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1226     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1227 
1228     setOperationAction(ISD::ROTL,              MVT::v8i32,  Custom);
1229     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1230 
1231     // With BWI, expanding (and promoting the shifts) is the better.
1232     if (!Subtarget.useBWIRegs())
1233       setOperationAction(ISD::ROTL,            MVT::v32i8,  Custom);
1234 
1235     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1236     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1237     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1238     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1239     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1240     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1241 
1242     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1243       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1244       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1245       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1246     }
1247 
1248     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1249     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1250     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1251     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1252 
1253     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1254       setOperationAction(ISD::SETCC,           VT, Custom);
1255       setOperationAction(ISD::STRICT_FSETCC,   VT, Custom);
1256       setOperationAction(ISD::STRICT_FSETCCS,  VT, Custom);
1257       setOperationAction(ISD::CTPOP,           VT, Custom);
1258       setOperationAction(ISD::CTLZ,            VT, Custom);
1259 
1260       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1261       // setcc all the way to isel and prefer SETGT in some isel patterns.
1262       setCondCodeAction(ISD::SETLT, VT, Custom);
1263       setCondCodeAction(ISD::SETLE, VT, Custom);
1264     }
1265 
1266     if (Subtarget.hasAnyFMA()) {
1267       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1268                        MVT::v2f64, MVT::v4f64 }) {
1269         setOperationAction(ISD::FMA, VT, Legal);
1270         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1271       }
1272     }
1273 
1274     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1275       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1276       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1277     }
1278 
1279     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1280     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1281     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1282     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1283 
1284     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1285     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1286     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1287     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1288     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1289     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1290 
1291     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1292     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1293     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1294     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1295     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1296 
1297     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1298     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1299     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1300     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1301     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1302     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1303     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1304     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1305 
1306     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1307       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1308       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1309       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1310       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1311       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1312     }
1313 
1314     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1315       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1316       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1317     }
1318 
1319     if (HasInt256) {
1320       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1321       // when we have a 256bit-wide blend with immediate.
1322       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1323       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1324 
1325       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1326       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1327         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1328         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1329         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1330         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1331         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1332         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1333       }
1334     }
1335 
1336     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1337                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1338       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1339       setOperationAction(ISD::MSTORE, VT, Legal);
1340     }
1341 
1342     // Extract subvector is special because the value type
1343     // (result) is 128-bit but the source is 256-bit wide.
1344     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1345                      MVT::v4f32, MVT::v2f64 }) {
1346       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1347     }
1348 
1349     // Custom lower several nodes for 256-bit types.
1350     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1351                     MVT::v8f32, MVT::v4f64 }) {
1352       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1353       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1354       setOperationAction(ISD::VSELECT,            VT, Custom);
1355       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1356       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1357       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1358       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1359       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1360       setOperationAction(ISD::STORE,              VT, Custom);
1361     }
1362 
1363     if (HasInt256) {
1364       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1365 
1366       // Custom legalize 2x32 to get a little better code.
1367       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1368       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1369 
1370       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1371                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1372         setOperationAction(ISD::MGATHER,  VT, Custom);
1373     }
1374   }
1375 
1376   // This block controls legalization of the mask vector sizes that are
1377   // available with AVX512. 512-bit vectors are in a separate block controlled
1378   // by useAVX512Regs.
1379   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1380     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1381     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1382     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1383     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1384     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1385 
1386     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1387     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1388     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1389 
1390     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1391     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1392     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1393     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1394     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1395     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1396     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1397     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1398     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1399     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1400     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1401     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1402 
1403     // There is no byte sized k-register load or store without AVX512DQ.
1404     if (!Subtarget.hasDQI()) {
1405       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1406       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1407       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1408       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1409 
1410       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1411       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1412       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1413       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1414     }
1415 
1416     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1417     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1418       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1419       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1420       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1421     }
1422 
1423     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1424       setOperationAction(ISD::ADD,              VT, Custom);
1425       setOperationAction(ISD::SUB,              VT, Custom);
1426       setOperationAction(ISD::MUL,              VT, Custom);
1427       setOperationAction(ISD::UADDSAT,          VT, Custom);
1428       setOperationAction(ISD::SADDSAT,          VT, Custom);
1429       setOperationAction(ISD::USUBSAT,          VT, Custom);
1430       setOperationAction(ISD::SSUBSAT,          VT, Custom);
1431       setOperationAction(ISD::VSELECT,          VT,  Expand);
1432     }
1433 
1434     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1435       setOperationAction(ISD::SETCC,            VT, Custom);
1436       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1437       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1438       setOperationAction(ISD::SELECT,           VT, Custom);
1439       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1440 
1441       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1442       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1443       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1444       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1445       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1446       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1447     }
1448 
1449     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1450       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1451   }
1452 
1453   // This block controls legalization for 512-bit operations with 32/64 bit
1454   // elements. 512-bits can be disabled based on prefer-vector-width and
1455   // required-vector-width function attributes.
1456   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1457     bool HasBWI = Subtarget.hasBWI();
1458 
1459     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1460     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1461     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1462     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1463     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1464     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1465 
1466     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1467       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1468       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1469       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1470       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1471       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1472       if (HasBWI)
1473         setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1474     }
1475 
1476     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1477       setOperationAction(ISD::FNEG,  VT, Custom);
1478       setOperationAction(ISD::FABS,  VT, Custom);
1479       setOperationAction(ISD::FMA,   VT, Legal);
1480       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1481       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1482     }
1483 
1484     for (MVT VT : { MVT::v16i1, MVT::v16i8, MVT::v16i16 }) {
1485       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1486       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1487       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1488       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1489     }
1490     setOperationAction(ISD::FP_TO_SINT,        MVT::v16i32, Legal);
1491     setOperationAction(ISD::FP_TO_UINT,        MVT::v16i32, Legal);
1492     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v16i32, Legal);
1493     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v16i32, Legal);
1494     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Legal);
1495     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Legal);
1496     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Legal);
1497     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Legal);
1498 
1499     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1500     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1501     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1502     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1503     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1504     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1505     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1506     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1507     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1508     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1509     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64,  Legal);
1510     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1511 
1512     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1513     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1514     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1515     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1516     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1517     if (HasBWI)
1518       setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1519 
1520     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1521     // to 512-bit rather than use the AVX2 instructions so that we can use
1522     // k-masks.
1523     if (!Subtarget.hasVLX()) {
1524       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1525            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1526         setOperationAction(ISD::MLOAD,  VT, Custom);
1527         setOperationAction(ISD::MSTORE, VT, Custom);
1528       }
1529     }
1530 
1531     setOperationAction(ISD::TRUNCATE,    MVT::v8i32,  Legal);
1532     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Legal);
1533     setOperationAction(ISD::TRUNCATE,    MVT::v32i8,  HasBWI ? Legal : Custom);
1534     setOperationAction(ISD::TRUNCATE,    MVT::v16i64, Custom);
1535     setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1536     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1537     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
1538     setOperationAction(ISD::ANY_EXTEND,  MVT::v32i16, Custom);
1539     setOperationAction(ISD::ANY_EXTEND,  MVT::v16i32, Custom);
1540     setOperationAction(ISD::ANY_EXTEND,  MVT::v8i64,  Custom);
1541     setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1542     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1543     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
1544 
1545     if (HasBWI) {
1546       // Extends from v64i1 masks to 512-bit vectors.
1547       setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1548       setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1549       setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1550     }
1551 
1552     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1553       setOperationAction(ISD::FFLOOR,            VT, Legal);
1554       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1555       setOperationAction(ISD::FCEIL,             VT, Legal);
1556       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1557       setOperationAction(ISD::FTRUNC,            VT, Legal);
1558       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1559       setOperationAction(ISD::FRINT,             VT, Legal);
1560       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1561       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1562       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1563 
1564       setOperationAction(ISD::FROUND,            VT, Custom);
1565     }
1566 
1567     for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1568       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1569       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1570     }
1571 
1572     setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1573     setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1574     setOperationAction(ISD::ADD, MVT::v64i8,  HasBWI ? Legal : Custom);
1575     setOperationAction(ISD::SUB, MVT::v64i8,  HasBWI ? Legal : Custom);
1576 
1577     setOperationAction(ISD::MUL, MVT::v8i64,  Custom);
1578     setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1579     setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1580     setOperationAction(ISD::MUL, MVT::v64i8,  Custom);
1581 
1582     setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1583     setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1584     setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1585     setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1586     setOperationAction(ISD::MULHS, MVT::v64i8,  Custom);
1587     setOperationAction(ISD::MULHU, MVT::v64i8,  Custom);
1588 
1589     setOperationAction(ISD::BITREVERSE, MVT::v64i8,  Custom);
1590 
1591     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1592       setOperationAction(ISD::SRL,              VT, Custom);
1593       setOperationAction(ISD::SHL,              VT, Custom);
1594       setOperationAction(ISD::SRA,              VT, Custom);
1595       setOperationAction(ISD::SETCC,            VT, Custom);
1596 
1597       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1598       // setcc all the way to isel and prefer SETGT in some isel patterns.
1599       setCondCodeAction(ISD::SETLT, VT, Custom);
1600       setCondCodeAction(ISD::SETLE, VT, Custom);
1601     }
1602     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1603       setOperationAction(ISD::SMAX,             VT, Legal);
1604       setOperationAction(ISD::UMAX,             VT, Legal);
1605       setOperationAction(ISD::SMIN,             VT, Legal);
1606       setOperationAction(ISD::UMIN,             VT, Legal);
1607       setOperationAction(ISD::ABS,              VT, Legal);
1608       setOperationAction(ISD::CTPOP,            VT, Custom);
1609       setOperationAction(ISD::ROTL,             VT, Custom);
1610       setOperationAction(ISD::ROTR,             VT, Custom);
1611       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1612       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1613     }
1614 
1615     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1616       setOperationAction(ISD::ABS,     VT, HasBWI ? Legal : Custom);
1617       setOperationAction(ISD::CTPOP,   VT, Subtarget.hasBITALG() ? Legal : Custom);
1618       setOperationAction(ISD::CTLZ,    VT, Custom);
1619       setOperationAction(ISD::SMAX,    VT, HasBWI ? Legal : Custom);
1620       setOperationAction(ISD::UMAX,    VT, HasBWI ? Legal : Custom);
1621       setOperationAction(ISD::SMIN,    VT, HasBWI ? Legal : Custom);
1622       setOperationAction(ISD::UMIN,    VT, HasBWI ? Legal : Custom);
1623       setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1624       setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1625       setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1626       setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1627     }
1628 
1629     if (Subtarget.hasDQI()) {
1630       setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1631       setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1632       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i64, Legal);
1633       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i64, Legal);
1634       setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1635       setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1636       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i64, Legal);
1637       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i64, Legal);
1638 
1639       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1640     }
1641 
1642     if (Subtarget.hasCDI()) {
1643       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1644       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1645         setOperationAction(ISD::CTLZ,            VT, Legal);
1646       }
1647     } // Subtarget.hasCDI()
1648 
1649     if (Subtarget.hasVPOPCNTDQ()) {
1650       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1651         setOperationAction(ISD::CTPOP, VT, Legal);
1652     }
1653 
1654     // Extract subvector is special because the value type
1655     // (result) is 256-bit but the source is 512-bit wide.
1656     // 128-bit was made Legal under AVX1.
1657     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1658                      MVT::v8f32, MVT::v4f64 })
1659       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1660 
1661     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1662                      MVT::v16f32, MVT::v8f64 }) {
1663       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1664       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1665       setOperationAction(ISD::SELECT,             VT, Custom);
1666       setOperationAction(ISD::VSELECT,            VT, Custom);
1667       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1668       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1669       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1670       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1671       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1672     }
1673 
1674     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1675       setOperationAction(ISD::MLOAD,               VT, Legal);
1676       setOperationAction(ISD::MSTORE,              VT, Legal);
1677       setOperationAction(ISD::MGATHER,             VT, Custom);
1678       setOperationAction(ISD::MSCATTER,            VT, Custom);
1679     }
1680     if (HasBWI) {
1681       for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1682         setOperationAction(ISD::MLOAD,        VT, Legal);
1683         setOperationAction(ISD::MSTORE,       VT, Legal);
1684       }
1685     } else {
1686       setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1687       setOperationAction(ISD::STORE, MVT::v64i8,  Custom);
1688     }
1689 
1690     if (Subtarget.hasVBMI2()) {
1691       for (auto VT : { MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1692         setOperationAction(ISD::FSHL, VT, Custom);
1693         setOperationAction(ISD::FSHR, VT, Custom);
1694       }
1695     }
1696   }// useAVX512Regs
1697 
1698   // This block controls legalization for operations that don't have
1699   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1700   // narrower widths.
1701   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1702     // These operations are handled on non-VLX by artificially widening in
1703     // isel patterns.
1704 
1705     setOperationAction(ISD::FP_TO_UINT, MVT::v8i32,
1706                        Subtarget.hasVLX() ? Legal : Custom);
1707     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32,
1708                        Subtarget.hasVLX() ? Legal : Custom);
1709     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1710     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i32,
1711                        Subtarget.hasVLX() ? Legal : Custom);
1712     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32,
1713                        Subtarget.hasVLX() ? Legal : Custom);
1714     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
1715     setOperationAction(ISD::UINT_TO_FP, MVT::v8i32,
1716                        Subtarget.hasVLX() ? Legal : Custom);
1717     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32,
1718                        Subtarget.hasVLX() ? Legal : Custom);
1719     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32,
1720                        Subtarget.hasVLX() ? Legal : Custom);
1721     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32,
1722                        Subtarget.hasVLX() ? Legal : Custom);
1723 
1724     if (Subtarget.hasDQI()) {
1725       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1726       // v2f32 UINT_TO_FP is already custom under SSE2.
1727       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
1728              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
1729              "Unexpected operation action!");
1730       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1731       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
1732       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
1733       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
1734       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
1735     }
1736 
1737     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1738       setOperationAction(ISD::SMAX, VT, Legal);
1739       setOperationAction(ISD::UMAX, VT, Legal);
1740       setOperationAction(ISD::SMIN, VT, Legal);
1741       setOperationAction(ISD::UMIN, VT, Legal);
1742       setOperationAction(ISD::ABS,  VT, Legal);
1743     }
1744 
1745     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1746       setOperationAction(ISD::ROTL,     VT, Custom);
1747       setOperationAction(ISD::ROTR,     VT, Custom);
1748     }
1749 
1750     // Custom legalize 2x32 to get a little better code.
1751     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1752     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1753 
1754     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1755                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1756       setOperationAction(ISD::MSCATTER, VT, Custom);
1757 
1758     if (Subtarget.hasDQI()) {
1759       for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1760         setOperationAction(ISD::SINT_TO_FP, VT,
1761                            Subtarget.hasVLX() ? Legal : Custom);
1762         setOperationAction(ISD::UINT_TO_FP, VT,
1763                            Subtarget.hasVLX() ? Legal : Custom);
1764         setOperationAction(ISD::STRICT_SINT_TO_FP, VT,
1765                            Subtarget.hasVLX() ? Legal : Custom);
1766         setOperationAction(ISD::STRICT_UINT_TO_FP, VT,
1767                            Subtarget.hasVLX() ? Legal : Custom);
1768         setOperationAction(ISD::FP_TO_SINT, VT,
1769                            Subtarget.hasVLX() ? Legal : Custom);
1770         setOperationAction(ISD::FP_TO_UINT, VT,
1771                            Subtarget.hasVLX() ? Legal : Custom);
1772         setOperationAction(ISD::STRICT_FP_TO_SINT, VT,
1773                            Subtarget.hasVLX() ? Legal : Custom);
1774         setOperationAction(ISD::STRICT_FP_TO_UINT, VT,
1775                            Subtarget.hasVLX() ? Legal : Custom);
1776         setOperationAction(ISD::MUL,               VT, Legal);
1777       }
1778     }
1779 
1780     if (Subtarget.hasCDI()) {
1781       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1782         setOperationAction(ISD::CTLZ,            VT, Legal);
1783       }
1784     } // Subtarget.hasCDI()
1785 
1786     if (Subtarget.hasVPOPCNTDQ()) {
1787       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1788         setOperationAction(ISD::CTPOP, VT, Legal);
1789     }
1790   }
1791 
1792   // This block control legalization of v32i1/v64i1 which are available with
1793   // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1794   // useBWIRegs.
1795   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1796     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1797     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1798 
1799     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1800       setOperationAction(ISD::ADD,                VT, Custom);
1801       setOperationAction(ISD::SUB,                VT, Custom);
1802       setOperationAction(ISD::MUL,                VT, Custom);
1803       setOperationAction(ISD::VSELECT,            VT, Expand);
1804       setOperationAction(ISD::UADDSAT,            VT, Custom);
1805       setOperationAction(ISD::SADDSAT,            VT, Custom);
1806       setOperationAction(ISD::USUBSAT,            VT, Custom);
1807       setOperationAction(ISD::SSUBSAT,            VT, Custom);
1808 
1809       setOperationAction(ISD::TRUNCATE,           VT, Custom);
1810       setOperationAction(ISD::SETCC,              VT, Custom);
1811       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1812       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1813       setOperationAction(ISD::SELECT,             VT, Custom);
1814       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1815       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1816       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1817       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1818     }
1819 
1820     for (auto VT : { MVT::v16i1, MVT::v32i1 })
1821       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1822 
1823     // Extends from v32i1 masks to 256-bit vectors.
1824     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1825     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1826     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
1827 
1828     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1829       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1830       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1831     }
1832 
1833     // These operations are handled on non-VLX by artificially widening in
1834     // isel patterns.
1835     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1836 
1837     if (Subtarget.hasBITALG()) {
1838       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1839         setOperationAction(ISD::CTPOP, VT, Legal);
1840     }
1841   }
1842 
1843   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1844     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1845     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1846     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1847     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1848     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1849 
1850     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1851     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1852     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1853     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1854     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1855 
1856     if (Subtarget.hasBWI()) {
1857       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1858       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1859     }
1860 
1861     if (Subtarget.hasVBMI2()) {
1862       // TODO: Make these legal even without VLX?
1863       for (auto VT : { MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1864                        MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1865         setOperationAction(ISD::FSHL, VT, Custom);
1866         setOperationAction(ISD::FSHR, VT, Custom);
1867       }
1868     }
1869 
1870     setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
1871     setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
1872     setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1873   }
1874 
1875   // We want to custom lower some of our intrinsics.
1876   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1877   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1878   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1879   if (!Subtarget.is64Bit()) {
1880     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1881   }
1882 
1883   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1884   // handle type legalization for these operations here.
1885   //
1886   // FIXME: We really should do custom legalization for addition and
1887   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1888   // than generic legalization for 64-bit multiplication-with-overflow, though.
1889   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1890     if (VT == MVT::i64 && !Subtarget.is64Bit())
1891       continue;
1892     // Add/Sub/Mul with overflow operations are custom lowered.
1893     setOperationAction(ISD::SADDO, VT, Custom);
1894     setOperationAction(ISD::UADDO, VT, Custom);
1895     setOperationAction(ISD::SSUBO, VT, Custom);
1896     setOperationAction(ISD::USUBO, VT, Custom);
1897     setOperationAction(ISD::SMULO, VT, Custom);
1898     setOperationAction(ISD::UMULO, VT, Custom);
1899 
1900     // Support carry in as value rather than glue.
1901     setOperationAction(ISD::ADDCARRY, VT, Custom);
1902     setOperationAction(ISD::SUBCARRY, VT, Custom);
1903     setOperationAction(ISD::SETCCCARRY, VT, Custom);
1904   }
1905 
1906   if (!Subtarget.is64Bit()) {
1907     // These libcalls are not available in 32-bit.
1908     setLibcallName(RTLIB::SHL_I128, nullptr);
1909     setLibcallName(RTLIB::SRL_I128, nullptr);
1910     setLibcallName(RTLIB::SRA_I128, nullptr);
1911     setLibcallName(RTLIB::MUL_I128, nullptr);
1912   }
1913 
1914   // Combine sin / cos into _sincos_stret if it is available.
1915   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1916       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1917     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1918     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1919   }
1920 
1921   if (Subtarget.isTargetWin64()) {
1922     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1923     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1924     setOperationAction(ISD::SREM, MVT::i128, Custom);
1925     setOperationAction(ISD::UREM, MVT::i128, Custom);
1926     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1927     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1928   }
1929 
1930   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1931   // is. We should promote the value to 64-bits to solve this.
1932   // This is what the CRT headers do - `fmodf` is an inline header
1933   // function casting to f64 and calling `fmod`.
1934   if (Subtarget.is32Bit() &&
1935       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
1936     for (ISD::NodeType Op :
1937          {ISD::FCEIL,  ISD::STRICT_FCEIL,
1938           ISD::FCOS,   ISD::STRICT_FCOS,
1939           ISD::FEXP,   ISD::STRICT_FEXP,
1940           ISD::FFLOOR, ISD::STRICT_FFLOOR,
1941           ISD::FREM,   ISD::STRICT_FREM,
1942           ISD::FLOG,   ISD::STRICT_FLOG,
1943           ISD::FLOG10, ISD::STRICT_FLOG10,
1944           ISD::FPOW,   ISD::STRICT_FPOW,
1945           ISD::FSIN,   ISD::STRICT_FSIN})
1946       if (isOperationExpand(Op, MVT::f32))
1947         setOperationAction(Op, MVT::f32, Promote);
1948 
1949   // We have target-specific dag combine patterns for the following nodes:
1950   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1951   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
1952   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
1953   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1954   setTargetDAGCombine(ISD::CONCAT_VECTORS);
1955   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1956   setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1957   setTargetDAGCombine(ISD::BITCAST);
1958   setTargetDAGCombine(ISD::VSELECT);
1959   setTargetDAGCombine(ISD::SELECT);
1960   setTargetDAGCombine(ISD::SHL);
1961   setTargetDAGCombine(ISD::SRA);
1962   setTargetDAGCombine(ISD::SRL);
1963   setTargetDAGCombine(ISD::OR);
1964   setTargetDAGCombine(ISD::AND);
1965   setTargetDAGCombine(ISD::ADD);
1966   setTargetDAGCombine(ISD::FADD);
1967   setTargetDAGCombine(ISD::FSUB);
1968   setTargetDAGCombine(ISD::FNEG);
1969   setTargetDAGCombine(ISD::FMA);
1970   setTargetDAGCombine(ISD::STRICT_FMA);
1971   setTargetDAGCombine(ISD::FMINNUM);
1972   setTargetDAGCombine(ISD::FMAXNUM);
1973   setTargetDAGCombine(ISD::SUB);
1974   setTargetDAGCombine(ISD::LOAD);
1975   setTargetDAGCombine(ISD::MLOAD);
1976   setTargetDAGCombine(ISD::STORE);
1977   setTargetDAGCombine(ISD::MSTORE);
1978   setTargetDAGCombine(ISD::TRUNCATE);
1979   setTargetDAGCombine(ISD::ZERO_EXTEND);
1980   setTargetDAGCombine(ISD::ANY_EXTEND);
1981   setTargetDAGCombine(ISD::SIGN_EXTEND);
1982   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1983   setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
1984   setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
1985   setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
1986   setTargetDAGCombine(ISD::SINT_TO_FP);
1987   setTargetDAGCombine(ISD::UINT_TO_FP);
1988   setTargetDAGCombine(ISD::STRICT_SINT_TO_FP);
1989   setTargetDAGCombine(ISD::STRICT_UINT_TO_FP);
1990   setTargetDAGCombine(ISD::SETCC);
1991   setTargetDAGCombine(ISD::MUL);
1992   setTargetDAGCombine(ISD::XOR);
1993   setTargetDAGCombine(ISD::MSCATTER);
1994   setTargetDAGCombine(ISD::MGATHER);
1995   setTargetDAGCombine(ISD::FP16_TO_FP);
1996   setTargetDAGCombine(ISD::FP_EXTEND);
1997   setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
1998   setTargetDAGCombine(ISD::FP_ROUND);
1999 
2000   computeRegisterProperties(Subtarget.getRegisterInfo());
2001 
2002   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2003   MaxStoresPerMemsetOptSize = 8;
2004   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2005   MaxStoresPerMemcpyOptSize = 4;
2006   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2007   MaxStoresPerMemmoveOptSize = 4;
2008 
2009   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2010   // that needs to benchmarked and balanced with the potential use of vector
2011   // load/store types (PR33329, PR33914).
2012   MaxLoadsPerMemcmp = 2;
2013   MaxLoadsPerMemcmpOptSize = 2;
2014 
2015   // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
2016   setPrefLoopAlignment(Align(1ULL << ExperimentalPrefLoopAlignment));
2017 
2018   // An out-of-order CPU can speculatively execute past a predictable branch,
2019   // but a conditional move could be stalled by an expensive earlier operation.
2020   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2021   EnableExtLdPromotion = true;
2022   setPrefFunctionAlignment(Align(16));
2023 
2024   verifyIntrinsicTables();
2025 
2026   // Default to having -disable-strictnode-mutation on
2027   IsStrictFPEnabled = true;
2028 }
2029 
2030 // This has so far only been implemented for 64-bit MachO.
useLoadStackGuardNode() const2031 bool X86TargetLowering::useLoadStackGuardNode() const {
2032   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2033 }
2034 
useStackGuardXorFP() const2035 bool X86TargetLowering::useStackGuardXorFP() const {
2036   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2037   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2038 }
2039 
emitStackGuardXorFP(SelectionDAG & DAG,SDValue Val,const SDLoc & DL) const2040 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2041                                                const SDLoc &DL) const {
2042   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2043   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2044   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2045   return SDValue(Node, 0);
2046 }
2047 
2048 TargetLoweringBase::LegalizeTypeAction
getPreferredVectorAction(MVT VT) const2049 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2050   if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2051       !Subtarget.hasBWI())
2052     return TypeSplitVector;
2053 
2054   if (VT.getVectorNumElements() != 1 &&
2055       VT.getVectorElementType() != MVT::i1)
2056     return TypeWidenVector;
2057 
2058   return TargetLoweringBase::getPreferredVectorAction(VT);
2059 }
2060 
2061 static std::pair<MVT, unsigned>
handleMaskRegisterForCallingConv(unsigned NumElts,CallingConv::ID CC,const X86Subtarget & Subtarget)2062 handleMaskRegisterForCallingConv(unsigned NumElts, CallingConv::ID CC,
2063                                  const X86Subtarget &Subtarget) {
2064   // v2i1/v4i1/v8i1/v16i1 all pass in xmm registers unless the calling
2065   // convention is one that uses k registers.
2066   if (NumElts == 2)
2067     return {MVT::v2i64, 1};
2068   if (NumElts == 4)
2069     return {MVT::v4i32, 1};
2070   if (NumElts == 8 && CC != CallingConv::X86_RegCall &&
2071       CC != CallingConv::Intel_OCL_BI)
2072     return {MVT::v8i16, 1};
2073   if (NumElts == 16 && CC != CallingConv::X86_RegCall &&
2074       CC != CallingConv::Intel_OCL_BI)
2075     return {MVT::v16i8, 1};
2076   // v32i1 passes in ymm unless we have BWI and the calling convention is
2077   // regcall.
2078   if (NumElts == 32 && (!Subtarget.hasBWI() || CC != CallingConv::X86_RegCall))
2079     return {MVT::v32i8, 1};
2080   // Split v64i1 vectors if we don't have v64i8 available.
2081   if (NumElts == 64 && Subtarget.hasBWI() && CC != CallingConv::X86_RegCall) {
2082     if (Subtarget.useAVX512Regs())
2083       return {MVT::v64i8, 1};
2084     return {MVT::v32i8, 2};
2085   }
2086 
2087   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2088   if (!isPowerOf2_32(NumElts) || (NumElts == 64 && !Subtarget.hasBWI()) ||
2089       NumElts > 64)
2090     return {MVT::i8, NumElts};
2091 
2092   return {MVT::INVALID_SIMPLE_VALUE_TYPE, 0};
2093 }
2094 
getRegisterTypeForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const2095 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2096                                                      CallingConv::ID CC,
2097                                                      EVT VT) const {
2098   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2099       Subtarget.hasAVX512()) {
2100     unsigned NumElts = VT.getVectorNumElements();
2101 
2102     MVT RegisterVT;
2103     unsigned NumRegisters;
2104     std::tie(RegisterVT, NumRegisters) =
2105         handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2106     if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2107       return RegisterVT;
2108   }
2109 
2110   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2111 }
2112 
getNumRegistersForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT) const2113 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2114                                                           CallingConv::ID CC,
2115                                                           EVT VT) const {
2116   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2117       Subtarget.hasAVX512()) {
2118     unsigned NumElts = VT.getVectorNumElements();
2119 
2120     MVT RegisterVT;
2121     unsigned NumRegisters;
2122     std::tie(RegisterVT, NumRegisters) =
2123         handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2124     if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2125       return NumRegisters;
2126   }
2127 
2128   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2129 }
2130 
getVectorTypeBreakdownForCallingConv(LLVMContext & Context,CallingConv::ID CC,EVT VT,EVT & IntermediateVT,unsigned & NumIntermediates,MVT & RegisterVT) const2131 unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2132     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2133     unsigned &NumIntermediates, MVT &RegisterVT) const {
2134   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2135   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2136       Subtarget.hasAVX512() &&
2137       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2138        (VT.getVectorNumElements() == 64 && !Subtarget.hasBWI()) ||
2139        VT.getVectorNumElements() > 64)) {
2140     RegisterVT = MVT::i8;
2141     IntermediateVT = MVT::i1;
2142     NumIntermediates = VT.getVectorNumElements();
2143     return NumIntermediates;
2144   }
2145 
2146   // Split v64i1 vectors if we don't have v64i8 available.
2147   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2148       CC != CallingConv::X86_RegCall) {
2149     RegisterVT = MVT::v32i8;
2150     IntermediateVT = MVT::v32i1;
2151     NumIntermediates = 2;
2152     return 2;
2153   }
2154 
2155   return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2156                                               NumIntermediates, RegisterVT);
2157 }
2158 
getSetCCResultType(const DataLayout & DL,LLVMContext & Context,EVT VT) const2159 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2160                                           LLVMContext& Context,
2161                                           EVT VT) const {
2162   if (!VT.isVector())
2163     return MVT::i8;
2164 
2165   if (Subtarget.hasAVX512()) {
2166     const unsigned NumElts = VT.getVectorNumElements();
2167 
2168     // Figure out what this type will be legalized to.
2169     EVT LegalVT = VT;
2170     while (getTypeAction(Context, LegalVT) != TypeLegal)
2171       LegalVT = getTypeToTransformTo(Context, LegalVT);
2172 
2173     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2174     if (LegalVT.getSimpleVT().is512BitVector())
2175       return EVT::getVectorVT(Context, MVT::i1, NumElts);
2176 
2177     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2178       // If we legalized to less than a 512-bit vector, then we will use a vXi1
2179       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2180       // vXi16/vXi8.
2181       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2182       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2183         return EVT::getVectorVT(Context, MVT::i1, NumElts);
2184     }
2185   }
2186 
2187   return VT.changeVectorElementTypeToInteger();
2188 }
2189 
2190 /// Helper for getByValTypeAlignment to determine
2191 /// the desired ByVal argument alignment.
getMaxByValAlign(Type * Ty,Align & MaxAlign)2192 static void getMaxByValAlign(Type *Ty, Align &MaxAlign) {
2193   if (MaxAlign == 16)
2194     return;
2195   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2196     if (VTy->getPrimitiveSizeInBits().getFixedSize() == 128)
2197       MaxAlign = Align(16);
2198   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2199     Align EltAlign;
2200     getMaxByValAlign(ATy->getElementType(), EltAlign);
2201     if (EltAlign > MaxAlign)
2202       MaxAlign = EltAlign;
2203   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2204     for (auto *EltTy : STy->elements()) {
2205       Align EltAlign;
2206       getMaxByValAlign(EltTy, EltAlign);
2207       if (EltAlign > MaxAlign)
2208         MaxAlign = EltAlign;
2209       if (MaxAlign == 16)
2210         break;
2211     }
2212   }
2213 }
2214 
2215 /// Return the desired alignment for ByVal aggregate
2216 /// function arguments in the caller parameter area. For X86, aggregates
2217 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2218 /// are at 4-byte boundaries.
getByValTypeAlignment(Type * Ty,const DataLayout & DL) const2219 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2220                                                   const DataLayout &DL) const {
2221   if (Subtarget.is64Bit()) {
2222     // Max of 8 and alignment of type.
2223     Align TyAlign = DL.getABITypeAlign(Ty);
2224     if (TyAlign > 8)
2225       return TyAlign.value();
2226     return 8;
2227   }
2228 
2229   Align Alignment(4);
2230   if (Subtarget.hasSSE1())
2231     getMaxByValAlign(Ty, Alignment);
2232   return Alignment.value();
2233 }
2234 
2235 /// It returns EVT::Other if the type should be determined using generic
2236 /// target-independent logic.
2237 /// For vector ops we check that the overall size isn't larger than our
2238 /// preferred vector width.
getOptimalMemOpType(const MemOp & Op,const AttributeList & FuncAttributes) const2239 EVT X86TargetLowering::getOptimalMemOpType(
2240     const MemOp &Op, const AttributeList &FuncAttributes) const {
2241   if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2242     if (Op.size() >= 16 &&
2243         (!Subtarget.isUnalignedMem16Slow() || Op.isAligned(Align(16)))) {
2244       // FIXME: Check if unaligned 64-byte accesses are slow.
2245       if (Op.size() >= 64 && Subtarget.hasAVX512() &&
2246           (Subtarget.getPreferVectorWidth() >= 512)) {
2247         return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2248       }
2249       // FIXME: Check if unaligned 32-byte accesses are slow.
2250       if (Op.size() >= 32 && Subtarget.hasAVX() &&
2251           (Subtarget.getPreferVectorWidth() >= 256)) {
2252         // Although this isn't a well-supported type for AVX1, we'll let
2253         // legalization and shuffle lowering produce the optimal codegen. If we
2254         // choose an optimal type with a vector element larger than a byte,
2255         // getMemsetStores() may create an intermediate splat (using an integer
2256         // multiply) before we splat as a vector.
2257         return MVT::v32i8;
2258       }
2259       if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2260         return MVT::v16i8;
2261       // TODO: Can SSE1 handle a byte vector?
2262       // If we have SSE1 registers we should be able to use them.
2263       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2264           (Subtarget.getPreferVectorWidth() >= 128))
2265         return MVT::v4f32;
2266     } else if (((Op.isMemcpy() && !Op.isMemcpyStrSrc()) || Op.isZeroMemset()) &&
2267                Op.size() >= 8 && !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2268       // Do not use f64 to lower memcpy if source is string constant. It's
2269       // better to use i32 to avoid the loads.
2270       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2271       // The gymnastics of splatting a byte value into an XMM register and then
2272       // only using 8-byte stores (because this is a CPU with slow unaligned
2273       // 16-byte accesses) makes that a loser.
2274       return MVT::f64;
2275     }
2276   }
2277   // This is a compromise. If we reach here, unaligned accesses may be slow on
2278   // this target. However, creating smaller, aligned accesses could be even
2279   // slower and would certainly be a lot more code.
2280   if (Subtarget.is64Bit() && Op.size() >= 8)
2281     return MVT::i64;
2282   return MVT::i32;
2283 }
2284 
isSafeMemOpType(MVT VT) const2285 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2286   if (VT == MVT::f32)
2287     return X86ScalarSSEf32;
2288   else if (VT == MVT::f64)
2289     return X86ScalarSSEf64;
2290   return true;
2291 }
2292 
allowsMisalignedMemoryAccesses(EVT VT,unsigned,unsigned Align,MachineMemOperand::Flags Flags,bool * Fast) const2293 bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2294     EVT VT, unsigned, unsigned Align, MachineMemOperand::Flags Flags,
2295     bool *Fast) const {
2296   if (Fast) {
2297     switch (VT.getSizeInBits()) {
2298     default:
2299       // 8-byte and under are always assumed to be fast.
2300       *Fast = true;
2301       break;
2302     case 128:
2303       *Fast = !Subtarget.isUnalignedMem16Slow();
2304       break;
2305     case 256:
2306       *Fast = !Subtarget.isUnalignedMem32Slow();
2307       break;
2308     // TODO: What about AVX-512 (512-bit) accesses?
2309     }
2310   }
2311   // NonTemporal vector memory ops must be aligned.
2312   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2313     // NT loads can only be vector aligned, so if its less aligned than the
2314     // minimum vector size (which we can split the vector down to), we might as
2315     // well use a regular unaligned vector load.
2316     // We don't have any NT loads pre-SSE41.
2317     if (!!(Flags & MachineMemOperand::MOLoad))
2318       return (Align < 16 || !Subtarget.hasSSE41());
2319     return false;
2320   }
2321   // Misaligned accesses of any size are always allowed.
2322   return true;
2323 }
2324 
2325 /// Return the entry encoding for a jump table in the
2326 /// current function.  The returned value is a member of the
2327 /// MachineJumpTableInfo::JTEntryKind enum.
getJumpTableEncoding() const2328 unsigned X86TargetLowering::getJumpTableEncoding() const {
2329   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2330   // symbol.
2331   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2332     return MachineJumpTableInfo::EK_Custom32;
2333 
2334   // Otherwise, use the normal jump table encoding heuristics.
2335   return TargetLowering::getJumpTableEncoding();
2336 }
2337 
useSoftFloat() const2338 bool X86TargetLowering::useSoftFloat() const {
2339   return Subtarget.useSoftFloat();
2340 }
2341 
markLibCallAttributes(MachineFunction * MF,unsigned CC,ArgListTy & Args) const2342 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2343                                               ArgListTy &Args) const {
2344 
2345   // Only relabel X86-32 for C / Stdcall CCs.
2346   if (Subtarget.is64Bit())
2347     return;
2348   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2349     return;
2350   unsigned ParamRegs = 0;
2351   if (auto *M = MF->getFunction().getParent())
2352     ParamRegs = M->getNumberRegisterParameters();
2353 
2354   // Mark the first N int arguments as having reg
2355   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2356     Type *T = Args[Idx].Ty;
2357     if (T->isIntOrPtrTy())
2358       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2359         unsigned numRegs = 1;
2360         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2361           numRegs = 2;
2362         if (ParamRegs < numRegs)
2363           return;
2364         ParamRegs -= numRegs;
2365         Args[Idx].IsInReg = true;
2366       }
2367   }
2368 }
2369 
2370 const MCExpr *
LowerCustomJumpTableEntry(const MachineJumpTableInfo * MJTI,const MachineBasicBlock * MBB,unsigned uid,MCContext & Ctx) const2371 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2372                                              const MachineBasicBlock *MBB,
2373                                              unsigned uid,MCContext &Ctx) const{
2374   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2375   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2376   // entries.
2377   return MCSymbolRefExpr::create(MBB->getSymbol(),
2378                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2379 }
2380 
2381 /// Returns relocation base for the given PIC jumptable.
getPICJumpTableRelocBase(SDValue Table,SelectionDAG & DAG) const2382 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2383                                                     SelectionDAG &DAG) const {
2384   if (!Subtarget.is64Bit())
2385     // This doesn't have SDLoc associated with it, but is not really the
2386     // same as a Register.
2387     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2388                        getPointerTy(DAG.getDataLayout()));
2389   return Table;
2390 }
2391 
2392 /// This returns the relocation base for the given PIC jumptable,
2393 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2394 const MCExpr *X86TargetLowering::
getPICJumpTableRelocBaseExpr(const MachineFunction * MF,unsigned JTI,MCContext & Ctx) const2395 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2396                              MCContext &Ctx) const {
2397   // X86-64 uses RIP relative addressing based on the jump table label.
2398   if (Subtarget.isPICStyleRIPRel())
2399     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2400 
2401   // Otherwise, the reference is relative to the PIC base.
2402   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2403 }
2404 
2405 std::pair<const TargetRegisterClass *, uint8_t>
findRepresentativeClass(const TargetRegisterInfo * TRI,MVT VT) const2406 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2407                                            MVT VT) const {
2408   const TargetRegisterClass *RRC = nullptr;
2409   uint8_t Cost = 1;
2410   switch (VT.SimpleTy) {
2411   default:
2412     return TargetLowering::findRepresentativeClass(TRI, VT);
2413   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2414     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2415     break;
2416   case MVT::x86mmx:
2417     RRC = &X86::VR64RegClass;
2418     break;
2419   case MVT::f32: case MVT::f64:
2420   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2421   case MVT::v4f32: case MVT::v2f64:
2422   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2423   case MVT::v8f32: case MVT::v4f64:
2424   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2425   case MVT::v16f32: case MVT::v8f64:
2426     RRC = &X86::VR128XRegClass;
2427     break;
2428   }
2429   return std::make_pair(RRC, Cost);
2430 }
2431 
getAddressSpace() const2432 unsigned X86TargetLowering::getAddressSpace() const {
2433   if (Subtarget.is64Bit())
2434     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2435   return 256;
2436 }
2437 
hasStackGuardSlotTLS(const Triple & TargetTriple)2438 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2439   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2440          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2441 }
2442 
SegmentOffset(IRBuilder<> & IRB,unsigned Offset,unsigned AddressSpace)2443 static Constant* SegmentOffset(IRBuilder<> &IRB,
2444                                unsigned Offset, unsigned AddressSpace) {
2445   return ConstantExpr::getIntToPtr(
2446       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2447       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2448 }
2449 
getIRStackGuard(IRBuilder<> & IRB) const2450 Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2451   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2452   // tcbhead_t; use it instead of the usual global variable (see
2453   // sysdeps/{i386,x86_64}/nptl/tls.h)
2454   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2455     if (Subtarget.isTargetFuchsia()) {
2456       // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2457       return SegmentOffset(IRB, 0x10, getAddressSpace());
2458     } else {
2459       // %fs:0x28, unless we're using a Kernel code model, in which case
2460       // it's %gs:0x28.  gs:0x14 on i386.
2461       unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2462       return SegmentOffset(IRB, Offset, getAddressSpace());
2463     }
2464   }
2465 
2466   return TargetLowering::getIRStackGuard(IRB);
2467 }
2468 
insertSSPDeclarations(Module & M) const2469 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2470   // MSVC CRT provides functionalities for stack protection.
2471   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2472       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2473     // MSVC CRT has a global variable holding security cookie.
2474     M.getOrInsertGlobal("__security_cookie",
2475                         Type::getInt8PtrTy(M.getContext()));
2476 
2477     // MSVC CRT has a function to validate security cookie.
2478     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2479         "__security_check_cookie", Type::getVoidTy(M.getContext()),
2480         Type::getInt8PtrTy(M.getContext()));
2481     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2482       F->setCallingConv(CallingConv::X86_FastCall);
2483       F->addAttribute(1, Attribute::AttrKind::InReg);
2484     }
2485     return;
2486   }
2487   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2488   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2489     return;
2490   TargetLowering::insertSSPDeclarations(M);
2491 }
2492 
getSDagStackGuard(const Module & M) const2493 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2494   // MSVC CRT has a global variable holding security cookie.
2495   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2496       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2497     return M.getGlobalVariable("__security_cookie");
2498   }
2499   return TargetLowering::getSDagStackGuard(M);
2500 }
2501 
getSSPStackGuardCheck(const Module & M) const2502 Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2503   // MSVC CRT has a function to validate security cookie.
2504   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2505       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2506     return M.getFunction("__security_check_cookie");
2507   }
2508   return TargetLowering::getSSPStackGuardCheck(M);
2509 }
2510 
getSafeStackPointerLocation(IRBuilder<> & IRB) const2511 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2512   if (Subtarget.getTargetTriple().isOSContiki())
2513     return getDefaultSafeStackPointerLocation(IRB, false);
2514 
2515   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2516   // definition of TLS_SLOT_SAFESTACK in
2517   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2518   if (Subtarget.isTargetAndroid()) {
2519     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2520     // %gs:0x24 on i386
2521     unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2522     return SegmentOffset(IRB, Offset, getAddressSpace());
2523   }
2524 
2525   // Fuchsia is similar.
2526   if (Subtarget.isTargetFuchsia()) {
2527     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2528     return SegmentOffset(IRB, 0x18, getAddressSpace());
2529   }
2530 
2531   return TargetLowering::getSafeStackPointerLocation(IRB);
2532 }
2533 
isNoopAddrSpaceCast(unsigned SrcAS,unsigned DestAS) const2534 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2535                                             unsigned DestAS) const {
2536   assert(SrcAS != DestAS && "Expected different address spaces!");
2537 
2538   const TargetMachine &TM = getTargetMachine();
2539   if (TM.getPointerSize(SrcAS) != TM.getPointerSize(DestAS))
2540     return false;
2541 
2542   return SrcAS < 256 && DestAS < 256;
2543 }
2544 
2545 //===----------------------------------------------------------------------===//
2546 //               Return Value Calling Convention Implementation
2547 //===----------------------------------------------------------------------===//
2548 
CanLowerReturn(CallingConv::ID CallConv,MachineFunction & MF,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,LLVMContext & Context) const2549 bool X86TargetLowering::CanLowerReturn(
2550     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2551     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2552   SmallVector<CCValAssign, 16> RVLocs;
2553   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2554   return CCInfo.CheckReturn(Outs, RetCC_X86);
2555 }
2556 
getScratchRegisters(CallingConv::ID) const2557 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2558   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2559   return ScratchRegs;
2560 }
2561 
2562 /// Lowers masks values (v*i1) to the local register values
2563 /// \returns DAG node after lowering to register type
lowerMasksToReg(const SDValue & ValArg,const EVT & ValLoc,const SDLoc & Dl,SelectionDAG & DAG)2564 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2565                                const SDLoc &Dl, SelectionDAG &DAG) {
2566   EVT ValVT = ValArg.getValueType();
2567 
2568   if (ValVT == MVT::v1i1)
2569     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2570                        DAG.getIntPtrConstant(0, Dl));
2571 
2572   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2573       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2574     // Two stage lowering might be required
2575     // bitcast:   v8i1 -> i8 / v16i1 -> i16
2576     // anyextend: i8   -> i32 / i16   -> i32
2577     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2578     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2579     if (ValLoc == MVT::i32)
2580       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2581     return ValToCopy;
2582   }
2583 
2584   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2585       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2586     // One stage lowering is required
2587     // bitcast:   v32i1 -> i32 / v64i1 -> i64
2588     return DAG.getBitcast(ValLoc, ValArg);
2589   }
2590 
2591   return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2592 }
2593 
2594 /// Breaks v64i1 value into two registers and adds the new node to the DAG
Passv64i1ArgInRegs(const SDLoc & Dl,SelectionDAG & DAG,SDValue & Arg,SmallVectorImpl<std::pair<Register,SDValue>> & RegsToPass,CCValAssign & VA,CCValAssign & NextVA,const X86Subtarget & Subtarget)2595 static void Passv64i1ArgInRegs(
2596     const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
2597     SmallVectorImpl<std::pair<Register, SDValue>> &RegsToPass, CCValAssign &VA,
2598     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2599   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2600   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2601   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2602   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2603          "The value should reside in two registers");
2604 
2605   // Before splitting the value we cast it to i64
2606   Arg = DAG.getBitcast(MVT::i64, Arg);
2607 
2608   // Splitting the value into two i32 types
2609   SDValue Lo, Hi;
2610   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2611                    DAG.getConstant(0, Dl, MVT::i32));
2612   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2613                    DAG.getConstant(1, Dl, MVT::i32));
2614 
2615   // Attach the two i32 types into corresponding registers
2616   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2617   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2618 }
2619 
2620 SDValue
LowerReturn(SDValue Chain,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SDLoc & dl,SelectionDAG & DAG) const2621 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2622                                bool isVarArg,
2623                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2624                                const SmallVectorImpl<SDValue> &OutVals,
2625                                const SDLoc &dl, SelectionDAG &DAG) const {
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2628 
2629   // In some cases we need to disable registers from the default CSR list.
2630   // For example, when they are used for argument passing.
2631   bool ShouldDisableCalleeSavedRegister =
2632       CallConv == CallingConv::X86_RegCall ||
2633       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2634 
2635   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2636     report_fatal_error("X86 interrupts may not return any value");
2637 
2638   SmallVector<CCValAssign, 16> RVLocs;
2639   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2640   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2641 
2642   SmallVector<std::pair<Register, SDValue>, 4> RetVals;
2643   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2644        ++I, ++OutsIndex) {
2645     CCValAssign &VA = RVLocs[I];
2646     assert(VA.isRegLoc() && "Can only return in registers!");
2647 
2648     // Add the register to the CalleeSaveDisableRegs list.
2649     if (ShouldDisableCalleeSavedRegister)
2650       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2651 
2652     SDValue ValToCopy = OutVals[OutsIndex];
2653     EVT ValVT = ValToCopy.getValueType();
2654 
2655     // Promote values to the appropriate types.
2656     if (VA.getLocInfo() == CCValAssign::SExt)
2657       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2658     else if (VA.getLocInfo() == CCValAssign::ZExt)
2659       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2660     else if (VA.getLocInfo() == CCValAssign::AExt) {
2661       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2662         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2663       else
2664         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2665     }
2666     else if (VA.getLocInfo() == CCValAssign::BCvt)
2667       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2668 
2669     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2670            "Unexpected FP-extend for return value.");
2671 
2672     // Report an error if we have attempted to return a value via an XMM
2673     // register and SSE was disabled.
2674     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
2675       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2676       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2677     } else if (!Subtarget.hasSSE2() &&
2678                X86::FR64XRegClass.contains(VA.getLocReg()) &&
2679                ValVT == MVT::f64) {
2680       // When returning a double via an XMM register, report an error if SSE2 is
2681       // not enabled.
2682       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2683       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2684     }
2685 
2686     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2687     // the RET instruction and handled by the FP Stackifier.
2688     if (VA.getLocReg() == X86::FP0 ||
2689         VA.getLocReg() == X86::FP1) {
2690       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2691       // change the value to the FP stack register class.
2692       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2693         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2694       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2695       // Don't emit a copytoreg.
2696       continue;
2697     }
2698 
2699     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2700     // which is returned in RAX / RDX.
2701     if (Subtarget.is64Bit()) {
2702       if (ValVT == MVT::x86mmx) {
2703         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2704           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2705           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2706                                   ValToCopy);
2707           // If we don't have SSE2 available, convert to v4f32 so the generated
2708           // register is legal.
2709           if (!Subtarget.hasSSE2())
2710             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2711         }
2712       }
2713     }
2714 
2715     if (VA.needsCustom()) {
2716       assert(VA.getValVT() == MVT::v64i1 &&
2717              "Currently the only custom case is when we split v64i1 to 2 regs");
2718 
2719       Passv64i1ArgInRegs(dl, DAG, ValToCopy, RetVals, VA, RVLocs[++I],
2720                          Subtarget);
2721 
2722       // Add the second register to the CalleeSaveDisableRegs list.
2723       if (ShouldDisableCalleeSavedRegister)
2724         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2725     } else {
2726       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2727     }
2728   }
2729 
2730   SDValue Flag;
2731   SmallVector<SDValue, 6> RetOps;
2732   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2733   // Operand #1 = Bytes To Pop
2734   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2735                    MVT::i32));
2736 
2737   // Copy the result values into the output registers.
2738   for (auto &RetVal : RetVals) {
2739     if (RetVal.first == X86::FP0 || RetVal.first == X86::FP1) {
2740       RetOps.push_back(RetVal.second);
2741       continue; // Don't emit a copytoreg.
2742     }
2743 
2744     Chain = DAG.getCopyToReg(Chain, dl, RetVal.first, RetVal.second, Flag);
2745     Flag = Chain.getValue(1);
2746     RetOps.push_back(
2747         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
2748   }
2749 
2750   // Swift calling convention does not require we copy the sret argument
2751   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2752 
2753   // All x86 ABIs require that for returning structs by value we copy
2754   // the sret argument into %rax/%eax (depending on ABI) for the return.
2755   // We saved the argument into a virtual register in the entry block,
2756   // so now we copy the value out and into %rax/%eax.
2757   //
2758   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2759   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2760   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2761   // either case FuncInfo->setSRetReturnReg() will have been called.
2762   if (Register SRetReg = FuncInfo->getSRetReturnReg()) {
2763     // When we have both sret and another return value, we should use the
2764     // original Chain stored in RetOps[0], instead of the current Chain updated
2765     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2766 
2767     // For the case of sret and another return value, we have
2768     //   Chain_0 at the function entry
2769     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
2770     // If we use Chain_1 in getCopyFromReg, we will have
2771     //   Val = getCopyFromReg(Chain_1)
2772     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
2773 
2774     // getCopyToReg(Chain_0) will be glued together with
2775     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2776     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2777     //   Data dependency from Unit B to Unit A due to usage of Val in
2778     //     getCopyToReg(Chain_1, Val)
2779     //   Chain dependency from Unit A to Unit B
2780 
2781     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2782     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2783                                      getPointerTy(MF.getDataLayout()));
2784 
2785     Register RetValReg
2786         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2787           X86::RAX : X86::EAX;
2788     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2789     Flag = Chain.getValue(1);
2790 
2791     // RAX/EAX now acts like a return value.
2792     RetOps.push_back(
2793         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2794 
2795     // Add the returned register to the CalleeSaveDisableRegs list.
2796     if (ShouldDisableCalleeSavedRegister)
2797       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2798   }
2799 
2800   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2801   const MCPhysReg *I =
2802       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2803   if (I) {
2804     for (; *I; ++I) {
2805       if (X86::GR64RegClass.contains(*I))
2806         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2807       else
2808         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2809     }
2810   }
2811 
2812   RetOps[0] = Chain;  // Update chain.
2813 
2814   // Add the flag if we have it.
2815   if (Flag.getNode())
2816     RetOps.push_back(Flag);
2817 
2818   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2819   if (CallConv == CallingConv::X86_INTR)
2820     opcode = X86ISD::IRET;
2821   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2822 }
2823 
isUsedByReturnOnly(SDNode * N,SDValue & Chain) const2824 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2825   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2826     return false;
2827 
2828   SDValue TCChain = Chain;
2829   SDNode *Copy = *N->use_begin();
2830   if (Copy->getOpcode() == ISD::CopyToReg) {
2831     // If the copy has a glue operand, we conservatively assume it isn't safe to
2832     // perform a tail call.
2833     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2834       return false;
2835     TCChain = Copy->getOperand(0);
2836   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2837     return false;
2838 
2839   bool HasRet = false;
2840   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2841        UI != UE; ++UI) {
2842     if (UI->getOpcode() != X86ISD::RET_FLAG)
2843       return false;
2844     // If we are returning more than one value, we can definitely
2845     // not make a tail call see PR19530
2846     if (UI->getNumOperands() > 4)
2847       return false;
2848     if (UI->getNumOperands() == 4 &&
2849         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2850       return false;
2851     HasRet = true;
2852   }
2853 
2854   if (!HasRet)
2855     return false;
2856 
2857   Chain = TCChain;
2858   return true;
2859 }
2860 
getTypeForExtReturn(LLVMContext & Context,EVT VT,ISD::NodeType ExtendKind) const2861 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2862                                            ISD::NodeType ExtendKind) const {
2863   MVT ReturnMVT = MVT::i32;
2864 
2865   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2866   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2867     // The ABI does not require i1, i8 or i16 to be extended.
2868     //
2869     // On Darwin, there is code in the wild relying on Clang's old behaviour of
2870     // always extending i8/i16 return values, so keep doing that for now.
2871     // (PR26665).
2872     ReturnMVT = MVT::i8;
2873   }
2874 
2875   EVT MinVT = getRegisterType(Context, ReturnMVT);
2876   return VT.bitsLT(MinVT) ? MinVT : VT;
2877 }
2878 
2879 /// Reads two 32 bit registers and creates a 64 bit mask value.
2880 /// \param VA The current 32 bit value that need to be assigned.
2881 /// \param NextVA The next 32 bit value that need to be assigned.
2882 /// \param Root The parent DAG node.
2883 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2884 ///                        glue purposes. In the case the DAG is already using
2885 ///                        physical register instead of virtual, we should glue
2886 ///                        our new SDValue to InFlag SDvalue.
2887 /// \return a new SDvalue of size 64bit.
getv64i1Argument(CCValAssign & VA,CCValAssign & NextVA,SDValue & Root,SelectionDAG & DAG,const SDLoc & Dl,const X86Subtarget & Subtarget,SDValue * InFlag=nullptr)2888 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2889                                 SDValue &Root, SelectionDAG &DAG,
2890                                 const SDLoc &Dl, const X86Subtarget &Subtarget,
2891                                 SDValue *InFlag = nullptr) {
2892   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2893   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2894   assert(VA.getValVT() == MVT::v64i1 &&
2895          "Expecting first location of 64 bit width type");
2896   assert(NextVA.getValVT() == VA.getValVT() &&
2897          "The locations should have the same type");
2898   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2899          "The values should reside in two registers");
2900 
2901   SDValue Lo, Hi;
2902   SDValue ArgValueLo, ArgValueHi;
2903 
2904   MachineFunction &MF = DAG.getMachineFunction();
2905   const TargetRegisterClass *RC = &X86::GR32RegClass;
2906 
2907   // Read a 32 bit value from the registers.
2908   if (nullptr == InFlag) {
2909     // When no physical register is present,
2910     // create an intermediate virtual register.
2911     Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
2912     ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2913     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2914     ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2915   } else {
2916     // When a physical register is available read the value from it and glue
2917     // the reads together.
2918     ArgValueLo =
2919       DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2920     *InFlag = ArgValueLo.getValue(2);
2921     ArgValueHi =
2922       DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2923     *InFlag = ArgValueHi.getValue(2);
2924   }
2925 
2926   // Convert the i32 type into v32i1 type.
2927   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2928 
2929   // Convert the i32 type into v32i1 type.
2930   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2931 
2932   // Concatenate the two values together.
2933   return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2934 }
2935 
2936 /// The function will lower a register of various sizes (8/16/32/64)
2937 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2938 /// \returns a DAG node contains the operand after lowering to mask type.
lowerRegToMasks(const SDValue & ValArg,const EVT & ValVT,const EVT & ValLoc,const SDLoc & Dl,SelectionDAG & DAG)2939 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2940                                const EVT &ValLoc, const SDLoc &Dl,
2941                                SelectionDAG &DAG) {
2942   SDValue ValReturned = ValArg;
2943 
2944   if (ValVT == MVT::v1i1)
2945     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2946 
2947   if (ValVT == MVT::v64i1) {
2948     // In 32 bit machine, this case is handled by getv64i1Argument
2949     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2950     // In 64 bit machine, There is no need to truncate the value only bitcast
2951   } else {
2952     MVT maskLen;
2953     switch (ValVT.getSimpleVT().SimpleTy) {
2954     case MVT::v8i1:
2955       maskLen = MVT::i8;
2956       break;
2957     case MVT::v16i1:
2958       maskLen = MVT::i16;
2959       break;
2960     case MVT::v32i1:
2961       maskLen = MVT::i32;
2962       break;
2963     default:
2964       llvm_unreachable("Expecting a vector of i1 types");
2965     }
2966 
2967     ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2968   }
2969   return DAG.getBitcast(ValVT, ValReturned);
2970 }
2971 
2972 /// Lower the result values of a call into the
2973 /// appropriate copies out of appropriate physical registers.
2974 ///
LowerCallResult(SDValue Chain,SDValue InFlag,CallingConv::ID CallConv,bool isVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals,uint32_t * RegMask) const2975 SDValue X86TargetLowering::LowerCallResult(
2976     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2977     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2978     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2979     uint32_t *RegMask) const {
2980 
2981   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2982   // Assign locations to each value returned by this call.
2983   SmallVector<CCValAssign, 16> RVLocs;
2984   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2985                  *DAG.getContext());
2986   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2987 
2988   // Copy all of the result registers out of their specified physreg.
2989   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2990        ++I, ++InsIndex) {
2991     CCValAssign &VA = RVLocs[I];
2992     EVT CopyVT = VA.getLocVT();
2993 
2994     // In some calling conventions we need to remove the used registers
2995     // from the register mask.
2996     if (RegMask) {
2997       for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2998            SubRegs.isValid(); ++SubRegs)
2999         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3000     }
3001 
3002     // Report an error if there was an attempt to return FP values via XMM
3003     // registers.
3004     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3005       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3006       if (VA.getLocReg() == X86::XMM1)
3007         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3008       else
3009         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3010     } else if (!Subtarget.hasSSE2() &&
3011                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3012                CopyVT == MVT::f64) {
3013       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3014       if (VA.getLocReg() == X86::XMM1)
3015         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3016       else
3017         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3018     }
3019 
3020     // If we prefer to use the value in xmm registers, copy it out as f80 and
3021     // use a truncate to move it from fp stack reg to xmm reg.
3022     bool RoundAfterCopy = false;
3023     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3024         isScalarFPTypeInSSEReg(VA.getValVT())) {
3025       if (!Subtarget.hasX87())
3026         report_fatal_error("X87 register return with X87 disabled");
3027       CopyVT = MVT::f80;
3028       RoundAfterCopy = (CopyVT != VA.getLocVT());
3029     }
3030 
3031     SDValue Val;
3032     if (VA.needsCustom()) {
3033       assert(VA.getValVT() == MVT::v64i1 &&
3034              "Currently the only custom case is when we split v64i1 to 2 regs");
3035       Val =
3036           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
3037     } else {
3038       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
3039                   .getValue(1);
3040       Val = Chain.getValue(0);
3041       InFlag = Chain.getValue(2);
3042     }
3043 
3044     if (RoundAfterCopy)
3045       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3046                         // This truncation won't change the value.
3047                         DAG.getIntPtrConstant(1, dl));
3048 
3049     if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
3050       if (VA.getValVT().isVector() &&
3051           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3052            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3053         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3054         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3055       } else
3056         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3057     }
3058 
3059     if (VA.getLocInfo() == CCValAssign::BCvt)
3060       Val = DAG.getBitcast(VA.getValVT(), Val);
3061 
3062     InVals.push_back(Val);
3063   }
3064 
3065   return Chain;
3066 }
3067 
3068 //===----------------------------------------------------------------------===//
3069 //                C & StdCall & Fast Calling Convention implementation
3070 //===----------------------------------------------------------------------===//
3071 //  StdCall calling convention seems to be standard for many Windows' API
3072 //  routines and around. It differs from C calling convention just a little:
3073 //  callee should clean up the stack, not caller. Symbols should be also
3074 //  decorated in some fancy way :) It doesn't support any vector arguments.
3075 //  For info on fast calling convention see Fast Calling Convention (tail call)
3076 //  implementation LowerX86_32FastCCCallTo.
3077 
3078 /// CallIsStructReturn - Determines whether a call uses struct return
3079 /// semantics.
3080 enum StructReturnType {
3081   NotStructReturn,
3082   RegStructReturn,
3083   StackStructReturn
3084 };
3085 static StructReturnType
callIsStructReturn(ArrayRef<ISD::OutputArg> Outs,bool IsMCU)3086 callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
3087   if (Outs.empty())
3088     return NotStructReturn;
3089 
3090   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
3091   if (!Flags.isSRet())
3092     return NotStructReturn;
3093   if (Flags.isInReg() || IsMCU)
3094     return RegStructReturn;
3095   return StackStructReturn;
3096 }
3097 
3098 /// Determines whether a function uses struct return semantics.
3099 static StructReturnType
argsAreStructReturn(ArrayRef<ISD::InputArg> Ins,bool IsMCU)3100 argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
3101   if (Ins.empty())
3102     return NotStructReturn;
3103 
3104   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
3105   if (!Flags.isSRet())
3106     return NotStructReturn;
3107   if (Flags.isInReg() || IsMCU)
3108     return RegStructReturn;
3109   return StackStructReturn;
3110 }
3111 
3112 /// Make a copy of an aggregate at address specified by "Src" to address
3113 /// "Dst" with size and alignment information specified by the specific
3114 /// parameter attribute. The copy will be passed as a byval function parameter.
CreateCopyOfByValArgument(SDValue Src,SDValue Dst,SDValue Chain,ISD::ArgFlagsTy Flags,SelectionDAG & DAG,const SDLoc & dl)3115 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3116                                          SDValue Chain, ISD::ArgFlagsTy Flags,
3117                                          SelectionDAG &DAG, const SDLoc &dl) {
3118   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
3119 
3120   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
3121                        /*isVolatile*/ false, /*AlwaysInline=*/true,
3122                        /*isTailCall*/ false,
3123                        /*MustPreserveCheriCapabilities=*/false,
3124                        MachinePointerInfo(), MachinePointerInfo());
3125 }
3126 
3127 /// Return true if the calling convention is one that we can guarantee TCO for.
canGuaranteeTCO(CallingConv::ID CC)3128 static bool canGuaranteeTCO(CallingConv::ID CC) {
3129   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3130           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3131           CC == CallingConv::HHVM || CC == CallingConv::Tail);
3132 }
3133 
3134 /// Return true if we might ever do TCO for calls with this calling convention.
mayTailCallThisCC(CallingConv::ID CC)3135 static bool mayTailCallThisCC(CallingConv::ID CC) {
3136   switch (CC) {
3137   // C calling conventions:
3138   case CallingConv::C:
3139   case CallingConv::Win64:
3140   case CallingConv::X86_64_SysV:
3141   // Callee pop conventions:
3142   case CallingConv::X86_ThisCall:
3143   case CallingConv::X86_StdCall:
3144   case CallingConv::X86_VectorCall:
3145   case CallingConv::X86_FastCall:
3146   // Swift:
3147   case CallingConv::Swift:
3148     return true;
3149   default:
3150     return canGuaranteeTCO(CC);
3151   }
3152 }
3153 
3154 /// Return true if the function is being made into a tailcall target by
3155 /// changing its ABI.
shouldGuaranteeTCO(CallingConv::ID CC,bool GuaranteedTailCallOpt)3156 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3157   return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) || CC == CallingConv::Tail;
3158 }
3159 
mayBeEmittedAsTailCall(const CallInst * CI) const3160 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3161   if (!CI->isTailCall())
3162     return false;
3163 
3164   CallingConv::ID CalleeCC = CI->getCallingConv();
3165   if (!mayTailCallThisCC(CalleeCC))
3166     return false;
3167 
3168   return true;
3169 }
3170 
3171 SDValue
LowerMemArgument(SDValue Chain,CallingConv::ID CallConv,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,MachineFrameInfo & MFI,unsigned i) const3172 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3173                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3174                                     const SDLoc &dl, SelectionDAG &DAG,
3175                                     const CCValAssign &VA,
3176                                     MachineFrameInfo &MFI, unsigned i) const {
3177   // Create the nodes corresponding to a load from this parameter slot.
3178   ISD::ArgFlagsTy Flags = Ins[i].Flags;
3179   bool AlwaysUseMutable = shouldGuaranteeTCO(
3180       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3181   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3182   EVT ValVT;
3183   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3184 
3185   // If value is passed by pointer we have address passed instead of the value
3186   // itself. No need to extend if the mask value and location share the same
3187   // absolute size.
3188   bool ExtendedInMem =
3189       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3190       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3191 
3192   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3193     ValVT = VA.getLocVT();
3194   else
3195     ValVT = VA.getValVT();
3196 
3197   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3198   // changed with more analysis.
3199   // In case of tail call optimization mark all arguments mutable. Since they
3200   // could be overwritten by lowering of arguments in case of a tail call.
3201   if (Flags.isByVal()) {
3202     unsigned Bytes = Flags.getByValSize();
3203     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3204 
3205     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3206     // can be improved with deeper analysis.
3207     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3208                                    /*isAliased=*/true);
3209     return DAG.getFrameIndex(FI, PtrVT);
3210   }
3211 
3212   // This is an argument in memory. We might be able to perform copy elision.
3213   // If the argument is passed directly in memory without any extension, then we
3214   // can perform copy elision. Large vector types, for example, may be passed
3215   // indirectly by pointer.
3216   if (Flags.isCopyElisionCandidate() &&
3217       VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem) {
3218     EVT ArgVT = Ins[i].ArgVT;
3219     SDValue PartAddr;
3220     if (Ins[i].PartOffset == 0) {
3221       // If this is a one-part value or the first part of a multi-part value,
3222       // create a stack object for the entire argument value type and return a
3223       // load from our portion of it. This assumes that if the first part of an
3224       // argument is in memory, the rest will also be in memory.
3225       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3226                                      /*IsImmutable=*/false);
3227       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3228       return DAG.getLoad(
3229           ValVT, dl, Chain, PartAddr,
3230           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3231     } else {
3232       // This is not the first piece of an argument in memory. See if there is
3233       // already a fixed stack object including this offset. If so, assume it
3234       // was created by the PartOffset == 0 branch above and create a load from
3235       // the appropriate offset into it.
3236       int64_t PartBegin = VA.getLocMemOffset();
3237       int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3238       int FI = MFI.getObjectIndexBegin();
3239       for (; MFI.isFixedObjectIndex(FI); ++FI) {
3240         int64_t ObjBegin = MFI.getObjectOffset(FI);
3241         int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3242         if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3243           break;
3244       }
3245       if (MFI.isFixedObjectIndex(FI)) {
3246         SDValue Addr =
3247             DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3248                         DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3249         return DAG.getLoad(
3250             ValVT, dl, Chain, Addr,
3251             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3252                                               Ins[i].PartOffset));
3253       }
3254     }
3255   }
3256 
3257   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3258                                  VA.getLocMemOffset(), isImmutable);
3259 
3260   // Set SExt or ZExt flag.
3261   if (VA.getLocInfo() == CCValAssign::ZExt) {
3262     MFI.setObjectZExt(FI, true);
3263   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3264     MFI.setObjectSExt(FI, true);
3265   }
3266 
3267   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3268   SDValue Val = DAG.getLoad(
3269       ValVT, dl, Chain, FIN,
3270       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3271   return ExtendedInMem
3272              ? (VA.getValVT().isVector()
3273                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3274                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3275              : Val;
3276 }
3277 
3278 // FIXME: Get this from tablegen.
get64BitArgumentGPRs(CallingConv::ID CallConv,const X86Subtarget & Subtarget)3279 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3280                                                 const X86Subtarget &Subtarget) {
3281   assert(Subtarget.is64Bit());
3282 
3283   if (Subtarget.isCallingConvWin64(CallConv)) {
3284     static const MCPhysReg GPR64ArgRegsWin64[] = {
3285       X86::RCX, X86::RDX, X86::R8,  X86::R9
3286     };
3287     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3288   }
3289 
3290   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3291     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3292   };
3293   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3294 }
3295 
3296 // FIXME: Get this from tablegen.
get64BitArgumentXMMs(MachineFunction & MF,CallingConv::ID CallConv,const X86Subtarget & Subtarget)3297 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3298                                                 CallingConv::ID CallConv,
3299                                                 const X86Subtarget &Subtarget) {
3300   assert(Subtarget.is64Bit());
3301   if (Subtarget.isCallingConvWin64(CallConv)) {
3302     // The XMM registers which might contain var arg parameters are shadowed
3303     // in their paired GPR.  So we only need to save the GPR to their home
3304     // slots.
3305     // TODO: __vectorcall will change this.
3306     return None;
3307   }
3308 
3309   const Function &F = MF.getFunction();
3310   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3311   bool isSoftFloat = Subtarget.useSoftFloat();
3312   assert(!(isSoftFloat && NoImplicitFloatOps) &&
3313          "SSE register cannot be used when SSE is disabled!");
3314   if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3315     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3316     // registers.
3317     return None;
3318 
3319   static const MCPhysReg XMMArgRegs64Bit[] = {
3320     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3321     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3322   };
3323   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3324 }
3325 
3326 #ifndef NDEBUG
isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs)3327 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3328   return llvm::is_sorted(
3329       ArgLocs, [](const CCValAssign &A, const CCValAssign &B) -> bool {
3330         return A.getValNo() < B.getValNo();
3331       });
3332 }
3333 #endif
3334 
3335 namespace {
3336 /// This is a helper class for lowering variable arguments parameters.
3337 class VarArgsLoweringHelper {
3338 public:
VarArgsLoweringHelper(X86MachineFunctionInfo * FuncInfo,const SDLoc & Loc,SelectionDAG & DAG,const X86Subtarget & Subtarget,CallingConv::ID CallConv,CCState & CCInfo)3339   VarArgsLoweringHelper(X86MachineFunctionInfo *FuncInfo, const SDLoc &Loc,
3340                         SelectionDAG &DAG, const X86Subtarget &Subtarget,
3341                         CallingConv::ID CallConv, CCState &CCInfo)
3342       : FuncInfo(FuncInfo), DL(Loc), DAG(DAG), Subtarget(Subtarget),
3343         TheMachineFunction(DAG.getMachineFunction()),
3344         TheFunction(TheMachineFunction.getFunction()),
3345         FrameInfo(TheMachineFunction.getFrameInfo()),
3346         FrameLowering(*Subtarget.getFrameLowering()),
3347         TargLowering(DAG.getTargetLoweringInfo()), CallConv(CallConv),
3348         CCInfo(CCInfo) {}
3349 
3350   // Lower variable arguments parameters.
3351   void lowerVarArgsParameters(SDValue &Chain, unsigned StackSize);
3352 
3353 private:
3354   void createVarArgAreaAndStoreRegisters(SDValue &Chain, unsigned StackSize);
3355 
3356   void forwardMustTailParameters(SDValue &Chain);
3357 
is64Bit()3358   bool is64Bit() { return Subtarget.is64Bit(); }
isWin64()3359   bool isWin64() { return Subtarget.isCallingConvWin64(CallConv); }
3360 
3361   X86MachineFunctionInfo *FuncInfo;
3362   const SDLoc &DL;
3363   SelectionDAG &DAG;
3364   const X86Subtarget &Subtarget;
3365   MachineFunction &TheMachineFunction;
3366   const Function &TheFunction;
3367   MachineFrameInfo &FrameInfo;
3368   const TargetFrameLowering &FrameLowering;
3369   const TargetLowering &TargLowering;
3370   CallingConv::ID CallConv;
3371   CCState &CCInfo;
3372 };
3373 } // namespace
3374 
createVarArgAreaAndStoreRegisters(SDValue & Chain,unsigned StackSize)3375 void VarArgsLoweringHelper::createVarArgAreaAndStoreRegisters(
3376     SDValue &Chain, unsigned StackSize) {
3377   // If the function takes variable number of arguments, make a frame index for
3378   // the start of the first vararg value... for expansion of llvm.va_start. We
3379   // can skip this if there are no va_start calls.
3380   if (is64Bit() || (CallConv != CallingConv::X86_FastCall &&
3381                     CallConv != CallingConv::X86_ThisCall)) {
3382     FuncInfo->setVarArgsFrameIndex(
3383         FrameInfo.CreateFixedObject(1, StackSize, true));
3384   }
3385 
3386   // Figure out if XMM registers are in use.
3387   assert(!(Subtarget.useSoftFloat() &&
3388            TheFunction.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3389          "SSE register cannot be used when SSE is disabled!");
3390 
3391   // 64-bit calling conventions support varargs and register parameters, so we
3392   // have to do extra work to spill them in the prologue.
3393   if (is64Bit()) {
3394     // Find the first unallocated argument registers.
3395     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3396     ArrayRef<MCPhysReg> ArgXMMs =
3397         get64BitArgumentXMMs(TheMachineFunction, CallConv, Subtarget);
3398     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3399     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3400 
3401     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3402            "SSE register cannot be used when SSE is disabled!");
3403 
3404     if (isWin64()) {
3405       // Get to the caller-allocated home save location.  Add 8 to account
3406       // for the return address.
3407       int HomeOffset = FrameLowering.getOffsetOfLocalArea() + 8;
3408       FuncInfo->setRegSaveFrameIndex(
3409           FrameInfo.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3410       // Fixup to set vararg frame on shadow area (4 x i64).
3411       if (NumIntRegs < 4)
3412         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3413     } else {
3414       // For X86-64, if there are vararg parameters that are passed via
3415       // registers, then we must store them to their spots on the stack so
3416       // they may be loaded by dereferencing the result of va_next.
3417       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3418       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3419       FuncInfo->setRegSaveFrameIndex(FrameInfo.CreateStackObject(
3420           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, Align(16), false));
3421     }
3422 
3423     SmallVector<SDValue, 6>
3424         LiveGPRs; // list of SDValue for GPR registers keeping live input value
3425     SmallVector<SDValue, 8> LiveXMMRegs; // list of SDValue for XMM registers
3426                                          // keeping live input value
3427     SDValue ALVal; // if applicable keeps SDValue for %al register
3428 
3429     // Gather all the live in physical registers.
3430     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3431       Register GPR = TheMachineFunction.addLiveIn(Reg, &X86::GR64RegClass);
3432       LiveGPRs.push_back(DAG.getCopyFromReg(Chain, DL, GPR, MVT::i64));
3433     }
3434     const auto &AvailableXmms = ArgXMMs.slice(NumXMMRegs);
3435     if (!AvailableXmms.empty()) {
3436       Register AL = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3437       ALVal = DAG.getCopyFromReg(Chain, DL, AL, MVT::i8);
3438       for (MCPhysReg Reg : AvailableXmms) {
3439         Register XMMReg = TheMachineFunction.addLiveIn(Reg, &X86::VR128RegClass);
3440         LiveXMMRegs.push_back(
3441             DAG.getCopyFromReg(Chain, DL, XMMReg, MVT::v4f32));
3442       }
3443     }
3444 
3445     // Store the integer parameter registers.
3446     SmallVector<SDValue, 8> MemOps;
3447     SDValue RSFIN =
3448         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3449                           TargLowering.getPointerTy(DAG.getDataLayout()));
3450     unsigned Offset = FuncInfo->getVarArgsGPOffset();
3451     for (SDValue Val : LiveGPRs) {
3452       SDValue FIN = DAG.getNode(ISD::ADD, DL,
3453                                 TargLowering.getPointerTy(DAG.getDataLayout()),
3454                                 RSFIN, DAG.getIntPtrConstant(Offset, DL));
3455       SDValue Store =
3456           DAG.getStore(Val.getValue(1), DL, Val, FIN,
3457                        MachinePointerInfo::getFixedStack(
3458                            DAG.getMachineFunction(),
3459                            FuncInfo->getRegSaveFrameIndex(), Offset));
3460       MemOps.push_back(Store);
3461       Offset += 8;
3462     }
3463 
3464     // Now store the XMM (fp + vector) parameter registers.
3465     if (!LiveXMMRegs.empty()) {
3466       SmallVector<SDValue, 12> SaveXMMOps;
3467       SaveXMMOps.push_back(Chain);
3468       SaveXMMOps.push_back(ALVal);
3469       SaveXMMOps.push_back(
3470           DAG.getIntPtrConstant(FuncInfo->getRegSaveFrameIndex(), DL));
3471       SaveXMMOps.push_back(
3472           DAG.getIntPtrConstant(FuncInfo->getVarArgsFPOffset(), DL));
3473       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3474                         LiveXMMRegs.end());
3475       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, DL,
3476                                    MVT::Other, SaveXMMOps));
3477     }
3478 
3479     if (!MemOps.empty())
3480       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3481   }
3482 }
3483 
forwardMustTailParameters(SDValue & Chain)3484 void VarArgsLoweringHelper::forwardMustTailParameters(SDValue &Chain) {
3485   // Find the largest legal vector type.
3486   MVT VecVT = MVT::Other;
3487   // FIXME: Only some x86_32 calling conventions support AVX512.
3488   if (Subtarget.useAVX512Regs() &&
3489       (is64Bit() || (CallConv == CallingConv::X86_VectorCall ||
3490                      CallConv == CallingConv::Intel_OCL_BI)))
3491     VecVT = MVT::v16f32;
3492   else if (Subtarget.hasAVX())
3493     VecVT = MVT::v8f32;
3494   else if (Subtarget.hasSSE2())
3495     VecVT = MVT::v4f32;
3496 
3497   // We forward some GPRs and some vector types.
3498   SmallVector<MVT, 2> RegParmTypes;
3499   MVT IntVT = is64Bit() ? MVT::i64 : MVT::i32;
3500   RegParmTypes.push_back(IntVT);
3501   if (VecVT != MVT::Other)
3502     RegParmTypes.push_back(VecVT);
3503 
3504   // Compute the set of forwarded registers. The rest are scratch.
3505   SmallVectorImpl<ForwardedRegister> &Forwards =
3506       FuncInfo->getForwardedMustTailRegParms();
3507   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3508 
3509   // Forward AL for SysV x86_64 targets, since it is used for varargs.
3510   if (is64Bit() && !isWin64() && !CCInfo.isAllocated(X86::AL)) {
3511     Register ALVReg = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3512     Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3513   }
3514 
3515   // Copy all forwards from physical to virtual registers.
3516   for (ForwardedRegister &FR : Forwards) {
3517     // FIXME: Can we use a less constrained schedule?
3518     SDValue RegVal = DAG.getCopyFromReg(Chain, DL, FR.VReg, FR.VT);
3519     FR.VReg = TheMachineFunction.getRegInfo().createVirtualRegister(
3520         TargLowering.getRegClassFor(FR.VT));
3521     Chain = DAG.getCopyToReg(Chain, DL, FR.VReg, RegVal);
3522   }
3523 }
3524 
lowerVarArgsParameters(SDValue & Chain,unsigned StackSize)3525 void VarArgsLoweringHelper::lowerVarArgsParameters(SDValue &Chain,
3526                                                    unsigned StackSize) {
3527   // Set FrameIndex to the 0xAAAAAAA value to mark unset state.
3528   // If necessary, it would be set into the correct value later.
3529   FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3530   FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3531 
3532   if (FrameInfo.hasVAStart())
3533     createVarArgAreaAndStoreRegisters(Chain, StackSize);
3534 
3535   if (FrameInfo.hasMustTailInVarArgFunc())
3536     forwardMustTailParameters(Chain);
3537 }
3538 
LowerFormalArguments(SDValue Chain,CallingConv::ID CallConv,bool IsVarArg,const SmallVectorImpl<ISD::InputArg> & Ins,const SDLoc & dl,SelectionDAG & DAG,SmallVectorImpl<SDValue> & InVals) const3539 SDValue X86TargetLowering::LowerFormalArguments(
3540     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3541     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3542     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3543   MachineFunction &MF = DAG.getMachineFunction();
3544   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3545 
3546   const Function &F = MF.getFunction();
3547   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3548       F.getName() == "main")
3549     FuncInfo->setForceFramePointer(true);
3550 
3551   MachineFrameInfo &MFI = MF.getFrameInfo();
3552   bool Is64Bit = Subtarget.is64Bit();
3553   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3554 
3555   assert(
3556       !(IsVarArg && canGuaranteeTCO(CallConv)) &&
3557       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3558 
3559   // Assign locations to all of the incoming arguments.
3560   SmallVector<CCValAssign, 16> ArgLocs;
3561   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3562 
3563   // Allocate shadow area for Win64.
3564   if (IsWin64)
3565     CCInfo.AllocateStack(32, Align(8));
3566 
3567   CCInfo.AnalyzeArguments(Ins, CC_X86);
3568 
3569   // In vectorcall calling convention a second pass is required for the HVA
3570   // types.
3571   if (CallingConv::X86_VectorCall == CallConv) {
3572     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3573   }
3574 
3575   // The next loop assumes that the locations are in the same order of the
3576   // input arguments.
3577   assert(isSortedByValueNo(ArgLocs) &&
3578          "Argument Location list must be sorted before lowering");
3579 
3580   SDValue ArgValue;
3581   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3582        ++I, ++InsIndex) {
3583     assert(InsIndex < Ins.size() && "Invalid Ins index");
3584     CCValAssign &VA = ArgLocs[I];
3585 
3586     if (VA.isRegLoc()) {
3587       EVT RegVT = VA.getLocVT();
3588       if (VA.needsCustom()) {
3589         assert(
3590             VA.getValVT() == MVT::v64i1 &&
3591             "Currently the only custom case is when we split v64i1 to 2 regs");
3592 
3593         // v64i1 values, in regcall calling convention, that are
3594         // compiled to 32 bit arch, are split up into two registers.
3595         ArgValue =
3596             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3597       } else {
3598         const TargetRegisterClass *RC;
3599         if (RegVT == MVT::i8)
3600           RC = &X86::GR8RegClass;
3601         else if (RegVT == MVT::i16)
3602           RC = &X86::GR16RegClass;
3603         else if (RegVT == MVT::i32)
3604           RC = &X86::GR32RegClass;
3605         else if (Is64Bit && RegVT == MVT::i64)
3606           RC = &X86::GR64RegClass;
3607         else if (RegVT == MVT::f32)
3608           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3609         else if (RegVT == MVT::f64)
3610           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3611         else if (RegVT == MVT::f80)
3612           RC = &X86::RFP80RegClass;
3613         else if (RegVT == MVT::f128)
3614           RC = &X86::VR128RegClass;
3615         else if (RegVT.is512BitVector())
3616           RC = &X86::VR512RegClass;
3617         else if (RegVT.is256BitVector())
3618           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3619         else if (RegVT.is128BitVector())
3620           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3621         else if (RegVT == MVT::x86mmx)
3622           RC = &X86::VR64RegClass;
3623         else if (RegVT == MVT::v1i1)
3624           RC = &X86::VK1RegClass;
3625         else if (RegVT == MVT::v8i1)
3626           RC = &X86::VK8RegClass;
3627         else if (RegVT == MVT::v16i1)
3628           RC = &X86::VK16RegClass;
3629         else if (RegVT == MVT::v32i1)
3630           RC = &X86::VK32RegClass;
3631         else if (RegVT == MVT::v64i1)
3632           RC = &X86::VK64RegClass;
3633         else
3634           llvm_unreachable("Unknown argument type!");
3635 
3636         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3637         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3638       }
3639 
3640       // If this is an 8 or 16-bit value, it is really passed promoted to 32
3641       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
3642       // right size.
3643       if (VA.getLocInfo() == CCValAssign::SExt)
3644         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3645                                DAG.getValueType(VA.getValVT()));
3646       else if (VA.getLocInfo() == CCValAssign::ZExt)
3647         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3648                                DAG.getValueType(VA.getValVT()));
3649       else if (VA.getLocInfo() == CCValAssign::BCvt)
3650         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3651 
3652       if (VA.isExtInLoc()) {
3653         // Handle MMX values passed in XMM regs.
3654         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3655           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3656         else if (VA.getValVT().isVector() &&
3657                  VA.getValVT().getScalarType() == MVT::i1 &&
3658                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3659                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3660           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3661           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3662         } else
3663           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3664       }
3665     } else {
3666       assert(VA.isMemLoc());
3667       ArgValue =
3668           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3669     }
3670 
3671     // If value is passed via pointer - do a load.
3672     if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3673       ArgValue =
3674           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3675 
3676     InVals.push_back(ArgValue);
3677   }
3678 
3679   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3680     // Swift calling convention does not require we copy the sret argument
3681     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3682     if (CallConv == CallingConv::Swift)
3683       continue;
3684 
3685     // All x86 ABIs require that for returning structs by value we copy the
3686     // sret argument into %rax/%eax (depending on ABI) for the return. Save
3687     // the argument into a virtual register so that we can access it from the
3688     // return points.
3689     if (Ins[I].Flags.isSRet()) {
3690       Register Reg = FuncInfo->getSRetReturnReg();
3691       if (!Reg) {
3692         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3693         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3694         FuncInfo->setSRetReturnReg(Reg);
3695       }
3696       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3697       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3698       break;
3699     }
3700   }
3701 
3702   unsigned StackSize = CCInfo.getNextStackOffset();
3703   // Align stack specially for tail calls.
3704   if (shouldGuaranteeTCO(CallConv,
3705                          MF.getTarget().Options.GuaranteedTailCallOpt))
3706     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3707 
3708   if (IsVarArg)
3709     VarArgsLoweringHelper(FuncInfo, dl, DAG, Subtarget, CallConv, CCInfo)
3710         .lowerVarArgsParameters(Chain, StackSize);
3711 
3712   // Some CCs need callee pop.
3713   if (X86::isCalleePop(CallConv, Is64Bit, IsVarArg,
3714                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
3715     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3716   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3717     // X86 interrupts must pop the error code (and the alignment padding) if
3718     // present.
3719     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3720   } else {
3721     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3722     // If this is an sret function, the return should pop the hidden pointer.
3723     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3724         !Subtarget.getTargetTriple().isOSMSVCRT() &&
3725         argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3726       FuncInfo->setBytesToPopOnReturn(4);
3727   }
3728 
3729   if (!Is64Bit) {
3730     // RegSaveFrameIndex is X86-64 only.
3731     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3732   }
3733 
3734   FuncInfo->setArgumentStackSize(StackSize);
3735 
3736   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3737     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3738     if (Personality == EHPersonality::CoreCLR) {
3739       assert(Is64Bit);
3740       // TODO: Add a mechanism to frame lowering that will allow us to indicate
3741       // that we'd prefer this slot be allocated towards the bottom of the frame
3742       // (i.e. near the stack pointer after allocating the frame).  Every
3743       // funclet needs a copy of this slot in its (mostly empty) frame, and the
3744       // offset from the bottom of this and each funclet's frame must be the
3745       // same, so the size of funclets' (mostly empty) frames is dictated by
3746       // how far this slot is from the bottom (since they allocate just enough
3747       // space to accommodate holding this slot at the correct offset).
3748       int PSPSymFI = MFI.CreateStackObject(8, Align(8), /*isSS=*/false);
3749       EHInfo->PSPSymFrameIdx = PSPSymFI;
3750     }
3751   }
3752 
3753   if (CallConv == CallingConv::X86_RegCall ||
3754       F.hasFnAttribute("no_caller_saved_registers")) {
3755     MachineRegisterInfo &MRI = MF.getRegInfo();
3756     for (std::pair<Register, Register> Pair : MRI.liveins())
3757       MRI.disableCalleeSavedRegister(Pair.first);
3758   }
3759 
3760   return Chain;
3761 }
3762 
LowerMemOpCallTo(SDValue Chain,SDValue StackPtr,SDValue Arg,const SDLoc & dl,SelectionDAG & DAG,const CCValAssign & VA,ISD::ArgFlagsTy Flags,bool isByVal) const3763 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3764                                             SDValue Arg, const SDLoc &dl,
3765                                             SelectionDAG &DAG,
3766                                             const CCValAssign &VA,
3767                                             ISD::ArgFlagsTy Flags,
3768                                             bool isByVal) const {
3769   unsigned LocMemOffset = VA.getLocMemOffset();
3770   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3771   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3772                        StackPtr, PtrOff);
3773   if (isByVal)
3774     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3775 
3776   return DAG.getStore(
3777       Chain, dl, Arg, PtrOff,
3778       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3779 }
3780 
3781 /// Emit a load of return address if tail call
3782 /// optimization is performed and it is required.
EmitTailCallLoadRetAddr(SelectionDAG & DAG,SDValue & OutRetAddr,SDValue Chain,bool IsTailCall,bool Is64Bit,int FPDiff,const SDLoc & dl) const3783 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3784     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3785     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3786   // Adjust the Return address stack slot.
3787   EVT VT = getPointerTy(DAG.getDataLayout());
3788   OutRetAddr = getReturnAddressFrameIndex(DAG);
3789 
3790   // Load the "old" Return address.
3791   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3792   return SDValue(OutRetAddr.getNode(), 1);
3793 }
3794 
3795 /// Emit a store of the return address if tail call
3796 /// optimization is performed and it is required (FPDiff!=0).
EmitTailCallStoreRetAddr(SelectionDAG & DAG,MachineFunction & MF,SDValue Chain,SDValue RetAddrFrIdx,EVT PtrVT,unsigned SlotSize,int FPDiff,const SDLoc & dl)3797 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3798                                         SDValue Chain, SDValue RetAddrFrIdx,
3799                                         EVT PtrVT, unsigned SlotSize,
3800                                         int FPDiff, const SDLoc &dl) {
3801   // Store the return address to the appropriate stack slot.
3802   if (!FPDiff) return Chain;
3803   // Calculate the new stack slot for the return address.
3804   int NewReturnAddrFI =
3805     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3806                                          false);
3807   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3808   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3809                        MachinePointerInfo::getFixedStack(
3810                            DAG.getMachineFunction(), NewReturnAddrFI));
3811   return Chain;
3812 }
3813 
3814 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3815 /// operation of specified width.
getMOVL(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)3816 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3817                        SDValue V2) {
3818   unsigned NumElems = VT.getVectorNumElements();
3819   SmallVector<int, 8> Mask;
3820   Mask.push_back(NumElems);
3821   for (unsigned i = 1; i != NumElems; ++i)
3822     Mask.push_back(i);
3823   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3824 }
3825 
3826 SDValue
LowerCall(TargetLowering::CallLoweringInfo & CLI,SmallVectorImpl<SDValue> & InVals) const3827 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3828                              SmallVectorImpl<SDValue> &InVals) const {
3829   SelectionDAG &DAG                     = CLI.DAG;
3830   SDLoc &dl                             = CLI.DL;
3831   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3832   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3833   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3834   SDValue Chain                         = CLI.Chain;
3835   SDValue Callee                        = CLI.Callee;
3836   CallingConv::ID CallConv              = CLI.CallConv;
3837   bool &isTailCall                      = CLI.IsTailCall;
3838   bool isVarArg                         = CLI.IsVarArg;
3839 
3840   MachineFunction &MF = DAG.getMachineFunction();
3841   bool Is64Bit        = Subtarget.is64Bit();
3842   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
3843   StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3844   bool IsSibcall      = false;
3845   bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
3846       CallConv == CallingConv::Tail;
3847   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3848   const auto *CI = dyn_cast_or_null<CallInst>(CLI.CB);
3849   const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3850   bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3851                  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3852   const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CB);
3853   bool HasNoCfCheck =
3854       (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3855   const Module *M = MF.getMMI().getModule();
3856   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3857 
3858   MachineFunction::CallSiteInfo CSInfo;
3859   if (CallConv == CallingConv::X86_INTR)
3860     report_fatal_error("X86 interrupts may not be called directly");
3861 
3862   if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO) {
3863     // If we are using a GOT, disable tail calls to external symbols with
3864     // default visibility. Tail calling such a symbol requires using a GOT
3865     // relocation, which forces early binding of the symbol. This breaks code
3866     // that require lazy function symbol resolution. Using musttail or
3867     // GuaranteedTailCallOpt will override this.
3868     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3869     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3870                G->getGlobal()->hasDefaultVisibility()))
3871       isTailCall = false;
3872   }
3873 
3874   bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
3875   if (IsMustTail) {
3876     // Force this to be a tail call.  The verifier rules are enough to ensure
3877     // that we can lower this successfully without moving the return address
3878     // around.
3879     isTailCall = true;
3880   } else if (isTailCall) {
3881     // Check if it's really possible to do a tail call.
3882     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3883                     isVarArg, SR != NotStructReturn,
3884                     MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3885                     Outs, OutVals, Ins, DAG);
3886 
3887     // Sibcalls are automatically detected tailcalls which do not require
3888     // ABI changes.
3889     if (!IsGuaranteeTCO && isTailCall)
3890       IsSibcall = true;
3891 
3892     if (isTailCall)
3893       ++NumTailCalls;
3894   }
3895 
3896   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3897          "Var args not supported with calling convention fastcc, ghc or hipe");
3898 
3899   // Analyze operands of the call, assigning locations to each operand.
3900   SmallVector<CCValAssign, 16> ArgLocs;
3901   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3902 
3903   // Allocate shadow area for Win64.
3904   if (IsWin64)
3905     CCInfo.AllocateStack(32, Align(8));
3906 
3907   CCInfo.AnalyzeArguments(Outs, CC_X86);
3908 
3909   // In vectorcall calling convention a second pass is required for the HVA
3910   // types.
3911   if (CallingConv::X86_VectorCall == CallConv) {
3912     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3913   }
3914 
3915   // Get a count of how many bytes are to be pushed on the stack.
3916   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3917   if (IsSibcall)
3918     // This is a sibcall. The memory operands are available in caller's
3919     // own caller's stack.
3920     NumBytes = 0;
3921   else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
3922     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3923 
3924   int FPDiff = 0;
3925   if (isTailCall && !IsSibcall && !IsMustTail) {
3926     // Lower arguments at fp - stackoffset + fpdiff.
3927     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3928 
3929     FPDiff = NumBytesCallerPushed - NumBytes;
3930 
3931     // Set the delta of movement of the returnaddr stackslot.
3932     // But only set if delta is greater than previous delta.
3933     if (FPDiff < X86Info->getTCReturnAddrDelta())
3934       X86Info->setTCReturnAddrDelta(FPDiff);
3935   }
3936 
3937   unsigned NumBytesToPush = NumBytes;
3938   unsigned NumBytesToPop = NumBytes;
3939 
3940   // If we have an inalloca argument, all stack space has already been allocated
3941   // for us and be right at the top of the stack.  We don't support multiple
3942   // arguments passed in memory when using inalloca.
3943   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3944     NumBytesToPush = 0;
3945     if (!ArgLocs.back().isMemLoc())
3946       report_fatal_error("cannot use inalloca attribute on a register "
3947                          "parameter");
3948     if (ArgLocs.back().getLocMemOffset() != 0)
3949       report_fatal_error("any parameter with the inalloca attribute must be "
3950                          "the only memory argument");
3951   } else if (CLI.IsPreallocated) {
3952     assert(ArgLocs.back().isMemLoc() &&
3953            "cannot use preallocated attribute on a register "
3954            "parameter");
3955     SmallVector<size_t, 4> PreallocatedOffsets;
3956     for (size_t i = 0; i < CLI.OutVals.size(); ++i) {
3957       if (CLI.CB->paramHasAttr(i, Attribute::Preallocated)) {
3958         PreallocatedOffsets.push_back(ArgLocs[i].getLocMemOffset());
3959       }
3960     }
3961     auto *MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
3962     size_t PreallocatedId = MFI->getPreallocatedIdForCallSite(CLI.CB);
3963     MFI->setPreallocatedStackSize(PreallocatedId, NumBytes);
3964     MFI->setPreallocatedArgOffsets(PreallocatedId, PreallocatedOffsets);
3965     NumBytesToPush = 0;
3966   }
3967 
3968   if (!IsSibcall && !IsMustTail)
3969     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3970                                  NumBytes - NumBytesToPush, dl);
3971 
3972   SDValue RetAddrFrIdx;
3973   // Load return address for tail calls.
3974   if (isTailCall && FPDiff)
3975     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3976                                     Is64Bit, FPDiff, dl);
3977 
3978   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
3979   SmallVector<SDValue, 8> MemOpChains;
3980   SDValue StackPtr;
3981 
3982   // The next loop assumes that the locations are in the same order of the
3983   // input arguments.
3984   assert(isSortedByValueNo(ArgLocs) &&
3985          "Argument Location list must be sorted before lowering");
3986 
3987   // Walk the register/memloc assignments, inserting copies/loads.  In the case
3988   // of tail call optimization arguments are handle later.
3989   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3990   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3991        ++I, ++OutIndex) {
3992     assert(OutIndex < Outs.size() && "Invalid Out index");
3993     // Skip inalloca/preallocated arguments, they have already been written.
3994     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3995     if (Flags.isInAlloca() || Flags.isPreallocated())
3996       continue;
3997 
3998     CCValAssign &VA = ArgLocs[I];
3999     EVT RegVT = VA.getLocVT();
4000     SDValue Arg = OutVals[OutIndex];
4001     bool isByVal = Flags.isByVal();
4002 
4003     // Promote the value if needed.
4004     switch (VA.getLocInfo()) {
4005     default: llvm_unreachable("Unknown loc info!");
4006     case CCValAssign::Full: break;
4007     case CCValAssign::SExt:
4008       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
4009       break;
4010     case CCValAssign::ZExt:
4011       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
4012       break;
4013     case CCValAssign::AExt:
4014       if (Arg.getValueType().isVector() &&
4015           Arg.getValueType().getVectorElementType() == MVT::i1)
4016         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
4017       else if (RegVT.is128BitVector()) {
4018         // Special case: passing MMX values in XMM registers.
4019         Arg = DAG.getBitcast(MVT::i64, Arg);
4020         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
4021         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
4022       } else
4023         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
4024       break;
4025     case CCValAssign::BCvt:
4026       Arg = DAG.getBitcast(RegVT, Arg);
4027       break;
4028     case CCValAssign::Indirect: {
4029       if (isByVal) {
4030         // Memcpy the argument to a temporary stack slot to prevent
4031         // the caller from seeing any modifications the callee may make
4032         // as guaranteed by the `byval` attribute.
4033         int FrameIdx = MF.getFrameInfo().CreateStackObject(
4034             Flags.getByValSize(),
4035             std::max(Align(16), Flags.getNonZeroByValAlign()), false);
4036         SDValue StackSlot =
4037             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
4038         Chain =
4039             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
4040         // From now on treat this as a regular pointer
4041         Arg = StackSlot;
4042         isByVal = false;
4043       } else {
4044         // Store the argument.
4045         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
4046         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
4047         Chain = DAG.getStore(
4048             Chain, dl, Arg, SpillSlot,
4049             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4050         Arg = SpillSlot;
4051       }
4052       break;
4053     }
4054     }
4055 
4056     if (VA.needsCustom()) {
4057       assert(VA.getValVT() == MVT::v64i1 &&
4058              "Currently the only custom case is when we split v64i1 to 2 regs");
4059       // Split v64i1 value into two registers
4060       Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
4061     } else if (VA.isRegLoc()) {
4062       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4063       const TargetOptions &Options = DAG.getTarget().Options;
4064       if (Options.EmitCallSiteInfo)
4065         CSInfo.emplace_back(VA.getLocReg(), I);
4066       if (isVarArg && IsWin64) {
4067         // Win64 ABI requires argument XMM reg to be copied to the corresponding
4068         // shadow reg if callee is a varargs function.
4069         Register ShadowReg;
4070         switch (VA.getLocReg()) {
4071         case X86::XMM0: ShadowReg = X86::RCX; break;
4072         case X86::XMM1: ShadowReg = X86::RDX; break;
4073         case X86::XMM2: ShadowReg = X86::R8; break;
4074         case X86::XMM3: ShadowReg = X86::R9; break;
4075         }
4076         if (ShadowReg)
4077           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4078       }
4079     } else if (!IsSibcall && (!isTailCall || isByVal)) {
4080       assert(VA.isMemLoc());
4081       if (!StackPtr.getNode())
4082         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4083                                       getPointerTy(DAG.getDataLayout()));
4084       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4085                                              dl, DAG, VA, Flags, isByVal));
4086     }
4087   }
4088 
4089   if (!MemOpChains.empty())
4090     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4091 
4092   if (Subtarget.isPICStyleGOT()) {
4093     // ELF / PIC requires GOT in the EBX register before function calls via PLT
4094     // GOT pointer.
4095     if (!isTailCall) {
4096       RegsToPass.push_back(std::make_pair(
4097           Register(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4098                                           getPointerTy(DAG.getDataLayout()))));
4099     } else {
4100       // If we are tail calling and generating PIC/GOT style code load the
4101       // address of the callee into ECX. The value in ecx is used as target of
4102       // the tail jump. This is done to circumvent the ebx/callee-saved problem
4103       // for tail calls on PIC/GOT architectures. Normally we would just put the
4104       // address of GOT into ebx and then call target@PLT. But for tail calls
4105       // ebx would be restored (since ebx is callee saved) before jumping to the
4106       // target@PLT.
4107 
4108       // Note: The actual moving to ECX is done further down.
4109       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4110       if (G && !G->getGlobal()->hasLocalLinkage() &&
4111           G->getGlobal()->hasDefaultVisibility())
4112         Callee = LowerGlobalAddress(Callee, DAG);
4113       else if (isa<ExternalSymbolSDNode>(Callee))
4114         Callee = LowerExternalSymbol(Callee, DAG);
4115     }
4116   }
4117 
4118   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
4119     // From AMD64 ABI document:
4120     // For calls that may call functions that use varargs or stdargs
4121     // (prototype-less calls or calls to functions containing ellipsis (...) in
4122     // the declaration) %al is used as hidden argument to specify the number
4123     // of SSE registers used. The contents of %al do not need to match exactly
4124     // the number of registers, but must be an ubound on the number of SSE
4125     // registers used and is in the range 0 - 8 inclusive.
4126 
4127     // Count the number of XMM registers allocated.
4128     static const MCPhysReg XMMArgRegs[] = {
4129       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4130       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4131     };
4132     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4133     assert((Subtarget.hasSSE1() || !NumXMMRegs)
4134            && "SSE registers cannot be used when SSE is disabled");
4135     RegsToPass.push_back(std::make_pair(Register(X86::AL),
4136                                         DAG.getConstant(NumXMMRegs, dl,
4137                                                         MVT::i8)));
4138   }
4139 
4140   if (isVarArg && IsMustTail) {
4141     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4142     for (const auto &F : Forwards) {
4143       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4144       RegsToPass.push_back(std::make_pair(F.PReg, Val));
4145     }
4146   }
4147 
4148   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
4149   // don't need this because the eligibility check rejects calls that require
4150   // shuffling arguments passed in memory.
4151   if (!IsSibcall && isTailCall) {
4152     // Force all the incoming stack arguments to be loaded from the stack
4153     // before any new outgoing arguments are stored to the stack, because the
4154     // outgoing stack slots may alias the incoming argument stack slots, and
4155     // the alias isn't otherwise explicit. This is slightly more conservative
4156     // than necessary, because it means that each store effectively depends
4157     // on every argument instead of just those arguments it would clobber.
4158     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4159 
4160     SmallVector<SDValue, 8> MemOpChains2;
4161     SDValue FIN;
4162     int FI = 0;
4163     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4164          ++I, ++OutsIndex) {
4165       CCValAssign &VA = ArgLocs[I];
4166 
4167       if (VA.isRegLoc()) {
4168         if (VA.needsCustom()) {
4169           assert((CallConv == CallingConv::X86_RegCall) &&
4170                  "Expecting custom case only in regcall calling convention");
4171           // This means that we are in special case where one argument was
4172           // passed through two register locations - Skip the next location
4173           ++I;
4174         }
4175 
4176         continue;
4177       }
4178 
4179       assert(VA.isMemLoc());
4180       SDValue Arg = OutVals[OutsIndex];
4181       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4182       // Skip inalloca/preallocated arguments.  They don't require any work.
4183       if (Flags.isInAlloca() || Flags.isPreallocated())
4184         continue;
4185       // Create frame index.
4186       int32_t Offset = VA.getLocMemOffset()+FPDiff;
4187       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4188       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4189       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4190 
4191       if (Flags.isByVal()) {
4192         // Copy relative to framepointer.
4193         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4194         if (!StackPtr.getNode())
4195           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4196                                         getPointerTy(DAG.getDataLayout()));
4197         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4198                              StackPtr, Source);
4199 
4200         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4201                                                          ArgChain,
4202                                                          Flags, DAG, dl));
4203       } else {
4204         // Store relative to framepointer.
4205         MemOpChains2.push_back(DAG.getStore(
4206             ArgChain, dl, Arg, FIN,
4207             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4208       }
4209     }
4210 
4211     if (!MemOpChains2.empty())
4212       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4213 
4214     // Store the return address to the appropriate stack slot.
4215     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4216                                      getPointerTy(DAG.getDataLayout()),
4217                                      RegInfo->getSlotSize(), FPDiff, dl);
4218   }
4219 
4220   // Build a sequence of copy-to-reg nodes chained together with token chain
4221   // and flag operands which copy the outgoing args into registers.
4222   SDValue InFlag;
4223   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4224     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4225                              RegsToPass[i].second, InFlag);
4226     InFlag = Chain.getValue(1);
4227   }
4228 
4229   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4230     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
4231     // In the 64-bit large code model, we have to make all calls
4232     // through a register, since the call instruction's 32-bit
4233     // pc-relative offset may not be large enough to hold the whole
4234     // address.
4235   } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4236              Callee->getOpcode() == ISD::ExternalSymbol) {
4237     // Lower direct calls to global addresses and external symbols. Setting
4238     // ForCall to true here has the effect of removing WrapperRIP when possible
4239     // to allow direct calls to be selected without first materializing the
4240     // address into a register.
4241     Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4242   } else if (Subtarget.isTarget64BitILP32() &&
4243              Callee->getValueType(0) == MVT::i32) {
4244     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4245     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4246   }
4247 
4248   // Returns a chain & a flag for retval copy to use.
4249   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4250   SmallVector<SDValue, 8> Ops;
4251 
4252   if (!IsSibcall && isTailCall && !IsMustTail) {
4253     Chain = DAG.getCALLSEQ_END(Chain,
4254                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4255                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4256     InFlag = Chain.getValue(1);
4257   }
4258 
4259   Ops.push_back(Chain);
4260   Ops.push_back(Callee);
4261 
4262   if (isTailCall)
4263     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
4264 
4265   // Add argument registers to the end of the list so that they are known live
4266   // into the call.
4267   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4268     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4269                                   RegsToPass[i].second.getValueType()));
4270 
4271   // Add a register mask operand representing the call-preserved registers.
4272   // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
4273   // set X86_INTR calling convention because it has the same CSR mask
4274   // (same preserved registers).
4275   const uint32_t *Mask = RegInfo->getCallPreservedMask(
4276       MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
4277   assert(Mask && "Missing call preserved mask for calling convention");
4278 
4279   // If this is an invoke in a 32-bit function using a funclet-based
4280   // personality, assume the function clobbers all registers. If an exception
4281   // is thrown, the runtime will not restore CSRs.
4282   // FIXME: Model this more precisely so that we can register allocate across
4283   // the normal edge and spill and fill across the exceptional edge.
4284   if (!Is64Bit && CLI.CB && isa<InvokeInst>(CLI.CB)) {
4285     const Function &CallerFn = MF.getFunction();
4286     EHPersonality Pers =
4287         CallerFn.hasPersonalityFn()
4288             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4289             : EHPersonality::Unknown;
4290     if (isFuncletEHPersonality(Pers))
4291       Mask = RegInfo->getNoPreservedMask();
4292   }
4293 
4294   // Define a new register mask from the existing mask.
4295   uint32_t *RegMask = nullptr;
4296 
4297   // In some calling conventions we need to remove the used physical registers
4298   // from the reg mask.
4299   if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4300     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4301 
4302     // Allocate a new Reg Mask and copy Mask.
4303     RegMask = MF.allocateRegMask();
4304     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4305     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4306 
4307     // Make sure all sub registers of the argument registers are reset
4308     // in the RegMask.
4309     for (auto const &RegPair : RegsToPass)
4310       for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4311            SubRegs.isValid(); ++SubRegs)
4312         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4313 
4314     // Create the RegMask Operand according to our updated mask.
4315     Ops.push_back(DAG.getRegisterMask(RegMask));
4316   } else {
4317     // Create the RegMask Operand according to the static mask.
4318     Ops.push_back(DAG.getRegisterMask(Mask));
4319   }
4320 
4321   if (InFlag.getNode())
4322     Ops.push_back(InFlag);
4323 
4324   if (isTailCall) {
4325     // We used to do:
4326     //// If this is the first return lowered for this function, add the regs
4327     //// to the liveout set for the function.
4328     // This isn't right, although it's probably harmless on x86; liveouts
4329     // should be computed from returns not tail calls.  Consider a void
4330     // function making a tail call to a function returning int.
4331     MF.getFrameInfo().setHasTailCall();
4332     SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4333     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4334     return Ret;
4335   }
4336 
4337   if (HasNoCfCheck && IsCFProtectionSupported) {
4338     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4339   } else {
4340     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4341   }
4342   InFlag = Chain.getValue(1);
4343   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4344   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4345 
4346   // Save heapallocsite metadata.
4347   if (CLI.CB)
4348     if (MDNode *HeapAlloc = CLI.CB->getMetadata("heapallocsite"))
4349       DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4350 
4351   // Create the CALLSEQ_END node.
4352   unsigned NumBytesForCalleeToPop;
4353   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4354                        DAG.getTarget().Options.GuaranteedTailCallOpt))
4355     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
4356   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4357            !Subtarget.getTargetTriple().isOSMSVCRT() &&
4358            SR == StackStructReturn)
4359     // If this is a call to a struct-return function, the callee
4360     // pops the hidden struct pointer, so we have to push it back.
4361     // This is common for Darwin/X86, Linux & Mingw32 targets.
4362     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4363     NumBytesForCalleeToPop = 4;
4364   else
4365     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
4366 
4367   // Returns a flag for retval copy to use.
4368   if (!IsSibcall) {
4369     Chain = DAG.getCALLSEQ_END(Chain,
4370                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4371                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4372                                                      true),
4373                                InFlag, dl);
4374     InFlag = Chain.getValue(1);
4375   }
4376 
4377   // Handle result values, copying them out of physregs into vregs that we
4378   // return.
4379   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4380                          InVals, RegMask);
4381 }
4382 
4383 //===----------------------------------------------------------------------===//
4384 //                Fast Calling Convention (tail call) implementation
4385 //===----------------------------------------------------------------------===//
4386 
4387 //  Like std call, callee cleans arguments, convention except that ECX is
4388 //  reserved for storing the tail called function address. Only 2 registers are
4389 //  free for argument passing (inreg). Tail call optimization is performed
4390 //  provided:
4391 //                * tailcallopt is enabled
4392 //                * caller/callee are fastcc
4393 //  On X86_64 architecture with GOT-style position independent code only local
4394 //  (within module) calls are supported at the moment.
4395 //  To keep the stack aligned according to platform abi the function
4396 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
4397 //  of stack alignment. (Dynamic linkers need this - Darwin's dyld for example)
4398 //  If a tail called function callee has more arguments than the caller the
4399 //  caller needs to make sure that there is room to move the RETADDR to. This is
4400 //  achieved by reserving an area the size of the argument delta right after the
4401 //  original RETADDR, but before the saved framepointer or the spilled registers
4402 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4403 //  stack layout:
4404 //    arg1
4405 //    arg2
4406 //    RETADDR
4407 //    [ new RETADDR
4408 //      move area ]
4409 //    (possible EBP)
4410 //    ESI
4411 //    EDI
4412 //    local1 ..
4413 
4414 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4415 /// requirement.
4416 unsigned
GetAlignedArgumentStackSize(const unsigned StackSize,SelectionDAG & DAG) const4417 X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
4418                                                SelectionDAG &DAG) const {
4419   const Align StackAlignment = Subtarget.getFrameLowering()->getStackAlign();
4420   const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
4421   assert(StackSize % SlotSize == 0 &&
4422          "StackSize must be a multiple of SlotSize");
4423   return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
4424 }
4425 
4426 /// Return true if the given stack call argument is already available in the
4427 /// same position (relatively) of the caller's incoming argument stack.
4428 static
MatchingStackOffset(SDValue Arg,unsigned Offset,ISD::ArgFlagsTy Flags,MachineFrameInfo & MFI,const MachineRegisterInfo * MRI,const X86InstrInfo * TII,const CCValAssign & VA)4429 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4430                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4431                          const X86InstrInfo *TII, const CCValAssign &VA) {
4432   unsigned Bytes = Arg.getValueSizeInBits() / 8;
4433 
4434   for (;;) {
4435     // Look through nodes that don't alter the bits of the incoming value.
4436     unsigned Op = Arg.getOpcode();
4437     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4438       Arg = Arg.getOperand(0);
4439       continue;
4440     }
4441     if (Op == ISD::TRUNCATE) {
4442       const SDValue &TruncInput = Arg.getOperand(0);
4443       if (TruncInput.getOpcode() == ISD::AssertZext &&
4444           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4445               Arg.getValueType()) {
4446         Arg = TruncInput.getOperand(0);
4447         continue;
4448       }
4449     }
4450     break;
4451   }
4452 
4453   int FI = INT_MAX;
4454   if (Arg.getOpcode() == ISD::CopyFromReg) {
4455     Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4456     if (!Register::isVirtualRegister(VR))
4457       return false;
4458     MachineInstr *Def = MRI->getVRegDef(VR);
4459     if (!Def)
4460       return false;
4461     if (!Flags.isByVal()) {
4462       if (!TII->isLoadFromStackSlot(*Def, FI))
4463         return false;
4464     } else {
4465       unsigned Opcode = Def->getOpcode();
4466       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4467            Opcode == X86::LEA64_32r) &&
4468           Def->getOperand(1).isFI()) {
4469         FI = Def->getOperand(1).getIndex();
4470         Bytes = Flags.getByValSize();
4471       } else
4472         return false;
4473     }
4474   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4475     if (Flags.isByVal())
4476       // ByVal argument is passed in as a pointer but it's now being
4477       // dereferenced. e.g.
4478       // define @foo(%struct.X* %A) {
4479       //   tail call @bar(%struct.X* byval %A)
4480       // }
4481       return false;
4482     SDValue Ptr = Ld->getBasePtr();
4483     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4484     if (!FINode)
4485       return false;
4486     FI = FINode->getIndex();
4487   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4488     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4489     FI = FINode->getIndex();
4490     Bytes = Flags.getByValSize();
4491   } else
4492     return false;
4493 
4494   assert(FI != INT_MAX);
4495   if (!MFI.isFixedObjectIndex(FI))
4496     return false;
4497 
4498   if (Offset != MFI.getObjectOffset(FI))
4499     return false;
4500 
4501   // If this is not byval, check that the argument stack object is immutable.
4502   // inalloca and argument copy elision can create mutable argument stack
4503   // objects. Byval objects can be mutated, but a byval call intends to pass the
4504   // mutated memory.
4505   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4506     return false;
4507 
4508   if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4509     // If the argument location is wider than the argument type, check that any
4510     // extension flags match.
4511     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4512         Flags.isSExt() != MFI.isObjectSExt(FI)) {
4513       return false;
4514     }
4515   }
4516 
4517   return Bytes == MFI.getObjectSize(FI);
4518 }
4519 
4520 /// Check whether the call is eligible for tail call optimization. Targets
4521 /// that want to do tail call optimization should implement this function.
IsEligibleForTailCallOptimization(SDValue Callee,CallingConv::ID CalleeCC,bool isVarArg,bool isCalleeStructRet,bool isCallerStructRet,Type * RetTy,const SmallVectorImpl<ISD::OutputArg> & Outs,const SmallVectorImpl<SDValue> & OutVals,const SmallVectorImpl<ISD::InputArg> & Ins,SelectionDAG & DAG) const4522 bool X86TargetLowering::IsEligibleForTailCallOptimization(
4523     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4524     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4525     const SmallVectorImpl<ISD::OutputArg> &Outs,
4526     const SmallVectorImpl<SDValue> &OutVals,
4527     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4528   if (!mayTailCallThisCC(CalleeCC))
4529     return false;
4530 
4531   // If -tailcallopt is specified, make fastcc functions tail-callable.
4532   MachineFunction &MF = DAG.getMachineFunction();
4533   const Function &CallerF = MF.getFunction();
4534 
4535   // If the function return type is x86_fp80 and the callee return type is not,
4536   // then the FP_EXTEND of the call result is not a nop. It's not safe to
4537   // perform a tailcall optimization here.
4538   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4539     return false;
4540 
4541   CallingConv::ID CallerCC = CallerF.getCallingConv();
4542   bool CCMatch = CallerCC == CalleeCC;
4543   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4544   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4545   bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
4546       CalleeCC == CallingConv::Tail;
4547 
4548   // Win64 functions have extra shadow space for argument homing. Don't do the
4549   // sibcall if the caller and callee have mismatched expectations for this
4550   // space.
4551   if (IsCalleeWin64 != IsCallerWin64)
4552     return false;
4553 
4554   if (IsGuaranteeTCO) {
4555     if (canGuaranteeTCO(CalleeCC) && CCMatch)
4556       return true;
4557     return false;
4558   }
4559 
4560   // Look for obvious safe cases to perform tail call optimization that do not
4561   // require ABI changes. This is what gcc calls sibcall.
4562 
4563   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4564   // emit a special epilogue.
4565   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4566   if (RegInfo->needsStackRealignment(MF))
4567     return false;
4568 
4569   // Also avoid sibcall optimization if either caller or callee uses struct
4570   // return semantics.
4571   if (isCalleeStructRet || isCallerStructRet)
4572     return false;
4573 
4574   // Do not sibcall optimize vararg calls unless all arguments are passed via
4575   // registers.
4576   LLVMContext &C = *DAG.getContext();
4577   if (isVarArg && !Outs.empty()) {
4578     // Optimizing for varargs on Win64 is unlikely to be safe without
4579     // additional testing.
4580     if (IsCalleeWin64 || IsCallerWin64)
4581       return false;
4582 
4583     SmallVector<CCValAssign, 16> ArgLocs;
4584     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4585 
4586     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4587     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4588       if (!ArgLocs[i].isRegLoc())
4589         return false;
4590   }
4591 
4592   // If the call result is in ST0 / ST1, it needs to be popped off the x87
4593   // stack.  Therefore, if it's not used by the call it is not safe to optimize
4594   // this into a sibcall.
4595   bool Unused = false;
4596   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4597     if (!Ins[i].Used) {
4598       Unused = true;
4599       break;
4600     }
4601   }
4602   if (Unused) {
4603     SmallVector<CCValAssign, 16> RVLocs;
4604     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4605     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4606     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4607       CCValAssign &VA = RVLocs[i];
4608       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4609         return false;
4610     }
4611   }
4612 
4613   // Check that the call results are passed in the same way.
4614   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4615                                   RetCC_X86, RetCC_X86))
4616     return false;
4617   // The callee has to preserve all registers the caller needs to preserve.
4618   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4619   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4620   if (!CCMatch) {
4621     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4622     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4623       return false;
4624   }
4625 
4626   unsigned StackArgsSize = 0;
4627 
4628   // If the callee takes no arguments then go on to check the results of the
4629   // call.
4630   if (!Outs.empty()) {
4631     // Check if stack adjustment is needed. For now, do not do this if any
4632     // argument is passed on the stack.
4633     SmallVector<CCValAssign, 16> ArgLocs;
4634     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4635 
4636     // Allocate shadow area for Win64
4637     if (IsCalleeWin64)
4638       CCInfo.AllocateStack(32, Align(8));
4639 
4640     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4641     StackArgsSize = CCInfo.getNextStackOffset();
4642 
4643     if (CCInfo.getNextStackOffset()) {
4644       // Check if the arguments are already laid out in the right way as
4645       // the caller's fixed stack objects.
4646       MachineFrameInfo &MFI = MF.getFrameInfo();
4647       const MachineRegisterInfo *MRI = &MF.getRegInfo();
4648       const X86InstrInfo *TII = Subtarget.getInstrInfo();
4649       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4650         CCValAssign &VA = ArgLocs[i];
4651         SDValue Arg = OutVals[i];
4652         ISD::ArgFlagsTy Flags = Outs[i].Flags;
4653         if (VA.getLocInfo() == CCValAssign::Indirect)
4654           return false;
4655         if (!VA.isRegLoc()) {
4656           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4657                                    MFI, MRI, TII, VA))
4658             return false;
4659         }
4660       }
4661     }
4662 
4663     bool PositionIndependent = isPositionIndependent();
4664     // If the tailcall address may be in a register, then make sure it's
4665     // possible to register allocate for it. In 32-bit, the call address can
4666     // only target EAX, EDX, or ECX since the tail call must be scheduled after
4667     // callee-saved registers are restored. These happen to be the same
4668     // registers used to pass 'inreg' arguments so watch out for those.
4669     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4670                                   !isa<ExternalSymbolSDNode>(Callee)) ||
4671                                  PositionIndependent)) {
4672       unsigned NumInRegs = 0;
4673       // In PIC we need an extra register to formulate the address computation
4674       // for the callee.
4675       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4676 
4677       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4678         CCValAssign &VA = ArgLocs[i];
4679         if (!VA.isRegLoc())
4680           continue;
4681         Register Reg = VA.getLocReg();
4682         switch (Reg) {
4683         default: break;
4684         case X86::EAX: case X86::EDX: case X86::ECX:
4685           if (++NumInRegs == MaxInRegs)
4686             return false;
4687           break;
4688         }
4689       }
4690     }
4691 
4692     const MachineRegisterInfo &MRI = MF.getRegInfo();
4693     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4694       return false;
4695   }
4696 
4697   bool CalleeWillPop =
4698       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4699                        MF.getTarget().Options.GuaranteedTailCallOpt);
4700 
4701   if (unsigned BytesToPop =
4702           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4703     // If we have bytes to pop, the callee must pop them.
4704     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4705     if (!CalleePopMatches)
4706       return false;
4707   } else if (CalleeWillPop && StackArgsSize > 0) {
4708     // If we don't have bytes to pop, make sure the callee doesn't pop any.
4709     return false;
4710   }
4711 
4712   return true;
4713 }
4714 
4715 FastISel *
createFastISel(FunctionLoweringInfo & funcInfo,const TargetLibraryInfo * libInfo) const4716 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4717                                   const TargetLibraryInfo *libInfo) const {
4718   return X86::createFastISel(funcInfo, libInfo);
4719 }
4720 
4721 //===----------------------------------------------------------------------===//
4722 //                           Other Lowering Hooks
4723 //===----------------------------------------------------------------------===//
4724 
MayFoldLoad(SDValue Op)4725 static bool MayFoldLoad(SDValue Op) {
4726   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4727 }
4728 
MayFoldIntoStore(SDValue Op)4729 static bool MayFoldIntoStore(SDValue Op) {
4730   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4731 }
4732 
MayFoldIntoZeroExtend(SDValue Op)4733 static bool MayFoldIntoZeroExtend(SDValue Op) {
4734   if (Op.hasOneUse()) {
4735     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4736     return (ISD::ZERO_EXTEND == Opcode);
4737   }
4738   return false;
4739 }
4740 
isTargetShuffle(unsigned Opcode)4741 static bool isTargetShuffle(unsigned Opcode) {
4742   switch(Opcode) {
4743   default: return false;
4744   case X86ISD::BLENDI:
4745   case X86ISD::PSHUFB:
4746   case X86ISD::PSHUFD:
4747   case X86ISD::PSHUFHW:
4748   case X86ISD::PSHUFLW:
4749   case X86ISD::SHUFP:
4750   case X86ISD::INSERTPS:
4751   case X86ISD::EXTRQI:
4752   case X86ISD::INSERTQI:
4753   case X86ISD::VALIGN:
4754   case X86ISD::PALIGNR:
4755   case X86ISD::VSHLDQ:
4756   case X86ISD::VSRLDQ:
4757   case X86ISD::MOVLHPS:
4758   case X86ISD::MOVHLPS:
4759   case X86ISD::MOVSHDUP:
4760   case X86ISD::MOVSLDUP:
4761   case X86ISD::MOVDDUP:
4762   case X86ISD::MOVSS:
4763   case X86ISD::MOVSD:
4764   case X86ISD::UNPCKL:
4765   case X86ISD::UNPCKH:
4766   case X86ISD::VBROADCAST:
4767   case X86ISD::VPERMILPI:
4768   case X86ISD::VPERMILPV:
4769   case X86ISD::VPERM2X128:
4770   case X86ISD::SHUF128:
4771   case X86ISD::VPERMIL2:
4772   case X86ISD::VPERMI:
4773   case X86ISD::VPPERM:
4774   case X86ISD::VPERMV:
4775   case X86ISD::VPERMV3:
4776   case X86ISD::VZEXT_MOVL:
4777     return true;
4778   }
4779 }
4780 
isTargetShuffleVariableMask(unsigned Opcode)4781 static bool isTargetShuffleVariableMask(unsigned Opcode) {
4782   switch (Opcode) {
4783   default: return false;
4784   // Target Shuffles.
4785   case X86ISD::PSHUFB:
4786   case X86ISD::VPERMILPV:
4787   case X86ISD::VPERMIL2:
4788   case X86ISD::VPPERM:
4789   case X86ISD::VPERMV:
4790   case X86ISD::VPERMV3:
4791     return true;
4792   // 'Faux' Target Shuffles.
4793   case ISD::OR:
4794   case ISD::AND:
4795   case X86ISD::ANDNP:
4796     return true;
4797   }
4798 }
4799 
isTargetShuffleSplat(SDValue Op)4800 static bool isTargetShuffleSplat(SDValue Op) {
4801   unsigned Opcode = Op.getOpcode();
4802   if (Opcode == ISD::EXTRACT_SUBVECTOR)
4803     return isTargetShuffleSplat(Op.getOperand(0));
4804   return Opcode == X86ISD::VBROADCAST || Opcode == X86ISD::VBROADCAST_LOAD;
4805 }
4806 
getReturnAddressFrameIndex(SelectionDAG & DAG) const4807 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4808   MachineFunction &MF = DAG.getMachineFunction();
4809   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4810   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4811   int ReturnAddrIndex = FuncInfo->getRAIndex();
4812 
4813   if (ReturnAddrIndex == 0) {
4814     // Set up a frame object for the return address.
4815     unsigned SlotSize = RegInfo->getSlotSize();
4816     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4817                                                           -(int64_t)SlotSize,
4818                                                           false);
4819     FuncInfo->setRAIndex(ReturnAddrIndex);
4820   }
4821 
4822   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4823 }
4824 
isOffsetSuitableForCodeModel(int64_t Offset,CodeModel::Model M,bool hasSymbolicDisplacement)4825 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4826                                        bool hasSymbolicDisplacement) {
4827   // Offset should fit into 32 bit immediate field.
4828   if (!isInt<32>(Offset))
4829     return false;
4830 
4831   // If we don't have a symbolic displacement - we don't have any extra
4832   // restrictions.
4833   if (!hasSymbolicDisplacement)
4834     return true;
4835 
4836   // FIXME: Some tweaks might be needed for medium code model.
4837   if (M != CodeModel::Small && M != CodeModel::Kernel)
4838     return false;
4839 
4840   // For small code model we assume that latest object is 16MB before end of 31
4841   // bits boundary. We may also accept pretty large negative constants knowing
4842   // that all objects are in the positive half of address space.
4843   if (M == CodeModel::Small && Offset < 16*1024*1024)
4844     return true;
4845 
4846   // For kernel code model we know that all object resist in the negative half
4847   // of 32bits address space. We may not accept negative offsets, since they may
4848   // be just off and we may accept pretty large positive ones.
4849   if (M == CodeModel::Kernel && Offset >= 0)
4850     return true;
4851 
4852   return false;
4853 }
4854 
4855 /// Determines whether the callee is required to pop its own arguments.
4856 /// Callee pop is necessary to support tail calls.
isCalleePop(CallingConv::ID CallingConv,bool is64Bit,bool IsVarArg,bool GuaranteeTCO)4857 bool X86::isCalleePop(CallingConv::ID CallingConv,
4858                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4859   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4860   // can guarantee TCO.
4861   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4862     return true;
4863 
4864   switch (CallingConv) {
4865   default:
4866     return false;
4867   case CallingConv::X86_StdCall:
4868   case CallingConv::X86_FastCall:
4869   case CallingConv::X86_ThisCall:
4870   case CallingConv::X86_VectorCall:
4871     return !is64Bit;
4872   }
4873 }
4874 
4875 /// Return true if the condition is an signed comparison operation.
isX86CCSigned(unsigned X86CC)4876 static bool isX86CCSigned(unsigned X86CC) {
4877   switch (X86CC) {
4878   default:
4879     llvm_unreachable("Invalid integer condition!");
4880   case X86::COND_E:
4881   case X86::COND_NE:
4882   case X86::COND_B:
4883   case X86::COND_A:
4884   case X86::COND_BE:
4885   case X86::COND_AE:
4886     return false;
4887   case X86::COND_G:
4888   case X86::COND_GE:
4889   case X86::COND_L:
4890   case X86::COND_LE:
4891     return true;
4892   }
4893 }
4894 
TranslateIntegerX86CC(ISD::CondCode SetCCOpcode)4895 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4896   switch (SetCCOpcode) {
4897   default: llvm_unreachable("Invalid integer condition!");
4898   case ISD::SETEQ:  return X86::COND_E;
4899   case ISD::SETGT:  return X86::COND_G;
4900   case ISD::SETGE:  return X86::COND_GE;
4901   case ISD::SETLT:  return X86::COND_L;
4902   case ISD::SETLE:  return X86::COND_LE;
4903   case ISD::SETNE:  return X86::COND_NE;
4904   case ISD::SETULT: return X86::COND_B;
4905   case ISD::SETUGT: return X86::COND_A;
4906   case ISD::SETULE: return X86::COND_BE;
4907   case ISD::SETUGE: return X86::COND_AE;
4908   }
4909 }
4910 
4911 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4912 /// condition code, returning the condition code and the LHS/RHS of the
4913 /// comparison to make.
TranslateX86CC(ISD::CondCode SetCCOpcode,const SDLoc & DL,bool isFP,SDValue & LHS,SDValue & RHS,SelectionDAG & DAG)4914 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4915                                bool isFP, SDValue &LHS, SDValue &RHS,
4916                                SelectionDAG &DAG) {
4917   if (!isFP) {
4918     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4919       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4920         // X > -1   -> X == 0, jump !sign.
4921         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4922         return X86::COND_NS;
4923       }
4924       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4925         // X < 0   -> X == 0, jump on sign.
4926         return X86::COND_S;
4927       }
4928       if (SetCCOpcode == ISD::SETGE && RHSC->isNullValue()) {
4929         // X >= 0   -> X == 0, jump on !sign.
4930         return X86::COND_NS;
4931       }
4932       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
4933         // X < 1   -> X <= 0
4934         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4935         return X86::COND_LE;
4936       }
4937     }
4938 
4939     return TranslateIntegerX86CC(SetCCOpcode);
4940   }
4941 
4942   // First determine if it is required or is profitable to flip the operands.
4943 
4944   // If LHS is a foldable load, but RHS is not, flip the condition.
4945   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4946       !ISD::isNON_EXTLoad(RHS.getNode())) {
4947     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4948     std::swap(LHS, RHS);
4949   }
4950 
4951   switch (SetCCOpcode) {
4952   default: break;
4953   case ISD::SETOLT:
4954   case ISD::SETOLE:
4955   case ISD::SETUGT:
4956   case ISD::SETUGE:
4957     std::swap(LHS, RHS);
4958     break;
4959   }
4960 
4961   // On a floating point condition, the flags are set as follows:
4962   // ZF  PF  CF   op
4963   //  0 | 0 | 0 | X > Y
4964   //  0 | 0 | 1 | X < Y
4965   //  1 | 0 | 0 | X == Y
4966   //  1 | 1 | 1 | unordered
4967   switch (SetCCOpcode) {
4968   default: llvm_unreachable("Condcode should be pre-legalized away");
4969   case ISD::SETUEQ:
4970   case ISD::SETEQ:   return X86::COND_E;
4971   case ISD::SETOLT:              // flipped
4972   case ISD::SETOGT:
4973   case ISD::SETGT:   return X86::COND_A;
4974   case ISD::SETOLE:              // flipped
4975   case ISD::SETOGE:
4976   case ISD::SETGE:   return X86::COND_AE;
4977   case ISD::SETUGT:              // flipped
4978   case ISD::SETULT:
4979   case ISD::SETLT:   return X86::COND_B;
4980   case ISD::SETUGE:              // flipped
4981   case ISD::SETULE:
4982   case ISD::SETLE:   return X86::COND_BE;
4983   case ISD::SETONE:
4984   case ISD::SETNE:   return X86::COND_NE;
4985   case ISD::SETUO:   return X86::COND_P;
4986   case ISD::SETO:    return X86::COND_NP;
4987   case ISD::SETOEQ:
4988   case ISD::SETUNE:  return X86::COND_INVALID;
4989   }
4990 }
4991 
4992 /// Is there a floating point cmov for the specific X86 condition code?
4993 /// Current x86 isa includes the following FP cmov instructions:
4994 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
hasFPCMov(unsigned X86CC)4995 static bool hasFPCMov(unsigned X86CC) {
4996   switch (X86CC) {
4997   default:
4998     return false;
4999   case X86::COND_B:
5000   case X86::COND_BE:
5001   case X86::COND_E:
5002   case X86::COND_P:
5003   case X86::COND_A:
5004   case X86::COND_AE:
5005   case X86::COND_NE:
5006   case X86::COND_NP:
5007     return true;
5008   }
5009 }
5010 
5011 
getTgtMemIntrinsic(IntrinsicInfo & Info,const CallInst & I,MachineFunction & MF,unsigned Intrinsic) const5012 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5013                                            const CallInst &I,
5014                                            MachineFunction &MF,
5015                                            unsigned Intrinsic) const {
5016 
5017   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
5018   if (!IntrData)
5019     return false;
5020 
5021   Info.flags = MachineMemOperand::MONone;
5022   Info.offset = 0;
5023 
5024   switch (IntrData->Type) {
5025   case TRUNCATE_TO_MEM_VI8:
5026   case TRUNCATE_TO_MEM_VI16:
5027   case TRUNCATE_TO_MEM_VI32: {
5028     Info.opc = ISD::INTRINSIC_VOID;
5029     Info.ptrVal = I.getArgOperand(0);
5030     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
5031     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
5032     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
5033       ScalarVT = MVT::i8;
5034     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
5035       ScalarVT = MVT::i16;
5036     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
5037       ScalarVT = MVT::i32;
5038 
5039     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
5040     Info.align = Align(1);
5041     Info.flags |= MachineMemOperand::MOStore;
5042     break;
5043   }
5044   case GATHER:
5045   case GATHER_AVX2: {
5046     Info.opc = ISD::INTRINSIC_W_CHAIN;
5047     Info.ptrVal = nullptr;
5048     MVT DataVT = MVT::getVT(I.getType());
5049     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5050     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5051                                 IndexVT.getVectorNumElements());
5052     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5053     Info.align = Align(1);
5054     Info.flags |= MachineMemOperand::MOLoad;
5055     break;
5056   }
5057   case SCATTER: {
5058     Info.opc = ISD::INTRINSIC_VOID;
5059     Info.ptrVal = nullptr;
5060     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
5061     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5062     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5063                                 IndexVT.getVectorNumElements());
5064     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5065     Info.align = Align(1);
5066     Info.flags |= MachineMemOperand::MOStore;
5067     break;
5068   }
5069   default:
5070     return false;
5071   }
5072 
5073   return true;
5074 }
5075 
5076 /// Returns true if the target can instruction select the
5077 /// specified FP immediate natively. If false, the legalizer will
5078 /// materialize the FP immediate as a load from a constant pool.
isFPImmLegal(const APFloat & Imm,EVT VT,bool ForCodeSize) const5079 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5080                                      bool ForCodeSize) const {
5081   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
5082     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
5083       return true;
5084   }
5085   return false;
5086 }
5087 
shouldReduceLoadWidth(SDNode * Load,ISD::LoadExtType ExtTy,EVT NewVT) const5088 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5089                                               ISD::LoadExtType ExtTy,
5090                                               EVT NewVT) const {
5091   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
5092 
5093   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5094   // relocation target a movq or addq instruction: don't let the load shrink.
5095   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5096   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5097     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5098       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5099 
5100   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5101   // those uses are extracted directly into a store, then the extract + store
5102   // can be store-folded. Therefore, it's probably not worth splitting the load.
5103   EVT VT = Load->getValueType(0);
5104   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5105     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5106       // Skip uses of the chain value. Result 0 of the node is the load value.
5107       if (UI.getUse().getResNo() != 0)
5108         continue;
5109 
5110       // If this use is not an extract + store, it's probably worth splitting.
5111       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5112           UI->use_begin()->getOpcode() != ISD::STORE)
5113         return true;
5114     }
5115     // All non-chain uses are extract + store.
5116     return false;
5117   }
5118 
5119   return true;
5120 }
5121 
5122 /// Returns true if it is beneficial to convert a load of a constant
5123 /// to just the constant itself.
shouldConvertConstantLoadToIntImm(const APInt & Imm,Type * Ty) const5124 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5125                                                           Type *Ty) const {
5126   assert(Ty->isIntegerTy());
5127 
5128   unsigned BitSize = Ty->getPrimitiveSizeInBits();
5129   if (BitSize == 0 || BitSize > 64)
5130     return false;
5131   return true;
5132 }
5133 
reduceSelectOfFPConstantLoads(EVT CmpOpVT) const5134 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5135   // If we are using XMM registers in the ABI and the condition of the select is
5136   // a floating-point compare and we have blendv or conditional move, then it is
5137   // cheaper to select instead of doing a cross-register move and creating a
5138   // load that depends on the compare result.
5139   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5140   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5141 }
5142 
convertSelectOfConstantsToMath(EVT VT) const5143 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5144   // TODO: It might be a win to ease or lift this restriction, but the generic
5145   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5146   if (VT.isVector() && Subtarget.hasAVX512())
5147     return false;
5148 
5149   return true;
5150 }
5151 
decomposeMulByConstant(LLVMContext & Context,EVT VT,SDValue C) const5152 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5153                                                SDValue C) const {
5154   // TODO: We handle scalars using custom code, but generic combining could make
5155   // that unnecessary.
5156   APInt MulC;
5157   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5158     return false;
5159 
5160   // Find the type this will be legalized too. Otherwise we might prematurely
5161   // convert this to shl+add/sub and then still have to type legalize those ops.
5162   // Another choice would be to defer the decision for illegal types until
5163   // after type legalization. But constant splat vectors of i64 can't make it
5164   // through type legalization on 32-bit targets so we would need to special
5165   // case vXi64.
5166   while (getTypeAction(Context, VT) != TypeLegal)
5167     VT = getTypeToTransformTo(Context, VT);
5168 
5169   // If vector multiply is legal, assume that's faster than shl + add/sub.
5170   // TODO: Multiply is a complex op with higher latency and lower throughput in
5171   //       most implementations, so this check could be loosened based on type
5172   //       and/or a CPU attribute.
5173   if (isOperationLegal(ISD::MUL, VT))
5174     return false;
5175 
5176   // shl+add, shl+sub, shl+add+neg
5177   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
5178          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
5179 }
5180 
isExtractSubvectorCheap(EVT ResVT,EVT SrcVT,unsigned Index) const5181 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
5182                                                 unsigned Index) const {
5183   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
5184     return false;
5185 
5186   // Mask vectors support all subregister combinations and operations that
5187   // extract half of vector.
5188   if (ResVT.getVectorElementType() == MVT::i1)
5189     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
5190                           (Index == ResVT.getVectorNumElements()));
5191 
5192   return (Index % ResVT.getVectorNumElements()) == 0;
5193 }
5194 
shouldScalarizeBinop(SDValue VecOp) const5195 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
5196   unsigned Opc = VecOp.getOpcode();
5197 
5198   // Assume target opcodes can't be scalarized.
5199   // TODO - do we have any exceptions?
5200   if (Opc >= ISD::BUILTIN_OP_END)
5201     return false;
5202 
5203   // If the vector op is not supported, try to convert to scalar.
5204   EVT VecVT = VecOp.getValueType();
5205   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
5206     return true;
5207 
5208   // If the vector op is supported, but the scalar op is not, the transform may
5209   // not be worthwhile.
5210   EVT ScalarVT = VecVT.getScalarType();
5211   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
5212 }
5213 
shouldFormOverflowOp(unsigned Opcode,EVT VT,bool) const5214 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
5215                                              bool) const {
5216   // TODO: Allow vectors?
5217   if (VT.isVector())
5218     return false;
5219   return VT.isSimple() || !isOperationExpand(Opcode, VT);
5220 }
5221 
isCheapToSpeculateCttz() const5222 bool X86TargetLowering::isCheapToSpeculateCttz() const {
5223   // Speculate cttz only if we can directly use TZCNT.
5224   return Subtarget.hasBMI();
5225 }
5226 
isCheapToSpeculateCtlz() const5227 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5228   // Speculate ctlz only if we can directly use LZCNT.
5229   return Subtarget.hasLZCNT();
5230 }
5231 
isLoadBitCastBeneficial(EVT LoadVT,EVT BitcastVT,const SelectionDAG & DAG,const MachineMemOperand & MMO) const5232 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5233                                                 const SelectionDAG &DAG,
5234                                                 const MachineMemOperand &MMO) const {
5235   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5236       BitcastVT.getVectorElementType() == MVT::i1)
5237     return false;
5238 
5239   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5240     return false;
5241 
5242   // If both types are legal vectors, it's always ok to convert them.
5243   if (LoadVT.isVector() && BitcastVT.isVector() &&
5244       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5245     return true;
5246 
5247   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5248 }
5249 
canMergeStoresTo(unsigned AddressSpace,EVT MemVT,const SelectionDAG & DAG) const5250 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5251                                          const SelectionDAG &DAG) const {
5252   // Do not merge to float value size (128 bytes) if no implicit
5253   // float attribute is set.
5254   bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
5255       Attribute::NoImplicitFloat);
5256 
5257   if (NoFloat) {
5258     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5259     return (MemVT.getSizeInBits() <= MaxIntSize);
5260   }
5261   // Make sure we don't merge greater than our preferred vector
5262   // width.
5263   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5264     return false;
5265   return true;
5266 }
5267 
isCtlzFast() const5268 bool X86TargetLowering::isCtlzFast() const {
5269   return Subtarget.hasFastLZCNT();
5270 }
5271 
isMaskAndCmp0FoldingBeneficial(const Instruction & AndI) const5272 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5273     const Instruction &AndI) const {
5274   return true;
5275 }
5276 
hasAndNotCompare(SDValue Y) const5277 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5278   EVT VT = Y.getValueType();
5279 
5280   if (VT.isVector())
5281     return false;
5282 
5283   if (!Subtarget.hasBMI())
5284     return false;
5285 
5286   // There are only 32-bit and 64-bit forms for 'andn'.
5287   if (VT != MVT::i32 && VT != MVT::i64)
5288     return false;
5289 
5290   return !isa<ConstantSDNode>(Y);
5291 }
5292 
hasAndNot(SDValue Y) const5293 bool X86TargetLowering::hasAndNot(SDValue Y) const {
5294   EVT VT = Y.getValueType();
5295 
5296   if (!VT.isVector())
5297     return hasAndNotCompare(Y);
5298 
5299   // Vector.
5300 
5301   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5302     return false;
5303 
5304   if (VT == MVT::v4i32)
5305     return true;
5306 
5307   return Subtarget.hasSSE2();
5308 }
5309 
hasBitTest(SDValue X,SDValue Y) const5310 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5311   return X.getValueType().isScalarInteger(); // 'bt'
5312 }
5313 
5314 bool X86TargetLowering::
shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(SDValue X,ConstantSDNode * XC,ConstantSDNode * CC,SDValue Y,unsigned OldShiftOpcode,unsigned NewShiftOpcode,SelectionDAG & DAG) const5315     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5316         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5317         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5318         SelectionDAG &DAG) const {
5319   // Does baseline recommend not to perform the fold by default?
5320   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5321           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5322     return false;
5323   // For scalars this transform is always beneficial.
5324   if (X.getValueType().isScalarInteger())
5325     return true;
5326   // If all the shift amounts are identical, then transform is beneficial even
5327   // with rudimentary SSE2 shifts.
5328   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5329     return true;
5330   // If we have AVX2 with it's powerful shift operations, then it's also good.
5331   if (Subtarget.hasAVX2())
5332     return true;
5333   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5334   return NewShiftOpcode == ISD::SHL;
5335 }
5336 
shouldFoldConstantShiftPairToMask(const SDNode * N,CombineLevel Level) const5337 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5338     const SDNode *N, CombineLevel Level) const {
5339   assert(((N->getOpcode() == ISD::SHL &&
5340            N->getOperand(0).getOpcode() == ISD::SRL) ||
5341           (N->getOpcode() == ISD::SRL &&
5342            N->getOperand(0).getOpcode() == ISD::SHL)) &&
5343          "Expected shift-shift mask");
5344   EVT VT = N->getValueType(0);
5345   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5346       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5347     // Only fold if the shift values are equal - so it folds to AND.
5348     // TODO - we should fold if either is a non-uniform vector but we don't do
5349     // the fold for non-splats yet.
5350     return N->getOperand(1) == N->getOperand(0).getOperand(1);
5351   }
5352   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5353 }
5354 
shouldFoldMaskToVariableShiftPair(SDValue Y) const5355 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5356   EVT VT = Y.getValueType();
5357 
5358   // For vectors, we don't have a preference, but we probably want a mask.
5359   if (VT.isVector())
5360     return false;
5361 
5362   // 64-bit shifts on 32-bit targets produce really bad bloated code.
5363   if (VT == MVT::i64 && !Subtarget.is64Bit())
5364     return false;
5365 
5366   return true;
5367 }
5368 
shouldExpandShift(SelectionDAG & DAG,SDNode * N) const5369 bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5370                                           SDNode *N) const {
5371   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5372       !Subtarget.isOSWindows())
5373     return false;
5374   return true;
5375 }
5376 
shouldSplatInsEltVarIndex(EVT VT) const5377 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5378   // Any legal vector type can be splatted more efficiently than
5379   // loading/spilling from memory.
5380   return isTypeLegal(VT);
5381 }
5382 
hasFastEqualityCompare(unsigned NumBits) const5383 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5384   MVT VT = MVT::getIntegerVT(NumBits);
5385   if (isTypeLegal(VT))
5386     return VT;
5387 
5388   // PMOVMSKB can handle this.
5389   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5390     return MVT::v16i8;
5391 
5392   // VPMOVMSKB can handle this.
5393   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5394     return MVT::v32i8;
5395 
5396   // TODO: Allow 64-bit type for 32-bit target.
5397   // TODO: 512-bit types should be allowed, but make sure that those
5398   // cases are handled in combineVectorSizedSetCCEquality().
5399 
5400   return MVT::INVALID_SIMPLE_VALUE_TYPE;
5401 }
5402 
5403 /// Val is the undef sentinel value or equal to the specified value.
isUndefOrEqual(int Val,int CmpVal)5404 static bool isUndefOrEqual(int Val, int CmpVal) {
5405   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5406 }
5407 
5408 /// Val is either the undef or zero sentinel value.
isUndefOrZero(int Val)5409 static bool isUndefOrZero(int Val) {
5410   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5411 }
5412 
5413 /// Return true if every element in Mask, beginning from position Pos and ending
5414 /// in Pos+Size is the undef sentinel value.
isUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)5415 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5416   return llvm::all_of(Mask.slice(Pos, Size),
5417                       [](int M) { return M == SM_SentinelUndef; });
5418 }
5419 
5420 /// Return true if the mask creates a vector whose lower half is undefined.
isUndefLowerHalf(ArrayRef<int> Mask)5421 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5422   unsigned NumElts = Mask.size();
5423   return isUndefInRange(Mask, 0, NumElts / 2);
5424 }
5425 
5426 /// Return true if the mask creates a vector whose upper half is undefined.
isUndefUpperHalf(ArrayRef<int> Mask)5427 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5428   unsigned NumElts = Mask.size();
5429   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5430 }
5431 
5432 /// Return true if Val falls within the specified range (L, H].
isInRange(int Val,int Low,int Hi)5433 static bool isInRange(int Val, int Low, int Hi) {
5434   return (Val >= Low && Val < Hi);
5435 }
5436 
5437 /// Return true if the value of any element in Mask falls within the specified
5438 /// range (L, H].
isAnyInRange(ArrayRef<int> Mask,int Low,int Hi)5439 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5440   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
5441 }
5442 
5443 /// Return true if the value of any element in Mask is the zero sentinel value.
isAnyZero(ArrayRef<int> Mask)5444 static bool isAnyZero(ArrayRef<int> Mask) {
5445   return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
5446 }
5447 
5448 /// Return true if the value of any element in Mask is the zero or undef
5449 /// sentinel values.
isAnyZeroOrUndef(ArrayRef<int> Mask)5450 static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
5451   return llvm::any_of(Mask, [](int M) {
5452     return M == SM_SentinelZero || M == SM_SentinelUndef;
5453   });
5454 }
5455 
5456 /// Return true if Val is undef or if its value falls within the
5457 /// specified range (L, H].
isUndefOrInRange(int Val,int Low,int Hi)5458 static bool isUndefOrInRange(int Val, int Low, int Hi) {
5459   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5460 }
5461 
5462 /// Return true if every element in Mask is undef or if its value
5463 /// falls within the specified range (L, H].
isUndefOrInRange(ArrayRef<int> Mask,int Low,int Hi)5464 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5465   return llvm::all_of(
5466       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
5467 }
5468 
5469 /// Return true if Val is undef, zero or if its value falls within the
5470 /// specified range (L, H].
isUndefOrZeroOrInRange(int Val,int Low,int Hi)5471 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5472   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5473 }
5474 
5475 /// Return true if every element in Mask is undef, zero or if its value
5476 /// falls within the specified range (L, H].
isUndefOrZeroOrInRange(ArrayRef<int> Mask,int Low,int Hi)5477 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5478   return llvm::all_of(
5479       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
5480 }
5481 
5482 /// Return true if every element in Mask, beginning
5483 /// from position Pos and ending in Pos + Size, falls within the specified
5484 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
isSequentialOrUndefInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)5485 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5486                                        unsigned Size, int Low, int Step = 1) {
5487   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5488     if (!isUndefOrEqual(Mask[i], Low))
5489       return false;
5490   return true;
5491 }
5492 
5493 /// Return true if every element in Mask, beginning
5494 /// from position Pos and ending in Pos+Size, falls within the specified
5495 /// sequential range (Low, Low+Size], or is undef or is zero.
isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size,int Low,int Step=1)5496 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5497                                              unsigned Size, int Low,
5498                                              int Step = 1) {
5499   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5500     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5501       return false;
5502   return true;
5503 }
5504 
5505 /// Return true if every element in Mask, beginning
5506 /// from position Pos and ending in Pos+Size is undef or is zero.
isUndefOrZeroInRange(ArrayRef<int> Mask,unsigned Pos,unsigned Size)5507 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5508                                  unsigned Size) {
5509   return llvm::all_of(Mask.slice(Pos, Size),
5510                       [](int M) { return isUndefOrZero(M); });
5511 }
5512 
5513 /// Helper function to test whether a shuffle mask could be
5514 /// simplified by widening the elements being shuffled.
5515 ///
5516 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5517 /// leaves it in an unspecified state.
5518 ///
5519 /// NOTE: This must handle normal vector shuffle masks and *target* vector
5520 /// shuffle masks. The latter have the special property of a '-2' representing
5521 /// a zero-ed lane of a vector.
canWidenShuffleElements(ArrayRef<int> Mask,SmallVectorImpl<int> & WidenedMask)5522 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5523                                     SmallVectorImpl<int> &WidenedMask) {
5524   WidenedMask.assign(Mask.size() / 2, 0);
5525   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5526     int M0 = Mask[i];
5527     int M1 = Mask[i + 1];
5528 
5529     // If both elements are undef, its trivial.
5530     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5531       WidenedMask[i / 2] = SM_SentinelUndef;
5532       continue;
5533     }
5534 
5535     // Check for an undef mask and a mask value properly aligned to fit with
5536     // a pair of values. If we find such a case, use the non-undef mask's value.
5537     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5538       WidenedMask[i / 2] = M1 / 2;
5539       continue;
5540     }
5541     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5542       WidenedMask[i / 2] = M0 / 2;
5543       continue;
5544     }
5545 
5546     // When zeroing, we need to spread the zeroing across both lanes to widen.
5547     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5548       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5549           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5550         WidenedMask[i / 2] = SM_SentinelZero;
5551         continue;
5552       }
5553       return false;
5554     }
5555 
5556     // Finally check if the two mask values are adjacent and aligned with
5557     // a pair.
5558     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5559       WidenedMask[i / 2] = M0 / 2;
5560       continue;
5561     }
5562 
5563     // Otherwise we can't safely widen the elements used in this shuffle.
5564     return false;
5565   }
5566   assert(WidenedMask.size() == Mask.size() / 2 &&
5567          "Incorrect size of mask after widening the elements!");
5568 
5569   return true;
5570 }
5571 
canWidenShuffleElements(ArrayRef<int> Mask,const APInt & Zeroable,bool V2IsZero,SmallVectorImpl<int> & WidenedMask)5572 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5573                                     const APInt &Zeroable,
5574                                     bool V2IsZero,
5575                                     SmallVectorImpl<int> &WidenedMask) {
5576   // Create an alternative mask with info about zeroable elements.
5577   // Here we do not set undef elements as zeroable.
5578   SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
5579   if (V2IsZero) {
5580     assert(!Zeroable.isNullValue() && "V2's non-undef elements are used?!");
5581     for (int i = 0, Size = Mask.size(); i != Size; ++i)
5582       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
5583         ZeroableMask[i] = SM_SentinelZero;
5584   }
5585   return canWidenShuffleElements(ZeroableMask, WidenedMask);
5586 }
5587 
canWidenShuffleElements(ArrayRef<int> Mask)5588 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5589   SmallVector<int, 32> WidenedMask;
5590   return canWidenShuffleElements(Mask, WidenedMask);
5591 }
5592 
5593 // Attempt to narrow/widen shuffle mask until it matches the target number of
5594 // elements.
scaleShuffleElements(ArrayRef<int> Mask,unsigned NumDstElts,SmallVectorImpl<int> & ScaledMask)5595 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
5596                                  SmallVectorImpl<int> &ScaledMask) {
5597   unsigned NumSrcElts = Mask.size();
5598   assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
5599          "Illegal shuffle scale factor");
5600 
5601   // Narrowing is guaranteed to work.
5602   if (NumDstElts >= NumSrcElts) {
5603     int Scale = NumDstElts / NumSrcElts;
5604     llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
5605     return true;
5606   }
5607 
5608   // We have to repeat the widening until we reach the target size, but we can
5609   // split out the first widening as it sets up ScaledMask for us.
5610   if (canWidenShuffleElements(Mask, ScaledMask)) {
5611     while (ScaledMask.size() > NumDstElts) {
5612       SmallVector<int, 16> WidenedMask;
5613       if (!canWidenShuffleElements(ScaledMask, WidenedMask))
5614         return false;
5615       ScaledMask = std::move(WidenedMask);
5616     }
5617     return true;
5618   }
5619 
5620   return false;
5621 }
5622 
5623 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
isZeroNode(SDValue Elt)5624 bool X86::isZeroNode(SDValue Elt) {
5625   return isNullConstant(Elt) || isNullFPConstant(Elt);
5626 }
5627 
5628 // Build a vector of constants.
5629 // Use an UNDEF node if MaskElt == -1.
5630 // Split 64-bit constants in the 32-bit mode.
getConstVector(ArrayRef<int> Values,MVT VT,SelectionDAG & DAG,const SDLoc & dl,bool IsMask=false)5631 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5632                               const SDLoc &dl, bool IsMask = false) {
5633 
5634   SmallVector<SDValue, 32>  Ops;
5635   bool Split = false;
5636 
5637   MVT ConstVecVT = VT;
5638   unsigned NumElts = VT.getVectorNumElements();
5639   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5640   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5641     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5642     Split = true;
5643   }
5644 
5645   MVT EltVT = ConstVecVT.getVectorElementType();
5646   for (unsigned i = 0; i < NumElts; ++i) {
5647     bool IsUndef = Values[i] < 0 && IsMask;
5648     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5649       DAG.getConstant(Values[i], dl, EltVT);
5650     Ops.push_back(OpNode);
5651     if (Split)
5652       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5653                     DAG.getConstant(0, dl, EltVT));
5654   }
5655   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5656   if (Split)
5657     ConstsNode = DAG.getBitcast(VT, ConstsNode);
5658   return ConstsNode;
5659 }
5660 
getConstVector(ArrayRef<APInt> Bits,APInt & Undefs,MVT VT,SelectionDAG & DAG,const SDLoc & dl)5661 static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5662                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5663   assert(Bits.size() == Undefs.getBitWidth() &&
5664          "Unequal constant and undef arrays");
5665   SmallVector<SDValue, 32> Ops;
5666   bool Split = false;
5667 
5668   MVT ConstVecVT = VT;
5669   unsigned NumElts = VT.getVectorNumElements();
5670   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5671   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5672     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5673     Split = true;
5674   }
5675 
5676   MVT EltVT = ConstVecVT.getVectorElementType();
5677   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5678     if (Undefs[i]) {
5679       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5680       continue;
5681     }
5682     const APInt &V = Bits[i];
5683     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
5684     if (Split) {
5685       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5686       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5687     } else if (EltVT == MVT::f32) {
5688       APFloat FV(APFloat::IEEEsingle(), V);
5689       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5690     } else if (EltVT == MVT::f64) {
5691       APFloat FV(APFloat::IEEEdouble(), V);
5692       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5693     } else {
5694       Ops.push_back(DAG.getConstant(V, dl, EltVT));
5695     }
5696   }
5697 
5698   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5699   return DAG.getBitcast(VT, ConstsNode);
5700 }
5701 
5702 /// Returns a vector of specified type with all zero elements.
getZeroVector(MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)5703 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5704                              SelectionDAG &DAG, const SDLoc &dl) {
5705   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
5706           VT.getVectorElementType() == MVT::i1) &&
5707          "Unexpected vector type");
5708 
5709   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5710   // type. This ensures they get CSE'd. But if the integer type is not
5711   // available, use a floating-point +0.0 instead.
5712   SDValue Vec;
5713   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5714     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5715   } else if (VT.isFloatingPoint()) {
5716     Vec = DAG.getConstantFP(+0.0, dl, VT);
5717   } else if (VT.getVectorElementType() == MVT::i1) {
5718     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
5719            "Unexpected vector type");
5720     Vec = DAG.getConstant(0, dl, VT);
5721   } else {
5722     unsigned Num32BitElts = VT.getSizeInBits() / 32;
5723     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5724   }
5725   return DAG.getBitcast(VT, Vec);
5726 }
5727 
extractSubVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)5728 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5729                                 const SDLoc &dl, unsigned vectorWidth) {
5730   EVT VT = Vec.getValueType();
5731   EVT ElVT = VT.getVectorElementType();
5732   unsigned Factor = VT.getSizeInBits()/vectorWidth;
5733   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5734                                   VT.getVectorNumElements()/Factor);
5735 
5736   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
5737   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5738   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5739 
5740   // This is the index of the first element of the vectorWidth-bit chunk
5741   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5742   IdxVal &= ~(ElemsPerChunk - 1);
5743 
5744   // If the input is a buildvector just emit a smaller one.
5745   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5746     return DAG.getBuildVector(ResultVT, dl,
5747                               Vec->ops().slice(IdxVal, ElemsPerChunk));
5748 
5749   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5750   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5751 }
5752 
5753 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
5754 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5755 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5756 /// instructions or a simple subregister reference. Idx is an index in the
5757 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
5758 /// lowering EXTRACT_VECTOR_ELT operations easier.
extract128BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5759 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5760                                    SelectionDAG &DAG, const SDLoc &dl) {
5761   assert((Vec.getValueType().is256BitVector() ||
5762           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
5763   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5764 }
5765 
5766 /// Generate a DAG to grab 256-bits from a 512-bit vector.
extract256BitVector(SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5767 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5768                                    SelectionDAG &DAG, const SDLoc &dl) {
5769   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
5770   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5771 }
5772 
insertSubVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl,unsigned vectorWidth)5773 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5774                                SelectionDAG &DAG, const SDLoc &dl,
5775                                unsigned vectorWidth) {
5776   assert((vectorWidth == 128 || vectorWidth == 256) &&
5777          "Unsupported vector width");
5778   // Inserting UNDEF is Result
5779   if (Vec.isUndef())
5780     return Result;
5781   EVT VT = Vec.getValueType();
5782   EVT ElVT = VT.getVectorElementType();
5783   EVT ResultVT = Result.getValueType();
5784 
5785   // Insert the relevant vectorWidth bits.
5786   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5787   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5788 
5789   // This is the index of the first element of the vectorWidth-bit chunk
5790   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5791   IdxVal &= ~(ElemsPerChunk - 1);
5792 
5793   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5794   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5795 }
5796 
5797 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
5798 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5799 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5800 /// simple superregister reference.  Idx is an index in the 128 bits
5801 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
5802 /// lowering INSERT_VECTOR_ELT operations easier.
insert128BitVector(SDValue Result,SDValue Vec,unsigned IdxVal,SelectionDAG & DAG,const SDLoc & dl)5803 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5804                                   SelectionDAG &DAG, const SDLoc &dl) {
5805   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
5806   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5807 }
5808 
5809 /// Widen a vector to a larger size with the same scalar type, with the new
5810 /// elements either zero or undef.
widenSubVector(MVT VT,SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)5811 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5812                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5813                               const SDLoc &dl) {
5814   assert(Vec.getValueSizeInBits() < VT.getSizeInBits() &&
5815          Vec.getValueType().getScalarType() == VT.getScalarType() &&
5816          "Unsupported vector widening type");
5817   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5818                                 : DAG.getUNDEF(VT);
5819   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5820                      DAG.getIntPtrConstant(0, dl));
5821 }
5822 
5823 /// Widen a vector to a larger size with the same scalar type, with the new
5824 /// elements either zero or undef.
widenSubVector(SDValue Vec,bool ZeroNewElements,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl,unsigned WideSizeInBits)5825 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
5826                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5827                               const SDLoc &dl, unsigned WideSizeInBits) {
5828   assert(Vec.getValueSizeInBits() < WideSizeInBits &&
5829          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
5830          "Unsupported vector widening type");
5831   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
5832   MVT SVT = Vec.getSimpleValueType().getScalarType();
5833   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
5834   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
5835 }
5836 
5837 // Helper function to collect subvector ops that are concatenated together,
5838 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
5839 // The subvectors in Ops are guaranteed to be the same type.
collectConcatOps(SDNode * N,SmallVectorImpl<SDValue> & Ops)5840 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
5841   assert(Ops.empty() && "Expected an empty ops vector");
5842 
5843   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
5844     Ops.append(N->op_begin(), N->op_end());
5845     return true;
5846   }
5847 
5848   if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
5849     SDValue Src = N->getOperand(0);
5850     SDValue Sub = N->getOperand(1);
5851     const APInt &Idx = N->getConstantOperandAPInt(2);
5852     EVT VT = Src.getValueType();
5853     EVT SubVT = Sub.getValueType();
5854 
5855     // TODO - Handle more general insert_subvector chains.
5856     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
5857         Idx == (VT.getVectorNumElements() / 2)) {
5858       // insert_subvector(insert_subvector(undef, x, lo), y, hi)
5859       if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
5860           Src.getOperand(1).getValueType() == SubVT &&
5861           isNullConstant(Src.getOperand(2))) {
5862         Ops.push_back(Src.getOperand(1));
5863         Ops.push_back(Sub);
5864         return true;
5865       }
5866       // insert_subvector(x, extract_subvector(x, lo), hi)
5867       if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5868           Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
5869         Ops.append(2, Sub);
5870         return true;
5871       }
5872     }
5873   }
5874 
5875   return false;
5876 }
5877 
splitVector(SDValue Op,SelectionDAG & DAG,const SDLoc & dl)5878 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
5879                                                const SDLoc &dl) {
5880   EVT VT = Op.getValueType();
5881   unsigned NumElems = VT.getVectorNumElements();
5882   unsigned SizeInBits = VT.getSizeInBits();
5883   assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
5884          "Can't split odd sized vector");
5885 
5886   SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
5887   SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
5888   return std::make_pair(Lo, Hi);
5889 }
5890 
5891 // Split an unary integer op into 2 half sized ops.
splitVectorIntUnary(SDValue Op,SelectionDAG & DAG)5892 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
5893   EVT VT = Op.getValueType();
5894 
5895   // Make sure we only try to split 256/512-bit types to avoid creating
5896   // narrow vectors.
5897   assert((Op.getOperand(0).getValueType().is256BitVector() ||
5898           Op.getOperand(0).getValueType().is512BitVector()) &&
5899          (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
5900   assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
5901              VT.getVectorNumElements() &&
5902          "Unexpected VTs!");
5903 
5904   SDLoc dl(Op);
5905 
5906   // Extract the Lo/Hi vectors
5907   SDValue Lo, Hi;
5908   std::tie(Lo, Hi) = splitVector(Op.getOperand(0), DAG, dl);
5909 
5910   EVT LoVT, HiVT;
5911   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5912   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
5913                      DAG.getNode(Op.getOpcode(), dl, LoVT, Lo),
5914                      DAG.getNode(Op.getOpcode(), dl, HiVT, Hi));
5915 }
5916 
5917 /// Break a binary integer operation into 2 half sized ops and then
5918 /// concatenate the result back.
splitVectorIntBinary(SDValue Op,SelectionDAG & DAG)5919 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
5920   EVT VT = Op.getValueType();
5921 
5922   // Sanity check that all the types match.
5923   assert(Op.getOperand(0).getValueType() == VT &&
5924          Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
5925   assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
5926 
5927   SDLoc dl(Op);
5928 
5929   // Extract the LHS Lo/Hi vectors
5930   SDValue LHS1, LHS2;
5931   std::tie(LHS1, LHS2) = splitVector(Op.getOperand(0), DAG, dl);
5932 
5933   // Extract the RHS Lo/Hi vectors
5934   SDValue RHS1, RHS2;
5935   std::tie(RHS1, RHS2) = splitVector(Op.getOperand(1), DAG, dl);
5936 
5937   EVT LoVT, HiVT;
5938   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5939   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
5940                      DAG.getNode(Op.getOpcode(), dl, LoVT, LHS1, RHS1),
5941                      DAG.getNode(Op.getOpcode(), dl, HiVT, LHS2, RHS2));
5942 }
5943 
5944 // Helper for splitting operands of an operation to legal target size and
5945 // apply a function on each part.
5946 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
5947 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
5948 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
5949 // The argument Builder is a function that will be applied on each split part:
5950 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
5951 template <typename F>
SplitOpsAndApply(SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,F Builder,bool CheckBWI=true)5952 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5953                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
5954                          F Builder, bool CheckBWI = true) {
5955   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
5956   unsigned NumSubs = 1;
5957   if ((CheckBWI && Subtarget.useBWIRegs()) ||
5958       (!CheckBWI && Subtarget.useAVX512Regs())) {
5959     if (VT.getSizeInBits() > 512) {
5960       NumSubs = VT.getSizeInBits() / 512;
5961       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
5962     }
5963   } else if (Subtarget.hasAVX2()) {
5964     if (VT.getSizeInBits() > 256) {
5965       NumSubs = VT.getSizeInBits() / 256;
5966       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
5967     }
5968   } else {
5969     if (VT.getSizeInBits() > 128) {
5970       NumSubs = VT.getSizeInBits() / 128;
5971       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
5972     }
5973   }
5974 
5975   if (NumSubs == 1)
5976     return Builder(DAG, DL, Ops);
5977 
5978   SmallVector<SDValue, 4> Subs;
5979   for (unsigned i = 0; i != NumSubs; ++i) {
5980     SmallVector<SDValue, 2> SubOps;
5981     for (SDValue Op : Ops) {
5982       EVT OpVT = Op.getValueType();
5983       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
5984       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
5985       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
5986     }
5987     Subs.push_back(Builder(DAG, DL, SubOps));
5988   }
5989   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
5990 }
5991 
5992 /// Insert i1-subvector to i1-vector.
insert1BitVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)5993 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5994                                 const X86Subtarget &Subtarget) {
5995 
5996   SDLoc dl(Op);
5997   SDValue Vec = Op.getOperand(0);
5998   SDValue SubVec = Op.getOperand(1);
5999   SDValue Idx = Op.getOperand(2);
6000   unsigned IdxVal = Op.getConstantOperandVal(2);
6001 
6002   // Inserting undef is a nop. We can just return the original vector.
6003   if (SubVec.isUndef())
6004     return Vec;
6005 
6006   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
6007     return Op;
6008 
6009   MVT OpVT = Op.getSimpleValueType();
6010   unsigned NumElems = OpVT.getVectorNumElements();
6011   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6012 
6013   // Extend to natively supported kshift.
6014   MVT WideOpVT = OpVT;
6015   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
6016     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
6017 
6018   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
6019   // if necessary.
6020   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
6021     // May need to promote to a legal type.
6022     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6023                      DAG.getConstant(0, dl, WideOpVT),
6024                      SubVec, Idx);
6025     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6026   }
6027 
6028   MVT SubVecVT = SubVec.getSimpleValueType();
6029   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
6030   assert(IdxVal + SubVecNumElems <= NumElems &&
6031          IdxVal % SubVecVT.getSizeInBits() == 0 &&
6032          "Unexpected index value in INSERT_SUBVECTOR");
6033 
6034   SDValue Undef = DAG.getUNDEF(WideOpVT);
6035 
6036   if (IdxVal == 0) {
6037     // Zero lower bits of the Vec
6038     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
6039     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
6040                       ZeroIdx);
6041     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6042     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6043     // Merge them together, SubVec should be zero extended.
6044     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6045                          DAG.getConstant(0, dl, WideOpVT),
6046                          SubVec, ZeroIdx);
6047     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6048     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6049   }
6050 
6051   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6052                        Undef, SubVec, ZeroIdx);
6053 
6054   if (Vec.isUndef()) {
6055     assert(IdxVal != 0 && "Unexpected index");
6056     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6057                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6058     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6059   }
6060 
6061   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
6062     assert(IdxVal != 0 && "Unexpected index");
6063     NumElems = WideOpVT.getVectorNumElements();
6064     unsigned ShiftLeft = NumElems - SubVecNumElems;
6065     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6066     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6067                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6068     if (ShiftRight != 0)
6069       SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6070                            DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6071     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6072   }
6073 
6074   // Simple case when we put subvector in the upper part
6075   if (IdxVal + SubVecNumElems == NumElems) {
6076     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6077                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6078     if (SubVecNumElems * 2 == NumElems) {
6079       // Special case, use legal zero extending insert_subvector. This allows
6080       // isel to optimize when bits are known zero.
6081       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
6082       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6083                         DAG.getConstant(0, dl, WideOpVT),
6084                         Vec, ZeroIdx);
6085     } else {
6086       // Otherwise use explicit shifts to zero the bits.
6087       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6088                         Undef, Vec, ZeroIdx);
6089       NumElems = WideOpVT.getVectorNumElements();
6090       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
6091       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6092       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6093     }
6094     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6095     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6096   }
6097 
6098   // Inserting into the middle is more complicated.
6099 
6100   NumElems = WideOpVT.getVectorNumElements();
6101 
6102   // Widen the vector if needed.
6103   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
6104 
6105   unsigned ShiftLeft = NumElems - SubVecNumElems;
6106   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6107 
6108   // Do an optimization for the the most frequently used types.
6109   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
6110     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
6111     Mask0.flipAllBits();
6112     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
6113     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
6114     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
6115     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6116                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6117     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6118                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6119     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6120 
6121     // Reduce to original width if needed.
6122     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6123   }
6124 
6125   // Clear the upper bits of the subvector and move it to its insert position.
6126   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6127                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6128   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6129                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6130 
6131   // Isolate the bits below the insertion point.
6132   unsigned LowShift = NumElems - IdxVal;
6133   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
6134                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
6135   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
6136                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
6137 
6138   // Isolate the bits after the last inserted bit.
6139   unsigned HighShift = IdxVal + SubVecNumElems;
6140   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
6141                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
6142   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
6143                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
6144 
6145   // Now OR all 3 pieces together.
6146   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
6147   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
6148 
6149   // Reduce to original width if needed.
6150   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6151 }
6152 
concatSubVectors(SDValue V1,SDValue V2,SelectionDAG & DAG,const SDLoc & dl)6153 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
6154                                 const SDLoc &dl) {
6155   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
6156   EVT SubVT = V1.getValueType();
6157   EVT SubSVT = SubVT.getScalarType();
6158   unsigned SubNumElts = SubVT.getVectorNumElements();
6159   unsigned SubVectorWidth = SubVT.getSizeInBits();
6160   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
6161   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
6162   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
6163 }
6164 
6165 /// Returns a vector of specified type with all bits set.
6166 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
6167 /// Then bitcast to their original type, ensuring they get CSE'd.
getOnesVector(EVT VT,SelectionDAG & DAG,const SDLoc & dl)6168 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6169   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6170          "Expected a 128/256/512-bit vector type");
6171 
6172   APInt Ones = APInt::getAllOnesValue(32);
6173   unsigned NumElts = VT.getSizeInBits() / 32;
6174   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
6175   return DAG.getBitcast(VT, Vec);
6176 }
6177 
6178 // Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode)6179 static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
6180   switch (Opcode) {
6181   case ISD::ANY_EXTEND:
6182   case ISD::ANY_EXTEND_VECTOR_INREG:
6183     return ISD::ANY_EXTEND_VECTOR_INREG;
6184   case ISD::ZERO_EXTEND:
6185   case ISD::ZERO_EXTEND_VECTOR_INREG:
6186     return ISD::ZERO_EXTEND_VECTOR_INREG;
6187   case ISD::SIGN_EXTEND:
6188   case ISD::SIGN_EXTEND_VECTOR_INREG:
6189     return ISD::SIGN_EXTEND_VECTOR_INREG;
6190   }
6191   llvm_unreachable("Unknown opcode");
6192 }
6193 
getExtendInVec(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue In,SelectionDAG & DAG)6194 static SDValue getExtendInVec(unsigned Opcode, const SDLoc &DL, EVT VT,
6195                               SDValue In, SelectionDAG &DAG) {
6196   EVT InVT = In.getValueType();
6197   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
6198   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
6199           ISD::ZERO_EXTEND == Opcode) &&
6200          "Unknown extension opcode");
6201 
6202   // For 256-bit vectors, we only need the lower (128-bit) input half.
6203   // For 512-bit vectors, we only need the lower input half or quarter.
6204   if (InVT.getSizeInBits() > 128) {
6205     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
6206            "Expected VTs to be the same size!");
6207     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
6208     In = extractSubVector(In, 0, DAG, DL,
6209                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
6210     InVT = In.getValueType();
6211   }
6212 
6213   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
6214     Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
6215 
6216   return DAG.getNode(Opcode, DL, VT, In);
6217 }
6218 
6219 // Match (xor X, -1) -> X.
6220 // Match extract_subvector(xor X, -1) -> extract_subvector(X).
6221 // Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
IsNOT(SDValue V,SelectionDAG & DAG,bool OneUse=false)6222 static SDValue IsNOT(SDValue V, SelectionDAG &DAG, bool OneUse = false) {
6223   V = OneUse ? peekThroughOneUseBitcasts(V) : peekThroughBitcasts(V);
6224   if (V.getOpcode() == ISD::XOR &&
6225       ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
6226     return V.getOperand(0);
6227   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6228       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
6229     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
6230       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
6231       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
6232                          Not, V.getOperand(1));
6233     }
6234   }
6235   SmallVector<SDValue, 2> CatOps;
6236   if (collectConcatOps(V.getNode(), CatOps)) {
6237     for (SDValue &CatOp : CatOps) {
6238       SDValue NotCat = IsNOT(CatOp, DAG);
6239       if (!NotCat) return SDValue();
6240       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
6241     }
6242     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
6243   }
6244   return SDValue();
6245 }
6246 
createUnpackShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Lo,bool Unary)6247 void llvm::createUnpackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6248                                    bool Lo, bool Unary) {
6249   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6250   int NumElts = VT.getVectorNumElements();
6251   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6252   for (int i = 0; i < NumElts; ++i) {
6253     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6254     int Pos = (i % NumEltsInLane) / 2 + LaneStart;
6255     Pos += (Unary ? 0 : NumElts * (i % 2));
6256     Pos += (Lo ? 0 : NumEltsInLane / 2);
6257     Mask.push_back(Pos);
6258   }
6259 }
6260 
6261 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
6262 /// imposed by AVX and specific to the unary pattern. Example:
6263 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
6264 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
createSplat2ShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Lo)6265 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6266                                    bool Lo) {
6267   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6268   int NumElts = VT.getVectorNumElements();
6269   for (int i = 0; i < NumElts; ++i) {
6270     int Pos = i / 2;
6271     Pos += (Lo ? 0 : NumElts / 2);
6272     Mask.push_back(Pos);
6273   }
6274 }
6275 
6276 /// Returns a vector_shuffle node for an unpackl operation.
getUnpackl(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)6277 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
6278                           SDValue V1, SDValue V2) {
6279   SmallVector<int, 8> Mask;
6280   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
6281   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6282 }
6283 
6284 /// Returns a vector_shuffle node for an unpackh operation.
getUnpackh(SelectionDAG & DAG,const SDLoc & dl,MVT VT,SDValue V1,SDValue V2)6285 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
6286                           SDValue V1, SDValue V2) {
6287   SmallVector<int, 8> Mask;
6288   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
6289   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6290 }
6291 
6292 /// Return a vector_shuffle of the specified vector of zero or undef vector.
6293 /// This produces a shuffle where the low element of V2 is swizzled into the
6294 /// zero/undef vector, landing at element Idx.
6295 /// 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)6296 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
6297                                            bool IsZero,
6298                                            const X86Subtarget &Subtarget,
6299                                            SelectionDAG &DAG) {
6300   MVT VT = V2.getSimpleValueType();
6301   SDValue V1 = IsZero
6302     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
6303   int NumElems = VT.getVectorNumElements();
6304   SmallVector<int, 16> MaskVec(NumElems);
6305   for (int i = 0; i != NumElems; ++i)
6306     // If this is the insertion idx, put the low elt of V2 here.
6307     MaskVec[i] = (i == Idx) ? NumElems : i;
6308   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
6309 }
6310 
getTargetConstantFromBasePtr(SDValue Ptr)6311 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
6312   if (Ptr.getOpcode() == X86ISD::Wrapper ||
6313       Ptr.getOpcode() == X86ISD::WrapperRIP)
6314     Ptr = Ptr.getOperand(0);
6315 
6316   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
6317   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
6318     return nullptr;
6319 
6320   return CNode->getConstVal();
6321 }
6322 
getTargetConstantFromNode(LoadSDNode * Load)6323 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
6324   if (!Load || !ISD::isNormalLoad(Load))
6325     return nullptr;
6326   return getTargetConstantFromBasePtr(Load->getBasePtr());
6327 }
6328 
getTargetConstantFromNode(SDValue Op)6329 static const Constant *getTargetConstantFromNode(SDValue Op) {
6330   Op = peekThroughBitcasts(Op);
6331   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
6332 }
6333 
6334 const Constant *
getTargetConstantFromLoad(LoadSDNode * LD) const6335 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
6336   assert(LD && "Unexpected null LoadSDNode");
6337   return getTargetConstantFromNode(LD);
6338 }
6339 
6340 // Extract raw constant bits from constant pools.
getTargetConstantBitsFromNode(SDValue Op,unsigned EltSizeInBits,APInt & UndefElts,SmallVectorImpl<APInt> & EltBits,bool AllowWholeUndefs=true,bool AllowPartialUndefs=true)6341 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
6342                                           APInt &UndefElts,
6343                                           SmallVectorImpl<APInt> &EltBits,
6344                                           bool AllowWholeUndefs = true,
6345                                           bool AllowPartialUndefs = true) {
6346   assert(EltBits.empty() && "Expected an empty EltBits vector");
6347 
6348   Op = peekThroughBitcasts(Op);
6349 
6350   EVT VT = Op.getValueType();
6351   unsigned SizeInBits = VT.getSizeInBits();
6352   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
6353   unsigned NumElts = SizeInBits / EltSizeInBits;
6354 
6355   // Bitcast a source array of element bits to the target size.
6356   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
6357     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
6358     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
6359     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
6360            "Constant bit sizes don't match");
6361 
6362     // Don't split if we don't allow undef bits.
6363     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
6364     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
6365       return false;
6366 
6367     // If we're already the right size, don't bother bitcasting.
6368     if (NumSrcElts == NumElts) {
6369       UndefElts = UndefSrcElts;
6370       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
6371       return true;
6372     }
6373 
6374     // Extract all the undef/constant element data and pack into single bitsets.
6375     APInt UndefBits(SizeInBits, 0);
6376     APInt MaskBits(SizeInBits, 0);
6377 
6378     for (unsigned i = 0; i != NumSrcElts; ++i) {
6379       unsigned BitOffset = i * SrcEltSizeInBits;
6380       if (UndefSrcElts[i])
6381         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
6382       MaskBits.insertBits(SrcEltBits[i], BitOffset);
6383     }
6384 
6385     // Split the undef/constant single bitset data into the target elements.
6386     UndefElts = APInt(NumElts, 0);
6387     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
6388 
6389     for (unsigned i = 0; i != NumElts; ++i) {
6390       unsigned BitOffset = i * EltSizeInBits;
6391       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
6392 
6393       // Only treat an element as UNDEF if all bits are UNDEF.
6394       if (UndefEltBits.isAllOnesValue()) {
6395         if (!AllowWholeUndefs)
6396           return false;
6397         UndefElts.setBit(i);
6398         continue;
6399       }
6400 
6401       // If only some bits are UNDEF then treat them as zero (or bail if not
6402       // supported).
6403       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
6404         return false;
6405 
6406       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
6407     }
6408     return true;
6409   };
6410 
6411   // Collect constant bits and insert into mask/undef bit masks.
6412   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
6413                                 unsigned UndefBitIndex) {
6414     if (!Cst)
6415       return false;
6416     if (isa<UndefValue>(Cst)) {
6417       Undefs.setBit(UndefBitIndex);
6418       return true;
6419     }
6420     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
6421       Mask = CInt->getValue();
6422       return true;
6423     }
6424     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
6425       Mask = CFP->getValueAPF().bitcastToAPInt();
6426       return true;
6427     }
6428     return false;
6429   };
6430 
6431   // Handle UNDEFs.
6432   if (Op.isUndef()) {
6433     APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
6434     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
6435     return CastBitData(UndefSrcElts, SrcEltBits);
6436   }
6437 
6438   // Extract scalar constant bits.
6439   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
6440     APInt UndefSrcElts = APInt::getNullValue(1);
6441     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
6442     return CastBitData(UndefSrcElts, SrcEltBits);
6443   }
6444   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6445     APInt UndefSrcElts = APInt::getNullValue(1);
6446     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6447     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
6448     return CastBitData(UndefSrcElts, SrcEltBits);
6449   }
6450 
6451   // Extract constant bits from build vector.
6452   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
6453     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6454     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6455 
6456     APInt UndefSrcElts(NumSrcElts, 0);
6457     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6458     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6459       const SDValue &Src = Op.getOperand(i);
6460       if (Src.isUndef()) {
6461         UndefSrcElts.setBit(i);
6462         continue;
6463       }
6464       auto *Cst = cast<ConstantSDNode>(Src);
6465       SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
6466     }
6467     return CastBitData(UndefSrcElts, SrcEltBits);
6468   }
6469   if (ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) {
6470     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6471     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6472 
6473     APInt UndefSrcElts(NumSrcElts, 0);
6474     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6475     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6476       const SDValue &Src = Op.getOperand(i);
6477       if (Src.isUndef()) {
6478         UndefSrcElts.setBit(i);
6479         continue;
6480       }
6481       auto *Cst = cast<ConstantFPSDNode>(Src);
6482       APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6483       SrcEltBits[i] = RawBits.zextOrTrunc(SrcEltSizeInBits);
6484     }
6485     return CastBitData(UndefSrcElts, SrcEltBits);
6486   }
6487 
6488   // Extract constant bits from constant pool vector.
6489   if (auto *Cst = getTargetConstantFromNode(Op)) {
6490     Type *CstTy = Cst->getType();
6491     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
6492     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
6493       return false;
6494 
6495     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
6496     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6497 
6498     APInt UndefSrcElts(NumSrcElts, 0);
6499     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6500     for (unsigned i = 0; i != NumSrcElts; ++i)
6501       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
6502                                UndefSrcElts, i))
6503         return false;
6504 
6505     return CastBitData(UndefSrcElts, SrcEltBits);
6506   }
6507 
6508   // Extract constant bits from a broadcasted constant pool scalar.
6509   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
6510       EltSizeInBits <= VT.getScalarSizeInBits()) {
6511     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
6512     if (MemIntr->getMemoryVT().getScalarSizeInBits() != VT.getScalarSizeInBits())
6513       return false;
6514 
6515     SDValue Ptr = MemIntr->getBasePtr();
6516     if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
6517       unsigned SrcEltSizeInBits = C->getType()->getScalarSizeInBits();
6518       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6519 
6520       APInt UndefSrcElts(NumSrcElts, 0);
6521       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
6522       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
6523         if (UndefSrcElts[0])
6524           UndefSrcElts.setBits(0, NumSrcElts);
6525         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
6526         return CastBitData(UndefSrcElts, SrcEltBits);
6527       }
6528     }
6529   }
6530 
6531   // Extract constant bits from a subvector broadcast.
6532   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST) {
6533     SmallVector<APInt, 16> SubEltBits;
6534     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6535                                       UndefElts, SubEltBits, AllowWholeUndefs,
6536                                       AllowPartialUndefs)) {
6537       UndefElts = APInt::getSplat(NumElts, UndefElts);
6538       while (EltBits.size() < NumElts)
6539         EltBits.append(SubEltBits.begin(), SubEltBits.end());
6540       return true;
6541     }
6542   }
6543 
6544   // Extract a rematerialized scalar constant insertion.
6545   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
6546       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6547       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
6548     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6549     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6550 
6551     APInt UndefSrcElts(NumSrcElts, 0);
6552     SmallVector<APInt, 64> SrcEltBits;
6553     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
6554     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
6555     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
6556     return CastBitData(UndefSrcElts, SrcEltBits);
6557   }
6558 
6559   // Insert constant bits from a base and sub vector sources.
6560   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
6561     // TODO - support insert_subvector through bitcasts.
6562     if (EltSizeInBits != VT.getScalarSizeInBits())
6563       return false;
6564 
6565     APInt UndefSubElts;
6566     SmallVector<APInt, 32> EltSubBits;
6567     if (getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6568                                       UndefSubElts, EltSubBits,
6569                                       AllowWholeUndefs, AllowPartialUndefs) &&
6570         getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6571                                       UndefElts, EltBits, AllowWholeUndefs,
6572                                       AllowPartialUndefs)) {
6573       unsigned BaseIdx = Op.getConstantOperandVal(2);
6574       UndefElts.insertBits(UndefSubElts, BaseIdx);
6575       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
6576         EltBits[BaseIdx + i] = EltSubBits[i];
6577       return true;
6578     }
6579   }
6580 
6581   // Extract constant bits from a subvector's source.
6582   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6583     // TODO - support extract_subvector through bitcasts.
6584     if (EltSizeInBits != VT.getScalarSizeInBits())
6585       return false;
6586 
6587     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6588                                       UndefElts, EltBits, AllowWholeUndefs,
6589                                       AllowPartialUndefs)) {
6590       EVT SrcVT = Op.getOperand(0).getValueType();
6591       unsigned NumSrcElts = SrcVT.getVectorNumElements();
6592       unsigned NumSubElts = VT.getVectorNumElements();
6593       unsigned BaseIdx = Op.getConstantOperandVal(1);
6594       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
6595       if ((BaseIdx + NumSubElts) != NumSrcElts)
6596         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
6597       if (BaseIdx != 0)
6598         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
6599       return true;
6600     }
6601   }
6602 
6603   // Extract constant bits from shuffle node sources.
6604   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
6605     // TODO - support shuffle through bitcasts.
6606     if (EltSizeInBits != VT.getScalarSizeInBits())
6607       return false;
6608 
6609     ArrayRef<int> Mask = SVN->getMask();
6610     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
6611         llvm::any_of(Mask, [](int M) { return M < 0; }))
6612       return false;
6613 
6614     APInt UndefElts0, UndefElts1;
6615     SmallVector<APInt, 32> EltBits0, EltBits1;
6616     if (isAnyInRange(Mask, 0, NumElts) &&
6617         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6618                                        UndefElts0, EltBits0, AllowWholeUndefs,
6619                                        AllowPartialUndefs))
6620       return false;
6621     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
6622         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6623                                        UndefElts1, EltBits1, AllowWholeUndefs,
6624                                        AllowPartialUndefs))
6625       return false;
6626 
6627     UndefElts = APInt::getNullValue(NumElts);
6628     for (int i = 0; i != (int)NumElts; ++i) {
6629       int M = Mask[i];
6630       if (M < 0) {
6631         UndefElts.setBit(i);
6632         EltBits.push_back(APInt::getNullValue(EltSizeInBits));
6633       } else if (M < (int)NumElts) {
6634         if (UndefElts0[M])
6635           UndefElts.setBit(i);
6636         EltBits.push_back(EltBits0[M]);
6637       } else {
6638         if (UndefElts1[M - NumElts])
6639           UndefElts.setBit(i);
6640         EltBits.push_back(EltBits1[M - NumElts]);
6641       }
6642     }
6643     return true;
6644   }
6645 
6646   return false;
6647 }
6648 
6649 namespace llvm {
6650 namespace X86 {
isConstantSplat(SDValue Op,APInt & SplatVal,bool AllowPartialUndefs)6651 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
6652   APInt UndefElts;
6653   SmallVector<APInt, 16> EltBits;
6654   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
6655                                     UndefElts, EltBits, true,
6656                                     AllowPartialUndefs)) {
6657     int SplatIndex = -1;
6658     for (int i = 0, e = EltBits.size(); i != e; ++i) {
6659       if (UndefElts[i])
6660         continue;
6661       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
6662         SplatIndex = -1;
6663         break;
6664       }
6665       SplatIndex = i;
6666     }
6667     if (0 <= SplatIndex) {
6668       SplatVal = EltBits[SplatIndex];
6669       return true;
6670     }
6671   }
6672 
6673   return false;
6674 }
6675 } // namespace X86
6676 } // namespace llvm
6677 
getTargetShuffleMaskIndices(SDValue MaskNode,unsigned MaskEltSizeInBits,SmallVectorImpl<uint64_t> & RawMask,APInt & UndefElts)6678 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
6679                                         unsigned MaskEltSizeInBits,
6680                                         SmallVectorImpl<uint64_t> &RawMask,
6681                                         APInt &UndefElts) {
6682   // Extract the raw target constant bits.
6683   SmallVector<APInt, 64> EltBits;
6684   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
6685                                      EltBits, /* AllowWholeUndefs */ true,
6686                                      /* AllowPartialUndefs */ false))
6687     return false;
6688 
6689   // Insert the extracted elements into the mask.
6690   for (APInt Elt : EltBits)
6691     RawMask.push_back(Elt.getZExtValue());
6692 
6693   return true;
6694 }
6695 
6696 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
6697 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
6698 /// Note: This ignores saturation, so inputs must be checked first.
createPackShuffleMask(MVT VT,SmallVectorImpl<int> & Mask,bool Unary,unsigned NumStages=1)6699 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6700                                   bool Unary, unsigned NumStages = 1) {
6701   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6702   unsigned NumElts = VT.getVectorNumElements();
6703   unsigned NumLanes = VT.getSizeInBits() / 128;
6704   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
6705   unsigned Offset = Unary ? 0 : NumElts;
6706   unsigned Repetitions = 1u << (NumStages - 1);
6707   unsigned Increment = 1u << NumStages;
6708   assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
6709 
6710   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
6711     for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
6712       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
6713         Mask.push_back(Elt + (Lane * NumEltsPerLane));
6714       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
6715         Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
6716     }
6717   }
6718 }
6719 
6720 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
getPackDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)6721 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
6722                                 APInt &DemandedLHS, APInt &DemandedRHS) {
6723   int NumLanes = VT.getSizeInBits() / 128;
6724   int NumElts = DemandedElts.getBitWidth();
6725   int NumInnerElts = NumElts / 2;
6726   int NumEltsPerLane = NumElts / NumLanes;
6727   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
6728 
6729   DemandedLHS = APInt::getNullValue(NumInnerElts);
6730   DemandedRHS = APInt::getNullValue(NumInnerElts);
6731 
6732   // Map DemandedElts to the packed operands.
6733   for (int Lane = 0; Lane != NumLanes; ++Lane) {
6734     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
6735       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6736       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6737       if (DemandedElts[OuterIdx])
6738         DemandedLHS.setBit(InnerIdx);
6739       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6740         DemandedRHS.setBit(InnerIdx);
6741     }
6742   }
6743 }
6744 
6745 // Split the demanded elts of a HADD/HSUB node between its operands.
getHorizDemandedElts(EVT VT,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS)6746 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
6747                                  APInt &DemandedLHS, APInt &DemandedRHS) {
6748   int NumLanes = VT.getSizeInBits() / 128;
6749   int NumElts = DemandedElts.getBitWidth();
6750   int NumEltsPerLane = NumElts / NumLanes;
6751   int HalfEltsPerLane = NumEltsPerLane / 2;
6752 
6753   DemandedLHS = APInt::getNullValue(NumElts);
6754   DemandedRHS = APInt::getNullValue(NumElts);
6755 
6756   // Map DemandedElts to the horizontal operands.
6757   for (int Idx = 0; Idx != NumElts; ++Idx) {
6758     if (!DemandedElts[Idx])
6759       continue;
6760     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
6761     int LocalIdx = Idx % NumEltsPerLane;
6762     if (LocalIdx < HalfEltsPerLane) {
6763       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6764       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6765     } else {
6766       LocalIdx -= HalfEltsPerLane;
6767       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6768       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6769     }
6770   }
6771 }
6772 
6773 /// Calculates the shuffle mask corresponding to the target-specific opcode.
6774 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6775 /// operands in \p Ops, and returns true.
6776 /// Sets \p IsUnary to true if only one source is used. Note that this will set
6777 /// IsUnary for shuffles which use a single input multiple times, and in those
6778 /// cases it will adjust the mask to only have indices within that single input.
6779 /// 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)6780 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
6781                                  SmallVectorImpl<SDValue> &Ops,
6782                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
6783   unsigned NumElems = VT.getVectorNumElements();
6784   unsigned MaskEltSize = VT.getScalarSizeInBits();
6785   SmallVector<uint64_t, 32> RawMask;
6786   APInt RawUndefs;
6787   uint64_t ImmN;
6788 
6789   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
6790   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
6791 
6792   IsUnary = false;
6793   bool IsFakeUnary = false;
6794   switch (N->getOpcode()) {
6795   case X86ISD::BLENDI:
6796     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6797     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6798     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6799     DecodeBLENDMask(NumElems, ImmN, Mask);
6800     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6801     break;
6802   case X86ISD::SHUFP:
6803     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6804     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6805     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6806     DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
6807     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6808     break;
6809   case X86ISD::INSERTPS:
6810     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6811     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6812     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6813     DecodeINSERTPSMask(ImmN, Mask);
6814     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6815     break;
6816   case X86ISD::EXTRQI:
6817     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6818     if (isa<ConstantSDNode>(N->getOperand(1)) &&
6819         isa<ConstantSDNode>(N->getOperand(2))) {
6820       int BitLen = N->getConstantOperandVal(1);
6821       int BitIdx = N->getConstantOperandVal(2);
6822       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6823       IsUnary = true;
6824     }
6825     break;
6826   case X86ISD::INSERTQI:
6827     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6828     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6829     if (isa<ConstantSDNode>(N->getOperand(2)) &&
6830         isa<ConstantSDNode>(N->getOperand(3))) {
6831       int BitLen = N->getConstantOperandVal(2);
6832       int BitIdx = N->getConstantOperandVal(3);
6833       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6834       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6835     }
6836     break;
6837   case X86ISD::UNPCKH:
6838     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6839     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6840     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6841     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6842     break;
6843   case X86ISD::UNPCKL:
6844     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6845     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6846     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6847     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6848     break;
6849   case X86ISD::MOVHLPS:
6850     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6851     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6852     DecodeMOVHLPSMask(NumElems, Mask);
6853     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6854     break;
6855   case X86ISD::MOVLHPS:
6856     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6857     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6858     DecodeMOVLHPSMask(NumElems, Mask);
6859     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6860     break;
6861   case X86ISD::VALIGN:
6862     assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
6863            "Only 32-bit and 64-bit elements are supported!");
6864     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6865     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6866     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6867     DecodeVALIGNMask(NumElems, ImmN, Mask);
6868     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6869     Ops.push_back(N->getOperand(1));
6870     Ops.push_back(N->getOperand(0));
6871     break;
6872   case X86ISD::PALIGNR:
6873     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6874     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6875     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6876     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6877     DecodePALIGNRMask(NumElems, ImmN, Mask);
6878     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6879     Ops.push_back(N->getOperand(1));
6880     Ops.push_back(N->getOperand(0));
6881     break;
6882   case X86ISD::VSHLDQ:
6883     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6884     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6885     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6886     DecodePSLLDQMask(NumElems, ImmN, Mask);
6887     IsUnary = true;
6888     break;
6889   case X86ISD::VSRLDQ:
6890     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6891     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6892     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6893     DecodePSRLDQMask(NumElems, ImmN, Mask);
6894     IsUnary = true;
6895     break;
6896   case X86ISD::PSHUFD:
6897   case X86ISD::VPERMILPI:
6898     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6899     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6900     DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
6901     IsUnary = true;
6902     break;
6903   case X86ISD::PSHUFHW:
6904     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6905     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6906     DecodePSHUFHWMask(NumElems, ImmN, Mask);
6907     IsUnary = true;
6908     break;
6909   case X86ISD::PSHUFLW:
6910     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6911     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6912     DecodePSHUFLWMask(NumElems, ImmN, Mask);
6913     IsUnary = true;
6914     break;
6915   case X86ISD::VZEXT_MOVL:
6916     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6917     DecodeZeroMoveLowMask(NumElems, Mask);
6918     IsUnary = true;
6919     break;
6920   case X86ISD::VBROADCAST: {
6921     SDValue N0 = N->getOperand(0);
6922     // See if we're broadcasting from index 0 of an EXTRACT_SUBVECTOR. If so,
6923     // add the pre-extracted value to the Ops vector.
6924     if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6925         N0.getOperand(0).getValueType() == VT &&
6926         N0.getConstantOperandVal(1) == 0)
6927       Ops.push_back(N0.getOperand(0));
6928 
6929     // We only decode broadcasts of same-sized vectors, unless the broadcast
6930     // came from an extract from the original width. If we found one, we
6931     // pushed it the Ops vector above.
6932     if (N0.getValueType() == VT || !Ops.empty()) {
6933       DecodeVectorBroadcast(NumElems, Mask);
6934       IsUnary = true;
6935       break;
6936     }
6937     return false;
6938   }
6939   case X86ISD::VPERMILPV: {
6940     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6941     IsUnary = true;
6942     SDValue MaskNode = N->getOperand(1);
6943     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6944                                     RawUndefs)) {
6945       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6946       break;
6947     }
6948     return false;
6949   }
6950   case X86ISD::PSHUFB: {
6951     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
6952     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6953     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6954     IsUnary = true;
6955     SDValue MaskNode = N->getOperand(1);
6956     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6957       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6958       break;
6959     }
6960     return false;
6961   }
6962   case X86ISD::VPERMI:
6963     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6964     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6965     DecodeVPERMMask(NumElems, ImmN, Mask);
6966     IsUnary = true;
6967     break;
6968   case X86ISD::MOVSS:
6969   case X86ISD::MOVSD:
6970     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6971     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6972     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6973     break;
6974   case X86ISD::VPERM2X128:
6975     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6976     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6977     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6978     DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
6979     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6980     break;
6981   case X86ISD::SHUF128:
6982     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6983     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6984     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6985     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
6986     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6987     break;
6988   case X86ISD::MOVSLDUP:
6989     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6990     DecodeMOVSLDUPMask(NumElems, Mask);
6991     IsUnary = true;
6992     break;
6993   case X86ISD::MOVSHDUP:
6994     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6995     DecodeMOVSHDUPMask(NumElems, Mask);
6996     IsUnary = true;
6997     break;
6998   case X86ISD::MOVDDUP:
6999     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7000     DecodeMOVDDUPMask(NumElems, Mask);
7001     IsUnary = true;
7002     break;
7003   case X86ISD::VPERMIL2: {
7004     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7005     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7006     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7007     SDValue MaskNode = N->getOperand(2);
7008     SDValue CtrlNode = N->getOperand(3);
7009     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
7010       unsigned CtrlImm = CtrlOp->getZExtValue();
7011       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7012                                       RawUndefs)) {
7013         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
7014                             Mask);
7015         break;
7016       }
7017     }
7018     return false;
7019   }
7020   case X86ISD::VPPERM: {
7021     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7022     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7023     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7024     SDValue MaskNode = N->getOperand(2);
7025     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7026       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
7027       break;
7028     }
7029     return false;
7030   }
7031   case X86ISD::VPERMV: {
7032     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7033     IsUnary = true;
7034     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
7035     Ops.push_back(N->getOperand(1));
7036     SDValue MaskNode = N->getOperand(0);
7037     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7038                                     RawUndefs)) {
7039       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
7040       break;
7041     }
7042     return false;
7043   }
7044   case X86ISD::VPERMV3: {
7045     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7046     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
7047     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
7048     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
7049     Ops.push_back(N->getOperand(0));
7050     Ops.push_back(N->getOperand(2));
7051     SDValue MaskNode = N->getOperand(1);
7052     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7053                                     RawUndefs)) {
7054       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
7055       break;
7056     }
7057     return false;
7058   }
7059   default: llvm_unreachable("unknown target shuffle node");
7060   }
7061 
7062   // Empty mask indicates the decode failed.
7063   if (Mask.empty())
7064     return false;
7065 
7066   // Check if we're getting a shuffle mask with zero'd elements.
7067   if (!AllowSentinelZero && isAnyZero(Mask))
7068     return false;
7069 
7070   // If we have a fake unary shuffle, the shuffle mask is spread across two
7071   // inputs that are actually the same node. Re-map the mask to always point
7072   // into the first input.
7073   if (IsFakeUnary)
7074     for (int &M : Mask)
7075       if (M >= (int)Mask.size())
7076         M -= Mask.size();
7077 
7078   // If we didn't already add operands in the opcode-specific code, default to
7079   // adding 1 or 2 operands starting at 0.
7080   if (Ops.empty()) {
7081     Ops.push_back(N->getOperand(0));
7082     if (!IsUnary || IsFakeUnary)
7083       Ops.push_back(N->getOperand(1));
7084   }
7085 
7086   return true;
7087 }
7088 
7089 /// Compute whether each element of a shuffle is zeroable.
7090 ///
7091 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7092 /// Either it is an undef element in the shuffle mask, the element of the input
7093 /// referenced is undef, or the element of the input referenced is known to be
7094 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7095 /// as many lanes with this technique as possible to simplify the remaining
7096 /// shuffle.
computeZeroableShuffleElements(ArrayRef<int> Mask,SDValue V1,SDValue V2,APInt & KnownUndef,APInt & KnownZero)7097 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
7098                                            SDValue V1, SDValue V2,
7099                                            APInt &KnownUndef, APInt &KnownZero) {
7100   int Size = Mask.size();
7101   KnownUndef = KnownZero = APInt::getNullValue(Size);
7102 
7103   V1 = peekThroughBitcasts(V1);
7104   V2 = peekThroughBitcasts(V2);
7105 
7106   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7107   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7108 
7109   int VectorSizeInBits = V1.getValueSizeInBits();
7110   int ScalarSizeInBits = VectorSizeInBits / Size;
7111   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
7112 
7113   for (int i = 0; i < Size; ++i) {
7114     int M = Mask[i];
7115     // Handle the easy cases.
7116     if (M < 0) {
7117       KnownUndef.setBit(i);
7118       continue;
7119     }
7120     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7121       KnownZero.setBit(i);
7122       continue;
7123     }
7124 
7125     // Determine shuffle input and normalize the mask.
7126     SDValue V = M < Size ? V1 : V2;
7127     M %= Size;
7128 
7129     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
7130     if (V.getOpcode() != ISD::BUILD_VECTOR)
7131       continue;
7132 
7133     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
7134     // the (larger) source element must be UNDEF/ZERO.
7135     if ((Size % V.getNumOperands()) == 0) {
7136       int Scale = Size / V->getNumOperands();
7137       SDValue Op = V.getOperand(M / Scale);
7138       if (Op.isUndef())
7139         KnownUndef.setBit(i);
7140       if (X86::isZeroNode(Op))
7141         KnownZero.setBit(i);
7142       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
7143         APInt Val = Cst->getAPIntValue();
7144         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7145         if (Val == 0)
7146           KnownZero.setBit(i);
7147       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7148         APInt Val = Cst->getValueAPF().bitcastToAPInt();
7149         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7150         if (Val == 0)
7151           KnownZero.setBit(i);
7152       }
7153       continue;
7154     }
7155 
7156     // If the BUILD_VECTOR has more elements then all the (smaller) source
7157     // elements must be UNDEF or ZERO.
7158     if ((V.getNumOperands() % Size) == 0) {
7159       int Scale = V->getNumOperands() / Size;
7160       bool AllUndef = true;
7161       bool AllZero = true;
7162       for (int j = 0; j < Scale; ++j) {
7163         SDValue Op = V.getOperand((M * Scale) + j);
7164         AllUndef &= Op.isUndef();
7165         AllZero &= X86::isZeroNode(Op);
7166       }
7167       if (AllUndef)
7168         KnownUndef.setBit(i);
7169       if (AllZero)
7170         KnownZero.setBit(i);
7171       continue;
7172     }
7173   }
7174 }
7175 
7176 /// Decode a target shuffle mask and inputs and see if any values are
7177 /// known to be undef or zero from their inputs.
7178 /// Returns true if the target shuffle mask was decoded.
7179 /// FIXME: Merge this with computeZeroableShuffleElements?
getTargetShuffleAndZeroables(SDValue N,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,APInt & KnownUndef,APInt & KnownZero)7180 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
7181                                          SmallVectorImpl<SDValue> &Ops,
7182                                          APInt &KnownUndef, APInt &KnownZero) {
7183   bool IsUnary;
7184   if (!isTargetShuffle(N.getOpcode()))
7185     return false;
7186 
7187   MVT VT = N.getSimpleValueType();
7188   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
7189     return false;
7190 
7191   int Size = Mask.size();
7192   SDValue V1 = Ops[0];
7193   SDValue V2 = IsUnary ? V1 : Ops[1];
7194   KnownUndef = KnownZero = APInt::getNullValue(Size);
7195 
7196   V1 = peekThroughBitcasts(V1);
7197   V2 = peekThroughBitcasts(V2);
7198 
7199   assert((VT.getSizeInBits() % Size) == 0 &&
7200          "Illegal split of shuffle value type");
7201   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
7202 
7203   // Extract known constant input data.
7204   APInt UndefSrcElts[2];
7205   SmallVector<APInt, 32> SrcEltBits[2];
7206   bool IsSrcConstant[2] = {
7207       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
7208                                     SrcEltBits[0], true, false),
7209       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
7210                                     SrcEltBits[1], true, false)};
7211 
7212   for (int i = 0; i < Size; ++i) {
7213     int M = Mask[i];
7214 
7215     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
7216     if (M < 0) {
7217       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
7218       if (SM_SentinelUndef == M)
7219         KnownUndef.setBit(i);
7220       if (SM_SentinelZero == M)
7221         KnownZero.setBit(i);
7222       continue;
7223     }
7224 
7225     // Determine shuffle input and normalize the mask.
7226     unsigned SrcIdx = M / Size;
7227     SDValue V = M < Size ? V1 : V2;
7228     M %= Size;
7229 
7230     // We are referencing an UNDEF input.
7231     if (V.isUndef()) {
7232       KnownUndef.setBit(i);
7233       continue;
7234     }
7235 
7236     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
7237     // TODO: We currently only set UNDEF for integer types - floats use the same
7238     // registers as vectors and many of the scalar folded loads rely on the
7239     // SCALAR_TO_VECTOR pattern.
7240     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7241         (Size % V.getValueType().getVectorNumElements()) == 0) {
7242       int Scale = Size / V.getValueType().getVectorNumElements();
7243       int Idx = M / Scale;
7244       if (Idx != 0 && !VT.isFloatingPoint())
7245         KnownUndef.setBit(i);
7246       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
7247         KnownZero.setBit(i);
7248       continue;
7249     }
7250 
7251     // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
7252     // base vectors.
7253     if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
7254       SDValue Vec = V.getOperand(0);
7255       int NumVecElts = Vec.getValueType().getVectorNumElements();
7256       if (Vec.isUndef() && Size == NumVecElts) {
7257         int Idx = V.getConstantOperandVal(2);
7258         int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
7259         if (M < Idx || (Idx + NumSubElts) <= M)
7260           KnownUndef.setBit(i);
7261       }
7262       continue;
7263     }
7264 
7265     // Attempt to extract from the source's constant bits.
7266     if (IsSrcConstant[SrcIdx]) {
7267       if (UndefSrcElts[SrcIdx][M])
7268         KnownUndef.setBit(i);
7269       else if (SrcEltBits[SrcIdx][M] == 0)
7270         KnownZero.setBit(i);
7271     }
7272   }
7273 
7274   assert(VT.getVectorNumElements() == (unsigned)Size &&
7275          "Different mask size from vector size!");
7276   return true;
7277 }
7278 
7279 // Replace target shuffle mask elements with known undef/zero sentinels.
resolveTargetShuffleFromZeroables(SmallVectorImpl<int> & Mask,const APInt & KnownUndef,const APInt & KnownZero,bool ResolveKnownZeros=true)7280 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
7281                                               const APInt &KnownUndef,
7282                                               const APInt &KnownZero,
7283                                               bool ResolveKnownZeros= true) {
7284   unsigned NumElts = Mask.size();
7285   assert(KnownUndef.getBitWidth() == NumElts &&
7286          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
7287 
7288   for (unsigned i = 0; i != NumElts; ++i) {
7289     if (KnownUndef[i])
7290       Mask[i] = SM_SentinelUndef;
7291     else if (ResolveKnownZeros && KnownZero[i])
7292       Mask[i] = SM_SentinelZero;
7293   }
7294 }
7295 
7296 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> & Mask,APInt & KnownUndef,APInt & KnownZero)7297 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
7298                                               APInt &KnownUndef,
7299                                               APInt &KnownZero) {
7300   unsigned NumElts = Mask.size();
7301   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
7302 
7303   for (unsigned i = 0; i != NumElts; ++i) {
7304     int M = Mask[i];
7305     if (SM_SentinelUndef == M)
7306       KnownUndef.setBit(i);
7307     if (SM_SentinelZero == M)
7308       KnownZero.setBit(i);
7309   }
7310 }
7311 
7312 // Forward declaration (for getFauxShuffleMask recursive check).
7313 // TODO: Use DemandedElts variant.
7314 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7315                                    SmallVectorImpl<int> &Mask,
7316                                    const SelectionDAG &DAG, unsigned Depth,
7317                                    bool ResolveKnownElts);
7318 
7319 // Attempt to decode ops that could be represented as a shuffle mask.
7320 // The decoded shuffle mask may contain a different number of elements to the
7321 // destination value type.
getFauxShuffleMask(SDValue N,const APInt & DemandedElts,SmallVectorImpl<int> & Mask,SmallVectorImpl<SDValue> & Ops,const SelectionDAG & DAG,unsigned Depth,bool ResolveKnownElts)7322 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
7323                                SmallVectorImpl<int> &Mask,
7324                                SmallVectorImpl<SDValue> &Ops,
7325                                const SelectionDAG &DAG, unsigned Depth,
7326                                bool ResolveKnownElts) {
7327   Mask.clear();
7328   Ops.clear();
7329 
7330   MVT VT = N.getSimpleValueType();
7331   unsigned NumElts = VT.getVectorNumElements();
7332   unsigned NumSizeInBits = VT.getSizeInBits();
7333   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7334   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
7335     return false;
7336   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
7337   unsigned NumSizeInBytes = NumSizeInBits / 8;
7338   unsigned NumBytesPerElt = NumBitsPerElt / 8;
7339 
7340   unsigned Opcode = N.getOpcode();
7341   switch (Opcode) {
7342   case ISD::VECTOR_SHUFFLE: {
7343     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
7344     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
7345     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
7346       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
7347       Ops.push_back(N.getOperand(0));
7348       Ops.push_back(N.getOperand(1));
7349       return true;
7350     }
7351     return false;
7352   }
7353   case ISD::AND:
7354   case X86ISD::ANDNP: {
7355     // Attempt to decode as a per-byte mask.
7356     APInt UndefElts;
7357     SmallVector<APInt, 32> EltBits;
7358     SDValue N0 = N.getOperand(0);
7359     SDValue N1 = N.getOperand(1);
7360     bool IsAndN = (X86ISD::ANDNP == Opcode);
7361     uint64_t ZeroMask = IsAndN ? 255 : 0;
7362     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
7363       return false;
7364     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
7365       if (UndefElts[i]) {
7366         Mask.push_back(SM_SentinelUndef);
7367         continue;
7368       }
7369       const APInt &ByteBits = EltBits[i];
7370       if (ByteBits != 0 && ByteBits != 255)
7371         return false;
7372       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
7373     }
7374     Ops.push_back(IsAndN ? N1 : N0);
7375     return true;
7376   }
7377   case ISD::OR: {
7378     // Inspect each operand at the byte level. We can merge these into a
7379     // blend shuffle mask if for each byte at least one is masked out (zero).
7380     KnownBits Known0 =
7381         DAG.computeKnownBits(N.getOperand(0), DemandedElts, Depth + 1);
7382     KnownBits Known1 =
7383         DAG.computeKnownBits(N.getOperand(1), DemandedElts, Depth + 1);
7384     if (Known0.One.isNullValue() && Known1.One.isNullValue()) {
7385       bool IsByteMask = true;
7386       APInt ZeroMask = APInt::getNullValue(NumBytesPerElt);
7387       APInt SelectMask = APInt::getNullValue(NumBytesPerElt);
7388       for (unsigned i = 0; i != NumBytesPerElt && IsByteMask; ++i) {
7389         unsigned LHS = Known0.Zero.extractBits(8, i * 8).getZExtValue();
7390         unsigned RHS = Known1.Zero.extractBits(8, i * 8).getZExtValue();
7391         if (LHS == 255 && RHS == 0)
7392           SelectMask.setBit(i);
7393         else if (LHS == 255 && RHS == 255)
7394           ZeroMask.setBit(i);
7395         else if (!(LHS == 0 && RHS == 255))
7396           IsByteMask = false;
7397       }
7398       if (IsByteMask) {
7399         for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt) {
7400           for (unsigned j = 0; j != NumBytesPerElt; ++j) {
7401             unsigned Ofs = (SelectMask[j] ? NumSizeInBytes : 0);
7402             int Idx = (ZeroMask[j] ? (int)SM_SentinelZero : (i + j + Ofs));
7403             Mask.push_back(Idx);
7404           }
7405         }
7406         Ops.push_back(N.getOperand(0));
7407         Ops.push_back(N.getOperand(1));
7408         return true;
7409       }
7410     }
7411 
7412     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
7413     // is a valid shuffle index.
7414     SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
7415     SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
7416     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
7417       return false;
7418     SmallVector<int, 64> SrcMask0, SrcMask1;
7419     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
7420     if (!getTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG, Depth + 1,
7421                                 true) ||
7422         !getTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG, Depth + 1,
7423                                 true))
7424       return false;
7425 
7426     // Shuffle inputs must be the same size as the result.
7427     if (llvm::any_of(SrcInputs0, [VT](SDValue Op) {
7428           return VT.getSizeInBits() != Op.getValueSizeInBits();
7429         }))
7430       return false;
7431     if (llvm::any_of(SrcInputs1, [VT](SDValue Op) {
7432           return VT.getSizeInBits() != Op.getValueSizeInBits();
7433         }))
7434       return false;
7435 
7436     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
7437     SmallVector<int, 64> Mask0, Mask1;
7438     narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
7439     narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
7440     for (size_t i = 0; i != MaskSize; ++i) {
7441       if (Mask0[i] == SM_SentinelUndef && Mask1[i] == SM_SentinelUndef)
7442         Mask.push_back(SM_SentinelUndef);
7443       else if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
7444         Mask.push_back(SM_SentinelZero);
7445       else if (Mask1[i] == SM_SentinelZero)
7446         Mask.push_back(Mask0[i]);
7447       else if (Mask0[i] == SM_SentinelZero)
7448         Mask.push_back(Mask1[i] + (int)(MaskSize * SrcInputs0.size()));
7449       else
7450         return false;
7451     }
7452     Ops.append(SrcInputs0.begin(), SrcInputs0.end());
7453     Ops.append(SrcInputs1.begin(), SrcInputs1.end());
7454     return true;
7455   }
7456   case ISD::INSERT_SUBVECTOR: {
7457     SDValue Src = N.getOperand(0);
7458     SDValue Sub = N.getOperand(1);
7459     EVT SubVT = Sub.getValueType();
7460     unsigned NumSubElts = SubVT.getVectorNumElements();
7461     if (!N->isOnlyUserOf(Sub.getNode()))
7462       return false;
7463     uint64_t InsertIdx = N.getConstantOperandVal(2);
7464     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
7465     if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
7466         Sub.getOperand(0).getValueType() == VT) {
7467       uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
7468       for (int i = 0; i != (int)NumElts; ++i)
7469         Mask.push_back(i);
7470       for (int i = 0; i != (int)NumSubElts; ++i)
7471         Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
7472       Ops.push_back(Src);
7473       Ops.push_back(Sub.getOperand(0));
7474       return true;
7475     }
7476     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
7477     SmallVector<int, 64> SubMask;
7478     SmallVector<SDValue, 2> SubInputs;
7479     if (!getTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
7480                                 SubMask, DAG, Depth + 1, ResolveKnownElts))
7481       return false;
7482 
7483     // Subvector shuffle inputs must not be larger than the subvector.
7484     if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
7485           return SubVT.getSizeInBits() < SubInput.getValueSizeInBits();
7486         }))
7487       return false;
7488 
7489     if (SubMask.size() != NumSubElts) {
7490       assert(((SubMask.size() % NumSubElts) == 0 ||
7491               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
7492       if ((NumSubElts % SubMask.size()) == 0) {
7493         int Scale = NumSubElts / SubMask.size();
7494         SmallVector<int,64> ScaledSubMask;
7495         narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
7496         SubMask = ScaledSubMask;
7497       } else {
7498         int Scale = SubMask.size() / NumSubElts;
7499         NumSubElts = SubMask.size();
7500         NumElts *= Scale;
7501         InsertIdx *= Scale;
7502       }
7503     }
7504     Ops.push_back(Src);
7505     Ops.append(SubInputs.begin(), SubInputs.end());
7506     for (int i = 0; i != (int)NumElts; ++i)
7507       Mask.push_back(i);
7508     for (int i = 0; i != (int)NumSubElts; ++i) {
7509       int M = SubMask[i];
7510       if (0 <= M) {
7511         int InputIdx = M / NumSubElts;
7512         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
7513       }
7514       Mask[i + InsertIdx] = M;
7515     }
7516     return true;
7517   }
7518   case X86ISD::PINSRB:
7519   case X86ISD::PINSRW:
7520   case ISD::SCALAR_TO_VECTOR:
7521   case ISD::INSERT_VECTOR_ELT: {
7522     // Match against a insert_vector_elt/scalar_to_vector of an extract from a
7523     // vector, for matching src/dst vector types.
7524     SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
7525 
7526     unsigned DstIdx = 0;
7527     if (Opcode != ISD::SCALAR_TO_VECTOR) {
7528       // Check we have an in-range constant insertion index.
7529       if (!isa<ConstantSDNode>(N.getOperand(2)) ||
7530           N.getConstantOperandAPInt(2).uge(NumElts))
7531         return false;
7532       DstIdx = N.getConstantOperandVal(2);
7533 
7534       // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
7535       if (X86::isZeroNode(Scl)) {
7536         Ops.push_back(N.getOperand(0));
7537         for (unsigned i = 0; i != NumElts; ++i)
7538           Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
7539         return true;
7540       }
7541     }
7542 
7543     // Peek through trunc/aext/zext.
7544     // TODO: aext shouldn't require SM_SentinelZero padding.
7545     // TODO: handle shift of scalars.
7546     unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
7547     while (Scl.getOpcode() == ISD::TRUNCATE ||
7548            Scl.getOpcode() == ISD::ANY_EXTEND ||
7549            Scl.getOpcode() == ISD::ZERO_EXTEND) {
7550       Scl = Scl.getOperand(0);
7551       MinBitsPerElt =
7552           std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
7553     }
7554     if ((MinBitsPerElt % 8) != 0)
7555       return false;
7556 
7557     // Attempt to find the source vector the scalar was extracted from.
7558     SDValue SrcExtract;
7559     if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
7560          Scl.getOpcode() == X86ISD::PEXTRW ||
7561          Scl.getOpcode() == X86ISD::PEXTRB) &&
7562         Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
7563       SrcExtract = Scl;
7564     }
7565     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
7566       return false;
7567 
7568     SDValue SrcVec = SrcExtract.getOperand(0);
7569     EVT SrcVT = SrcVec.getValueType();
7570     if (!SrcVT.getScalarType().isByteSized())
7571       return false;
7572     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
7573     unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
7574     unsigned DstByte = DstIdx * NumBytesPerElt;
7575     MinBitsPerElt =
7576         std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
7577 
7578     // Create 'identity' byte level shuffle mask and then add inserted bytes.
7579     if (Opcode == ISD::SCALAR_TO_VECTOR) {
7580       Ops.push_back(SrcVec);
7581       Mask.append(NumSizeInBytes, SM_SentinelUndef);
7582     } else {
7583       Ops.push_back(SrcVec);
7584       Ops.push_back(N.getOperand(0));
7585       for (int i = 0; i != (int)NumSizeInBytes; ++i)
7586         Mask.push_back(NumSizeInBytes + i);
7587     }
7588 
7589     unsigned MinBytesPerElts = MinBitsPerElt / 8;
7590     MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
7591     for (unsigned i = 0; i != MinBytesPerElts; ++i)
7592       Mask[DstByte + i] = SrcByte + i;
7593     for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
7594       Mask[DstByte + i] = SM_SentinelZero;
7595     return true;
7596   }
7597   case X86ISD::PACKSS:
7598   case X86ISD::PACKUS: {
7599     SDValue N0 = N.getOperand(0);
7600     SDValue N1 = N.getOperand(1);
7601     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
7602            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
7603            "Unexpected input value type");
7604 
7605     APInt EltsLHS, EltsRHS;
7606     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
7607 
7608     // If we know input saturation won't happen we can treat this
7609     // as a truncation shuffle.
7610     if (Opcode == X86ISD::PACKSS) {
7611       if ((!N0.isUndef() &&
7612            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
7613           (!N1.isUndef() &&
7614            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
7615         return false;
7616     } else {
7617       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
7618       if ((!N0.isUndef() &&
7619            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
7620           (!N1.isUndef() &&
7621            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
7622         return false;
7623     }
7624 
7625     bool IsUnary = (N0 == N1);
7626 
7627     Ops.push_back(N0);
7628     if (!IsUnary)
7629       Ops.push_back(N1);
7630 
7631     createPackShuffleMask(VT, Mask, IsUnary);
7632     return true;
7633   }
7634   case X86ISD::VTRUNC: {
7635     SDValue Src = N.getOperand(0);
7636     EVT SrcVT = Src.getValueType();
7637     // Truncated source must be a simple vector.
7638     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7639         (SrcVT.getScalarSizeInBits() % 8) != 0)
7640       return false;
7641     unsigned NumSrcElts = SrcVT.getVectorNumElements();
7642     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7643     unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
7644     assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
7645     for (unsigned i = 0; i != NumSrcElts; ++i)
7646       Mask.push_back(i * Scale);
7647     Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
7648     Ops.push_back(Src);
7649     return true;
7650   }
7651   case X86ISD::VSHLI:
7652   case X86ISD::VSRLI: {
7653     uint64_t ShiftVal = N.getConstantOperandVal(1);
7654     // Out of range bit shifts are guaranteed to be zero.
7655     if (NumBitsPerElt <= ShiftVal) {
7656       Mask.append(NumElts, SM_SentinelZero);
7657       return true;
7658     }
7659 
7660     // We can only decode 'whole byte' bit shifts as shuffles.
7661     if ((ShiftVal % 8) != 0)
7662       break;
7663 
7664     uint64_t ByteShift = ShiftVal / 8;
7665     Ops.push_back(N.getOperand(0));
7666 
7667     // Clear mask to all zeros and insert the shifted byte indices.
7668     Mask.append(NumSizeInBytes, SM_SentinelZero);
7669 
7670     if (X86ISD::VSHLI == Opcode) {
7671       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7672         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7673           Mask[i + j] = i + j - ByteShift;
7674     } else {
7675       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7676         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7677           Mask[i + j - ByteShift] = i + j;
7678     }
7679     return true;
7680   }
7681   case X86ISD::VROTLI:
7682   case X86ISD::VROTRI: {
7683     // We can only decode 'whole byte' bit rotates as shuffles.
7684     uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7685     if ((RotateVal % 8) != 0)
7686       return false;
7687     Ops.push_back(N.getOperand(0));
7688     int Offset = RotateVal / 8;
7689     Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7690     for (int i = 0; i != (int)NumElts; ++i) {
7691       int BaseIdx = i * NumBytesPerElt;
7692       for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7693         Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7694       }
7695     }
7696     return true;
7697   }
7698   case X86ISD::VBROADCAST: {
7699     SDValue Src = N.getOperand(0);
7700     if (!Src.getSimpleValueType().isVector())
7701       return false;
7702     Ops.push_back(Src);
7703     Mask.append(NumElts, 0);
7704     return true;
7705   }
7706   case ISD::ZERO_EXTEND:
7707   case ISD::ANY_EXTEND:
7708   case ISD::ZERO_EXTEND_VECTOR_INREG:
7709   case ISD::ANY_EXTEND_VECTOR_INREG: {
7710     SDValue Src = N.getOperand(0);
7711     EVT SrcVT = Src.getValueType();
7712 
7713     // Extended source must be a simple vector.
7714     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7715         (SrcVT.getScalarSizeInBits() % 8) != 0)
7716       return false;
7717 
7718     bool IsAnyExtend =
7719         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7720     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7721                          IsAnyExtend, Mask);
7722     Ops.push_back(Src);
7723     return true;
7724   }
7725   }
7726 
7727   return false;
7728 }
7729 
7730 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask)7731 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
7732                                               SmallVectorImpl<int> &Mask) {
7733   int MaskWidth = Mask.size();
7734   SmallVector<SDValue, 16> UsedInputs;
7735   for (int i = 0, e = Inputs.size(); i < e; ++i) {
7736     int lo = UsedInputs.size() * MaskWidth;
7737     int hi = lo + MaskWidth;
7738 
7739     // Strip UNDEF input usage.
7740     if (Inputs[i].isUndef())
7741       for (int &M : Mask)
7742         if ((lo <= M) && (M < hi))
7743           M = SM_SentinelUndef;
7744 
7745     // Check for unused inputs.
7746     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7747       for (int &M : Mask)
7748         if (lo <= M)
7749           M -= MaskWidth;
7750       continue;
7751     }
7752 
7753     // Check for repeated inputs.
7754     bool IsRepeat = false;
7755     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7756       if (UsedInputs[j] != Inputs[i])
7757         continue;
7758       for (int &M : Mask)
7759         if (lo <= M)
7760           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7761       IsRepeat = true;
7762       break;
7763     }
7764     if (IsRepeat)
7765       continue;
7766 
7767     UsedInputs.push_back(Inputs[i]);
7768   }
7769   Inputs = UsedInputs;
7770 }
7771 
7772 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7773 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7774 /// 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)7775 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7776                                    SmallVectorImpl<SDValue> &Inputs,
7777                                    SmallVectorImpl<int> &Mask,
7778                                    APInt &KnownUndef, APInt &KnownZero,
7779                                    const SelectionDAG &DAG, unsigned Depth,
7780                                    bool ResolveKnownElts) {
7781   EVT VT = Op.getValueType();
7782   if (!VT.isSimple() || !VT.isVector())
7783     return false;
7784 
7785   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7786     if (ResolveKnownElts)
7787       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7788     return true;
7789   }
7790   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7791                          ResolveKnownElts)) {
7792     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7793     return true;
7794   }
7795   return false;
7796 }
7797 
getTargetShuffleInputs(SDValue Op,SmallVectorImpl<SDValue> & Inputs,SmallVectorImpl<int> & Mask,const SelectionDAG & DAG,unsigned Depth=0,bool ResolveKnownElts=true)7798 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7799                                    SmallVectorImpl<int> &Mask,
7800                                    const SelectionDAG &DAG, unsigned Depth = 0,
7801                                    bool ResolveKnownElts = true) {
7802   EVT VT = Op.getValueType();
7803   if (!VT.isSimple() || !VT.isVector())
7804     return false;
7805 
7806   APInt KnownUndef, KnownZero;
7807   unsigned NumElts = Op.getValueType().getVectorNumElements();
7808   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
7809   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7810                                 KnownZero, DAG, Depth, ResolveKnownElts);
7811 }
7812 
7813 /// Returns the scalar element that will make up the i'th
7814 /// element of the result of the vector shuffle.
getShuffleScalarElt(SDValue Op,unsigned Index,SelectionDAG & DAG,unsigned Depth)7815 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
7816                                    SelectionDAG &DAG, unsigned Depth) {
7817   if (Depth >= SelectionDAG::MaxRecursionDepth)
7818     return SDValue(); // Limit search depth.
7819 
7820   EVT VT = Op.getValueType();
7821   unsigned Opcode = Op.getOpcode();
7822   unsigned NumElems = VT.getVectorNumElements();
7823 
7824   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7825   if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
7826     int Elt = SV->getMaskElt(Index);
7827 
7828     if (Elt < 0)
7829       return DAG.getUNDEF(VT.getVectorElementType());
7830 
7831     SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
7832     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7833   }
7834 
7835   // Recurse into target specific vector shuffles to find scalars.
7836   if (isTargetShuffle(Opcode)) {
7837     MVT ShufVT = VT.getSimpleVT();
7838     MVT ShufSVT = ShufVT.getVectorElementType();
7839     int NumElems = (int)ShufVT.getVectorNumElements();
7840     SmallVector<int, 16> ShuffleMask;
7841     SmallVector<SDValue, 16> ShuffleOps;
7842     bool IsUnary;
7843 
7844     if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
7845                               ShuffleMask, IsUnary))
7846       return SDValue();
7847 
7848     int Elt = ShuffleMask[Index];
7849     if (Elt == SM_SentinelZero)
7850       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
7851                                  : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
7852     if (Elt == SM_SentinelUndef)
7853       return DAG.getUNDEF(ShufSVT);
7854 
7855     assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
7856     SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7857     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7858   }
7859 
7860   // Recurse into insert_subvector base/sub vector to find scalars.
7861   if (Opcode == ISD::INSERT_SUBVECTOR) {
7862     SDValue Vec = Op.getOperand(0);
7863     SDValue Sub = Op.getOperand(1);
7864     uint64_t SubIdx = Op.getConstantOperandVal(2);
7865     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
7866 
7867     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7868       return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
7869     return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
7870   }
7871 
7872   // Recurse into concat_vectors sub vector to find scalars.
7873   if (Opcode == ISD::CONCAT_VECTORS) {
7874     EVT SubVT = Op.getOperand(0).getValueType();
7875     unsigned NumSubElts = SubVT.getVectorNumElements();
7876     uint64_t SubIdx = Index / NumSubElts;
7877     uint64_t SubElt = Index % NumSubElts;
7878     return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
7879   }
7880 
7881   // Recurse into extract_subvector src vector to find scalars.
7882   if (Opcode == ISD::EXTRACT_SUBVECTOR) {
7883     SDValue Src = Op.getOperand(0);
7884     uint64_t SrcIdx = Op.getConstantOperandVal(1);
7885     return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
7886   }
7887 
7888   // We only peek through bitcasts of the same vector width.
7889   if (Opcode == ISD::BITCAST) {
7890     SDValue Src = Op.getOperand(0);
7891     EVT SrcVT = Src.getValueType();
7892     if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
7893       return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
7894     return SDValue();
7895   }
7896 
7897   // Actual nodes that may contain scalar elements
7898 
7899   // For insert_vector_elt - either return the index matching scalar or recurse
7900   // into the base vector.
7901   if (Opcode == ISD::INSERT_VECTOR_ELT &&
7902       isa<ConstantSDNode>(Op.getOperand(2))) {
7903     if (Op.getConstantOperandAPInt(2) == Index)
7904       return Op.getOperand(1);
7905     return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
7906   }
7907 
7908   if (Opcode == ISD::SCALAR_TO_VECTOR)
7909     return (Index == 0) ? Op.getOperand(0)
7910                         : DAG.getUNDEF(VT.getVectorElementType());
7911 
7912   if (Opcode == ISD::BUILD_VECTOR)
7913     return Op.getOperand(Index);
7914 
7915   return SDValue();
7916 }
7917 
7918 // Use PINSRB/PINSRW/PINSRD to create a build vector.
LowerBuildVectorAsInsert(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)7919 static SDValue LowerBuildVectorAsInsert(SDValue Op, unsigned NonZeros,
7920                                         unsigned NumNonZero, unsigned NumZero,
7921                                         SelectionDAG &DAG,
7922                                         const X86Subtarget &Subtarget) {
7923   MVT VT = Op.getSimpleValueType();
7924   unsigned NumElts = VT.getVectorNumElements();
7925   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
7926           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
7927          "Illegal vector insertion");
7928 
7929   SDLoc dl(Op);
7930   SDValue V;
7931   bool First = true;
7932 
7933   for (unsigned i = 0; i < NumElts; ++i) {
7934     bool IsNonZero = (NonZeros & (1 << i)) != 0;
7935     if (!IsNonZero)
7936       continue;
7937 
7938     // If the build vector contains zeros or our first insertion is not the
7939     // first index then insert into zero vector to break any register
7940     // dependency else use SCALAR_TO_VECTOR.
7941     if (First) {
7942       First = false;
7943       if (NumZero || 0 != i)
7944         V = getZeroVector(VT, Subtarget, DAG, dl);
7945       else {
7946         assert(0 == i && "Expected insertion into zero-index");
7947         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7948         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
7949         V = DAG.getBitcast(VT, V);
7950         continue;
7951       }
7952     }
7953     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
7954                     DAG.getIntPtrConstant(i, dl));
7955   }
7956 
7957   return V;
7958 }
7959 
7960 /// Custom lower build_vector of v16i8.
LowerBuildVectorv16i8(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)7961 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
7962                                      unsigned NumNonZero, unsigned NumZero,
7963                                      SelectionDAG &DAG,
7964                                      const X86Subtarget &Subtarget) {
7965   if (NumNonZero > 8 && !Subtarget.hasSSE41())
7966     return SDValue();
7967 
7968   // SSE4.1 - use PINSRB to insert each byte directly.
7969   if (Subtarget.hasSSE41())
7970     return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
7971                                     Subtarget);
7972 
7973   SDLoc dl(Op);
7974   SDValue V;
7975 
7976   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
7977   for (unsigned i = 0; i < 16; i += 2) {
7978     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
7979     bool NextIsNonZero = (NonZeros & (1 << (i + 1))) != 0;
7980     if (!ThisIsNonZero && !NextIsNonZero)
7981       continue;
7982 
7983     // FIXME: Investigate combining the first 4 bytes as a i32 instead.
7984     SDValue Elt;
7985     if (ThisIsNonZero) {
7986       if (NumZero || NextIsNonZero)
7987         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7988       else
7989         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7990     }
7991 
7992     if (NextIsNonZero) {
7993       SDValue NextElt = Op.getOperand(i + 1);
7994       if (i == 0 && NumZero)
7995         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
7996       else
7997         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
7998       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
7999                             DAG.getConstant(8, dl, MVT::i8));
8000       if (ThisIsNonZero)
8001         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
8002       else
8003         Elt = NextElt;
8004     }
8005 
8006     // If our first insertion is not the first index or zeros are needed, then
8007     // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
8008     // elements undefined).
8009     if (!V) {
8010       if (i != 0 || NumZero)
8011         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
8012       else {
8013         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
8014         V = DAG.getBitcast(MVT::v8i16, V);
8015         continue;
8016       }
8017     }
8018     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
8019     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
8020                     DAG.getIntPtrConstant(i / 2, dl));
8021   }
8022 
8023   return DAG.getBitcast(MVT::v16i8, V);
8024 }
8025 
8026 /// Custom lower build_vector of v8i16.
LowerBuildVectorv8i16(SDValue Op,unsigned NonZeros,unsigned NumNonZero,unsigned NumZero,SelectionDAG & DAG,const X86Subtarget & Subtarget)8027 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
8028                                      unsigned NumNonZero, unsigned NumZero,
8029                                      SelectionDAG &DAG,
8030                                      const X86Subtarget &Subtarget) {
8031   if (NumNonZero > 4 && !Subtarget.hasSSE41())
8032     return SDValue();
8033 
8034   // Use PINSRW to insert each byte directly.
8035   return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
8036                                   Subtarget);
8037 }
8038 
8039 /// Custom lower build_vector of v4i32 or v4f32.
LowerBuildVectorv4x32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)8040 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
8041                                      const X86Subtarget &Subtarget) {
8042   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
8043   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
8044   // Because we're creating a less complicated build vector here, we may enable
8045   // further folding of the MOVDDUP via shuffle transforms.
8046   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
8047       Op.getOperand(0) == Op.getOperand(2) &&
8048       Op.getOperand(1) == Op.getOperand(3) &&
8049       Op.getOperand(0) != Op.getOperand(1)) {
8050     SDLoc DL(Op);
8051     MVT VT = Op.getSimpleValueType();
8052     MVT EltVT = VT.getVectorElementType();
8053     // Create a new build vector with the first 2 elements followed by undef
8054     // padding, bitcast to v2f64, duplicate, and bitcast back.
8055     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
8056                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
8057     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
8058     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
8059     return DAG.getBitcast(VT, Dup);
8060   }
8061 
8062   // Find all zeroable elements.
8063   std::bitset<4> Zeroable, Undefs;
8064   for (int i = 0; i < 4; ++i) {
8065     SDValue Elt = Op.getOperand(i);
8066     Undefs[i] = Elt.isUndef();
8067     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
8068   }
8069   assert(Zeroable.size() - Zeroable.count() > 1 &&
8070          "We expect at least two non-zero elements!");
8071 
8072   // We only know how to deal with build_vector nodes where elements are either
8073   // zeroable or extract_vector_elt with constant index.
8074   SDValue FirstNonZero;
8075   unsigned FirstNonZeroIdx;
8076   for (unsigned i = 0; i < 4; ++i) {
8077     if (Zeroable[i])
8078       continue;
8079     SDValue Elt = Op.getOperand(i);
8080     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8081         !isa<ConstantSDNode>(Elt.getOperand(1)))
8082       return SDValue();
8083     // Make sure that this node is extracting from a 128-bit vector.
8084     MVT VT = Elt.getOperand(0).getSimpleValueType();
8085     if (!VT.is128BitVector())
8086       return SDValue();
8087     if (!FirstNonZero.getNode()) {
8088       FirstNonZero = Elt;
8089       FirstNonZeroIdx = i;
8090     }
8091   }
8092 
8093   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
8094   SDValue V1 = FirstNonZero.getOperand(0);
8095   MVT VT = V1.getSimpleValueType();
8096 
8097   // See if this build_vector can be lowered as a blend with zero.
8098   SDValue Elt;
8099   unsigned EltMaskIdx, EltIdx;
8100   int Mask[4];
8101   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
8102     if (Zeroable[EltIdx]) {
8103       // The zero vector will be on the right hand side.
8104       Mask[EltIdx] = EltIdx+4;
8105       continue;
8106     }
8107 
8108     Elt = Op->getOperand(EltIdx);
8109     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
8110     EltMaskIdx = Elt.getConstantOperandVal(1);
8111     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
8112       break;
8113     Mask[EltIdx] = EltIdx;
8114   }
8115 
8116   if (EltIdx == 4) {
8117     // Let the shuffle legalizer deal with blend operations.
8118     SDValue VZeroOrUndef = (Zeroable == Undefs)
8119                                ? DAG.getUNDEF(VT)
8120                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
8121     if (V1.getSimpleValueType() != VT)
8122       V1 = DAG.getBitcast(VT, V1);
8123     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
8124   }
8125 
8126   // See if we can lower this build_vector to a INSERTPS.
8127   if (!Subtarget.hasSSE41())
8128     return SDValue();
8129 
8130   SDValue V2 = Elt.getOperand(0);
8131   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
8132     V1 = SDValue();
8133 
8134   bool CanFold = true;
8135   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
8136     if (Zeroable[i])
8137       continue;
8138 
8139     SDValue Current = Op->getOperand(i);
8140     SDValue SrcVector = Current->getOperand(0);
8141     if (!V1.getNode())
8142       V1 = SrcVector;
8143     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
8144   }
8145 
8146   if (!CanFold)
8147     return SDValue();
8148 
8149   assert(V1.getNode() && "Expected at least two non-zero elements!");
8150   if (V1.getSimpleValueType() != MVT::v4f32)
8151     V1 = DAG.getBitcast(MVT::v4f32, V1);
8152   if (V2.getSimpleValueType() != MVT::v4f32)
8153     V2 = DAG.getBitcast(MVT::v4f32, V2);
8154 
8155   // Ok, we can emit an INSERTPS instruction.
8156   unsigned ZMask = Zeroable.to_ulong();
8157 
8158   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
8159   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8160   SDLoc DL(Op);
8161   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8162                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
8163   return DAG.getBitcast(VT, Result);
8164 }
8165 
8166 /// Return a vector logical shift node.
getVShift(bool isLeft,EVT VT,SDValue SrcOp,unsigned NumBits,SelectionDAG & DAG,const TargetLowering & TLI,const SDLoc & dl)8167 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
8168                          SelectionDAG &DAG, const TargetLowering &TLI,
8169                          const SDLoc &dl) {
8170   assert(VT.is128BitVector() && "Unknown type for VShift");
8171   MVT ShVT = MVT::v16i8;
8172   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
8173   SrcOp = DAG.getBitcast(ShVT, SrcOp);
8174   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
8175   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
8176   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
8177 }
8178 
LowerAsSplatVectorLoad(SDValue SrcOp,MVT VT,const SDLoc & dl,SelectionDAG & DAG)8179 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
8180                                       SelectionDAG &DAG) {
8181 
8182   // Check if the scalar load can be widened into a vector load. And if
8183   // the address is "base + cst" see if the cst can be "absorbed" into
8184   // the shuffle mask.
8185   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
8186     SDValue Ptr = LD->getBasePtr();
8187     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
8188       return SDValue();
8189     EVT PVT = LD->getValueType(0);
8190     if (PVT != MVT::i32 && PVT != MVT::f32)
8191       return SDValue();
8192 
8193     int FI = -1;
8194     int64_t Offset = 0;
8195     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
8196       FI = FINode->getIndex();
8197       Offset = 0;
8198     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
8199                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
8200       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8201       Offset = Ptr.getConstantOperandVal(1);
8202       Ptr = Ptr.getOperand(0);
8203     } else {
8204       return SDValue();
8205     }
8206 
8207     // FIXME: 256-bit vector instructions don't require a strict alignment,
8208     // improve this code to support it better.
8209     Align RequiredAlign(VT.getSizeInBits() / 8);
8210     SDValue Chain = LD->getChain();
8211     // Make sure the stack object alignment is at least 16 or 32.
8212     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8213     MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
8214     if (!InferredAlign || *InferredAlign < RequiredAlign) {
8215       if (MFI.isFixedObjectIndex(FI)) {
8216         // Can't change the alignment. FIXME: It's possible to compute
8217         // the exact stack offset and reference FI + adjust offset instead.
8218         // If someone *really* cares about this. That's the way to implement it.
8219         return SDValue();
8220       } else {
8221         MFI.setObjectAlignment(FI, RequiredAlign);
8222       }
8223     }
8224 
8225     // (Offset % 16 or 32) must be multiple of 4. Then address is then
8226     // Ptr + (Offset & ~15).
8227     if (Offset < 0)
8228       return SDValue();
8229     if ((Offset % RequiredAlign.value()) & 3)
8230       return SDValue();
8231     int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
8232     if (StartOffset) {
8233       SDLoc DL(Ptr);
8234       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
8235                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
8236     }
8237 
8238     int EltNo = (Offset - StartOffset) >> 2;
8239     unsigned NumElems = VT.getVectorNumElements();
8240 
8241     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
8242     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
8243                              LD->getPointerInfo().getWithOffset(StartOffset));
8244 
8245     SmallVector<int, 8> Mask(NumElems, EltNo);
8246 
8247     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
8248   }
8249 
8250   return SDValue();
8251 }
8252 
8253 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
findEltLoadSrc(SDValue Elt,LoadSDNode * & Ld,int64_t & ByteOffset)8254 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
8255   if (ISD::isNON_EXTLoad(Elt.getNode())) {
8256     auto *BaseLd = cast<LoadSDNode>(Elt);
8257     if (!BaseLd->isSimple())
8258       return false;
8259     Ld = BaseLd;
8260     ByteOffset = 0;
8261     return true;
8262   }
8263 
8264   switch (Elt.getOpcode()) {
8265   case ISD::BITCAST:
8266   case ISD::TRUNCATE:
8267   case ISD::SCALAR_TO_VECTOR:
8268     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
8269   case ISD::SRL:
8270     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8271       uint64_t Idx = IdxC->getZExtValue();
8272       if ((Idx % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
8273         ByteOffset += Idx / 8;
8274         return true;
8275       }
8276     }
8277     break;
8278   case ISD::EXTRACT_VECTOR_ELT:
8279     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8280       SDValue Src = Elt.getOperand(0);
8281       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
8282       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
8283       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
8284           findEltLoadSrc(Src, Ld, ByteOffset)) {
8285         uint64_t Idx = IdxC->getZExtValue();
8286         ByteOffset += Idx * (SrcSizeInBits / 8);
8287         return true;
8288       }
8289     }
8290     break;
8291   }
8292 
8293   return false;
8294 }
8295 
8296 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
8297 /// elements can be replaced by a single large load which has the same value as
8298 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
8299 ///
8300 /// 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)8301 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
8302                                         const SDLoc &DL, SelectionDAG &DAG,
8303                                         const X86Subtarget &Subtarget,
8304                                         bool isAfterLegalize) {
8305   if ((VT.getScalarSizeInBits() % 8) != 0)
8306     return SDValue();
8307 
8308   unsigned NumElems = Elts.size();
8309 
8310   int LastLoadedElt = -1;
8311   APInt LoadMask = APInt::getNullValue(NumElems);
8312   APInt ZeroMask = APInt::getNullValue(NumElems);
8313   APInt UndefMask = APInt::getNullValue(NumElems);
8314 
8315   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
8316   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
8317 
8318   // For each element in the initializer, see if we've found a load, zero or an
8319   // undef.
8320   for (unsigned i = 0; i < NumElems; ++i) {
8321     SDValue Elt = peekThroughBitcasts(Elts[i]);
8322     if (!Elt.getNode())
8323       return SDValue();
8324     if (Elt.isUndef()) {
8325       UndefMask.setBit(i);
8326       continue;
8327     }
8328     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
8329       ZeroMask.setBit(i);
8330       continue;
8331     }
8332 
8333     // Each loaded element must be the correct fractional portion of the
8334     // requested vector load.
8335     unsigned EltSizeInBits = Elt.getValueSizeInBits();
8336     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
8337       return SDValue();
8338 
8339     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
8340       return SDValue();
8341     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
8342     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
8343       return SDValue();
8344 
8345     LoadMask.setBit(i);
8346     LastLoadedElt = i;
8347   }
8348   assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +
8349           LoadMask.countPopulation()) == NumElems &&
8350          "Incomplete element masks");
8351 
8352   // Handle Special Cases - all undef or undef/zero.
8353   if (UndefMask.countPopulation() == NumElems)
8354     return DAG.getUNDEF(VT);
8355 
8356   // FIXME: Should we return this as a BUILD_VECTOR instead?
8357   if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
8358     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
8359                           : DAG.getConstantFP(0.0, DL, VT);
8360 
8361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8362   int FirstLoadedElt = LoadMask.countTrailingZeros();
8363   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
8364   EVT EltBaseVT = EltBase.getValueType();
8365   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
8366          "Register/Memory size mismatch");
8367   LoadSDNode *LDBase = Loads[FirstLoadedElt];
8368   assert(LDBase && "Did not find base load for merging consecutive loads");
8369   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
8370   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
8371   int LoadSizeInBits = (1 + LastLoadedElt - FirstLoadedElt) * BaseSizeInBits;
8372   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
8373 
8374   // TODO: Support offsetting the base load.
8375   if (ByteOffsets[FirstLoadedElt] != 0)
8376     return SDValue();
8377 
8378   // Check to see if the element's load is consecutive to the base load
8379   // or offset from a previous (already checked) load.
8380   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
8381     LoadSDNode *Ld = Loads[EltIdx];
8382     int64_t ByteOffset = ByteOffsets[EltIdx];
8383     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
8384       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
8385       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
8386               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
8387     }
8388     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
8389                                               EltIdx - FirstLoadedElt);
8390   };
8391 
8392   // Consecutive loads can contain UNDEFS but not ZERO elements.
8393   // Consecutive loads with UNDEFs and ZEROs elements require a
8394   // an additional shuffle stage to clear the ZERO elements.
8395   bool IsConsecutiveLoad = true;
8396   bool IsConsecutiveLoadWithZeros = true;
8397   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
8398     if (LoadMask[i]) {
8399       if (!CheckConsecutiveLoad(LDBase, i)) {
8400         IsConsecutiveLoad = false;
8401         IsConsecutiveLoadWithZeros = false;
8402         break;
8403       }
8404     } else if (ZeroMask[i]) {
8405       IsConsecutiveLoad = false;
8406     }
8407   }
8408 
8409   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
8410     auto MMOFlags = LDBase->getMemOperand()->getFlags();
8411     assert(LDBase->isSimple() &&
8412            "Cannot merge volatile or atomic loads.");
8413     SDValue NewLd =
8414         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
8415                     LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
8416                     MMOFlags);
8417     for (auto *LD : Loads)
8418       if (LD)
8419         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
8420     return NewLd;
8421   };
8422 
8423   // Check if the base load is entirely dereferenceable.
8424   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
8425       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
8426 
8427   // LOAD - all consecutive load/undefs (must start/end with a load or be
8428   // entirely dereferenceable). If we have found an entire vector of loads and
8429   // undefs, then return a large load of the entire vector width starting at the
8430   // base pointer. If the vector contains zeros, then attempt to shuffle those
8431   // elements.
8432   if (FirstLoadedElt == 0 &&
8433       (LastLoadedElt == (int)(NumElems - 1) || IsDereferenceable) &&
8434       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
8435     if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
8436       return SDValue();
8437 
8438     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
8439     // will lower to regular temporal loads and use the cache.
8440     if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
8441         VT.is256BitVector() && !Subtarget.hasInt256())
8442       return SDValue();
8443 
8444     if (NumElems == 1)
8445       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
8446 
8447     if (!ZeroMask)
8448       return CreateLoad(VT, LDBase);
8449 
8450     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
8451     // vector and a zero vector to clear out the zero elements.
8452     if (!isAfterLegalize && VT.isVector()) {
8453       unsigned NumMaskElts = VT.getVectorNumElements();
8454       if ((NumMaskElts % NumElems) == 0) {
8455         unsigned Scale = NumMaskElts / NumElems;
8456         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
8457         for (unsigned i = 0; i < NumElems; ++i) {
8458           if (UndefMask[i])
8459             continue;
8460           int Offset = ZeroMask[i] ? NumMaskElts : 0;
8461           for (unsigned j = 0; j != Scale; ++j)
8462             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
8463         }
8464         SDValue V = CreateLoad(VT, LDBase);
8465         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
8466                                    : DAG.getConstantFP(0.0, DL, VT);
8467         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
8468       }
8469     }
8470   }
8471 
8472   // If the upper half of a ymm/zmm load is undef then just load the lower half.
8473   if (VT.is256BitVector() || VT.is512BitVector()) {
8474     unsigned HalfNumElems = NumElems / 2;
8475     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnesValue()) {
8476       EVT HalfVT =
8477           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
8478       SDValue HalfLD =
8479           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
8480                                    DAG, Subtarget, isAfterLegalize);
8481       if (HalfLD)
8482         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
8483                            HalfLD, DAG.getIntPtrConstant(0, DL));
8484     }
8485   }
8486 
8487   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
8488   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
8489       (LoadSizeInBits == 32 || LoadSizeInBits == 64) &&
8490       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
8491     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
8492                                       : MVT::getIntegerVT(LoadSizeInBits);
8493     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
8494     // Allow v4f32 on SSE1 only targets.
8495     // FIXME: Add more isel patterns so we can just use VT directly.
8496     if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
8497       VecVT = MVT::v4f32;
8498     if (TLI.isTypeLegal(VecVT)) {
8499       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8500       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8501       SDValue ResNode = DAG.getMemIntrinsicNode(
8502           X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
8503           LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
8504       for (auto *LD : Loads)
8505         if (LD)
8506           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8507       return DAG.getBitcast(VT, ResNode);
8508     }
8509   }
8510 
8511   // BROADCAST - match the smallest possible repetition pattern, load that
8512   // scalar/subvector element and then broadcast to the entire vector.
8513   if (ZeroMask.isNullValue() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8514       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8515     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8516       unsigned RepeatSize = SubElems * BaseSizeInBits;
8517       unsigned ScalarSize = std::min(RepeatSize, 64u);
8518       if (!Subtarget.hasAVX2() && ScalarSize < 32)
8519         continue;
8520 
8521       bool Match = true;
8522       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8523       for (unsigned i = 0; i != NumElems && Match; ++i) {
8524         if (!LoadMask[i])
8525           continue;
8526         SDValue Elt = peekThroughBitcasts(Elts[i]);
8527         if (RepeatedLoads[i % SubElems].isUndef())
8528           RepeatedLoads[i % SubElems] = Elt;
8529         else
8530           Match &= (RepeatedLoads[i % SubElems] == Elt);
8531       }
8532 
8533       // We must have loads at both ends of the repetition.
8534       Match &= !RepeatedLoads.front().isUndef();
8535       Match &= !RepeatedLoads.back().isUndef();
8536       if (!Match)
8537         continue;
8538 
8539       EVT RepeatVT =
8540           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8541               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8542               : EVT::getFloatingPointVT(ScalarSize);
8543       if (RepeatSize > ScalarSize)
8544         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8545                                     RepeatSize / ScalarSize);
8546       EVT BroadcastVT =
8547           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8548                            VT.getSizeInBits() / ScalarSize);
8549       if (TLI.isTypeLegal(BroadcastVT)) {
8550         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8551                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, isAfterLegalize)) {
8552           unsigned Opcode = RepeatSize > ScalarSize ? X86ISD::SUBV_BROADCAST
8553                                                     : X86ISD::VBROADCAST;
8554           SDValue Broadcast = DAG.getNode(Opcode, DL, BroadcastVT, RepeatLoad);
8555           return DAG.getBitcast(VT, Broadcast);
8556         }
8557       }
8558     }
8559   }
8560 
8561   return SDValue();
8562 }
8563 
8564 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8565 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8566 // are consecutive, non-overlapping, and in the right order.
combineToConsecutiveLoads(EVT VT,SDValue Op,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool isAfterLegalize)8567 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
8568                                          SelectionDAG &DAG,
8569                                          const X86Subtarget &Subtarget,
8570                                          bool isAfterLegalize) {
8571   SmallVector<SDValue, 64> Elts;
8572   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8573     if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
8574       Elts.push_back(Elt);
8575       continue;
8576     }
8577     return SDValue();
8578   }
8579   assert(Elts.size() == VT.getVectorNumElements());
8580   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8581                                   isAfterLegalize);
8582 }
8583 
getConstantVector(MVT VT,const APInt & SplatValue,unsigned SplatBitSize,LLVMContext & C)8584 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8585                                    unsigned SplatBitSize, LLVMContext &C) {
8586   unsigned ScalarSize = VT.getScalarSizeInBits();
8587   unsigned NumElm = SplatBitSize / ScalarSize;
8588 
8589   SmallVector<Constant *, 32> ConstantVec;
8590   for (unsigned i = 0; i < NumElm; i++) {
8591     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
8592     Constant *Const;
8593     if (VT.isFloatingPoint()) {
8594       if (ScalarSize == 32) {
8595         Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8596       } else {
8597         assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8598         Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8599       }
8600     } else
8601       Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8602     ConstantVec.push_back(Const);
8603   }
8604   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8605 }
8606 
isFoldableUseOfShuffle(SDNode * N)8607 static bool isFoldableUseOfShuffle(SDNode *N) {
8608   for (auto *U : N->uses()) {
8609     unsigned Opc = U->getOpcode();
8610     // VPERMV/VPERMV3 shuffles can never fold their index operands.
8611     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8612       return false;
8613     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8614       return false;
8615     if (isTargetShuffle(Opc))
8616       return true;
8617     if (Opc == ISD::BITCAST) // Ignore bitcasts
8618       return isFoldableUseOfShuffle(U);
8619     if (N->hasOneUse())
8620       return true;
8621   }
8622   return false;
8623 }
8624 
8625 // Check if the current node of build vector is a zero extended vector.
8626 // // If so, return the value extended.
8627 // // For example: (0,0,0,a,0,0,0,a,0,0,0,a,0,0,0,a) returns a.
8628 // // NumElt - return the number of zero extended identical values.
8629 // // EltType - return the type of the value include the zero extend.
isSplatZeroExtended(const BuildVectorSDNode * Op,unsigned & NumElt,MVT & EltType)8630 static SDValue isSplatZeroExtended(const BuildVectorSDNode *Op,
8631                                    unsigned &NumElt, MVT &EltType) {
8632   SDValue ExtValue = Op->getOperand(0);
8633   unsigned NumElts = Op->getNumOperands();
8634   unsigned Delta = NumElts;
8635 
8636   for (unsigned i = 1; i < NumElts; i++) {
8637     if (Op->getOperand(i) == ExtValue) {
8638       Delta = i;
8639       break;
8640     }
8641     if (!(Op->getOperand(i).isUndef() || isNullConstant(Op->getOperand(i))))
8642       return SDValue();
8643   }
8644   if (!isPowerOf2_32(Delta) || Delta == 1)
8645     return SDValue();
8646 
8647   for (unsigned i = Delta; i < NumElts; i++) {
8648     if (i % Delta == 0) {
8649       if (Op->getOperand(i) != ExtValue)
8650         return SDValue();
8651     } else if (!(isNullConstant(Op->getOperand(i)) ||
8652                  Op->getOperand(i).isUndef()))
8653       return SDValue();
8654   }
8655   unsigned EltSize = Op->getSimpleValueType(0).getScalarSizeInBits();
8656   unsigned ExtVTSize = EltSize * Delta;
8657   EltType = MVT::getIntegerVT(ExtVTSize);
8658   NumElt = NumElts / Delta;
8659   return ExtValue;
8660 }
8661 
8662 /// Attempt to use the vbroadcast instruction to generate a splat value
8663 /// from a splat BUILD_VECTOR which uses:
8664 ///  a. A single scalar load, or a constant.
8665 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8666 ///
8667 /// The VBROADCAST node is returned when a pattern is found,
8668 /// or SDValue() otherwise.
lowerBuildVectorAsBroadcast(BuildVectorSDNode * BVOp,const X86Subtarget & Subtarget,SelectionDAG & DAG)8669 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
8670                                            const X86Subtarget &Subtarget,
8671                                            SelectionDAG &DAG) {
8672   // VBROADCAST requires AVX.
8673   // TODO: Splats could be generated for non-AVX CPUs using SSE
8674   // instructions, but there's less potential gain for only 128-bit vectors.
8675   if (!Subtarget.hasAVX())
8676     return SDValue();
8677 
8678   MVT VT = BVOp->getSimpleValueType(0);
8679   SDLoc dl(BVOp);
8680 
8681   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
8682          "Unsupported vector type for broadcast.");
8683 
8684   BitVector UndefElements;
8685   SDValue Ld = BVOp->getSplatValue(&UndefElements);
8686 
8687   // Attempt to use VBROADCASTM
8688   // From this pattern:
8689   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8690   // b. t1 = (build_vector t0 t0)
8691   //
8692   // Create (VBROADCASTM v2i1 X)
8693   if (Subtarget.hasCDI() && (VT.is512BitVector() || Subtarget.hasVLX())) {
8694     MVT EltType = VT.getScalarType();
8695     unsigned NumElts = VT.getVectorNumElements();
8696     SDValue BOperand;
8697     SDValue ZeroExtended = isSplatZeroExtended(BVOp, NumElts, EltType);
8698     if ((ZeroExtended && ZeroExtended.getOpcode() == ISD::BITCAST) ||
8699         (Ld && Ld.getOpcode() == ISD::ZERO_EXTEND &&
8700          Ld.getOperand(0).getOpcode() == ISD::BITCAST)) {
8701       if (ZeroExtended)
8702         BOperand = ZeroExtended.getOperand(0);
8703       else
8704         BOperand = Ld.getOperand(0).getOperand(0);
8705       MVT MaskVT = BOperand.getSimpleValueType();
8706       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
8707           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8708         SDValue Brdcst =
8709             DAG.getNode(X86ISD::VBROADCASTM, dl,
8710                         MVT::getVectorVT(EltType, NumElts), BOperand);
8711         return DAG.getBitcast(VT, Brdcst);
8712       }
8713     }
8714   }
8715 
8716   unsigned NumElts = VT.getVectorNumElements();
8717   unsigned NumUndefElts = UndefElements.count();
8718   if (!Ld || (NumElts - NumUndefElts) <= 1) {
8719     APInt SplatValue, Undef;
8720     unsigned SplatBitSize;
8721     bool HasUndef;
8722     // Check if this is a repeated constant pattern suitable for broadcasting.
8723     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8724         SplatBitSize > VT.getScalarSizeInBits() &&
8725         SplatBitSize < VT.getSizeInBits()) {
8726       // Avoid replacing with broadcast when it's a use of a shuffle
8727       // instruction to preserve the present custom lowering of shuffles.
8728       if (isFoldableUseOfShuffle(BVOp))
8729         return SDValue();
8730       // replace BUILD_VECTOR with broadcast of the repeated constants.
8731       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8732       LLVMContext *Ctx = DAG.getContext();
8733       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8734       if (Subtarget.hasAVX()) {
8735         if (SplatBitSize == 32 || SplatBitSize == 64 ||
8736             (SplatBitSize < 32 && Subtarget.hasAVX2())) {
8737           // Splatted value can fit in one INTEGER constant in constant pool.
8738           // Load the constant and broadcast it.
8739           MVT CVT = MVT::getIntegerVT(SplatBitSize);
8740           Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
8741           Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
8742           SDValue CP = DAG.getConstantPool(C, PVT);
8743           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8744 
8745           Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8746           SDVTList Tys =
8747               DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
8748           SDValue Ops[] = {DAG.getEntryNode(), CP};
8749           MachinePointerInfo MPI =
8750               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8751           SDValue Brdcst = DAG.getMemIntrinsicNode(
8752               X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT, MPI, Alignment,
8753               MachineMemOperand::MOLoad);
8754           return DAG.getBitcast(VT, Brdcst);
8755         }
8756         if (SplatBitSize > 64) {
8757           // Load the vector of constants and broadcast it.
8758           MVT CVT = VT.getScalarType();
8759           Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
8760                                              *Ctx);
8761           SDValue VCP = DAG.getConstantPool(VecC, PVT);
8762           unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8763           Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
8764           Ld = DAG.getLoad(
8765               MVT::getVectorVT(CVT, NumElm), dl, DAG.getEntryNode(), VCP,
8766               MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
8767               Alignment);
8768           SDValue Brdcst = DAG.getNode(X86ISD::SUBV_BROADCAST, dl, VT, Ld);
8769           return DAG.getBitcast(VT, Brdcst);
8770         }
8771       }
8772     }
8773 
8774     // If we are moving a scalar into a vector (Ld must be set and all elements
8775     // but 1 are undef) and that operation is not obviously supported by
8776     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8777     // That's better than general shuffling and may eliminate a load to GPR and
8778     // move from scalar to vector register.
8779     if (!Ld || NumElts - NumUndefElts != 1)
8780       return SDValue();
8781     unsigned ScalarSize = Ld.getValueSizeInBits();
8782     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8783       return SDValue();
8784   }
8785 
8786   bool ConstSplatVal =
8787       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8788   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8789 
8790   // Make sure that all of the users of a non-constant load are from the
8791   // BUILD_VECTOR node.
8792   // FIXME: Is the use count needed for non-constant, non-load case?
8793   if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
8794     return SDValue();
8795 
8796   unsigned ScalarSize = Ld.getValueSizeInBits();
8797   bool IsGE256 = (VT.getSizeInBits() >= 256);
8798 
8799   // When optimizing for size, generate up to 5 extra bytes for a broadcast
8800   // instruction to save 8 or more bytes of constant pool data.
8801   // TODO: If multiple splats are generated to load the same constant,
8802   // it may be detrimental to overall size. There needs to be a way to detect
8803   // that condition to know if this is truly a size win.
8804   bool OptForSize = DAG.shouldOptForSize();
8805 
8806   // Handle broadcasting a single constant scalar from the constant pool
8807   // into a vector.
8808   // On Sandybridge (no AVX2), it is still better to load a constant vector
8809   // from the constant pool and not to broadcast it from a scalar.
8810   // But override that restriction when optimizing for size.
8811   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
8812   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
8813     EVT CVT = Ld.getValueType();
8814     assert(!CVT.isVector() && "Must not broadcast a vector type");
8815 
8816     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
8817     // For size optimization, also splat v2f64 and v2i64, and for size opt
8818     // with AVX2, also splat i8 and i16.
8819     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
8820     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8821         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
8822       const Constant *C = nullptr;
8823       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
8824         C = CI->getConstantIntValue();
8825       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
8826         C = CF->getConstantFPValue();
8827 
8828       assert(C && "Invalid constant type");
8829 
8830       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8831       SDValue CP =
8832           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
8833       Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8834 
8835       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8836       SDValue Ops[] = {DAG.getEntryNode(), CP};
8837       MachinePointerInfo MPI =
8838           MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8839       return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8840                                      MPI, Alignment, MachineMemOperand::MOLoad);
8841     }
8842   }
8843 
8844   // Handle AVX2 in-register broadcasts.
8845   if (!IsLoad && Subtarget.hasInt256() &&
8846       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
8847     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8848 
8849   // The scalar source must be a normal load.
8850   if (!IsLoad)
8851     return SDValue();
8852 
8853   // Make sure the non-chain result is only used by this build vector.
8854   if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
8855     return SDValue();
8856 
8857   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8858       (Subtarget.hasVLX() && ScalarSize == 64)) {
8859     auto *LN = cast<LoadSDNode>(Ld);
8860     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8861     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8862     SDValue BCast =
8863         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8864                                 LN->getMemoryVT(), LN->getMemOperand());
8865     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8866     return BCast;
8867   }
8868 
8869   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
8870   // double since there is no vbroadcastsd xmm
8871   if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
8872       (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
8873     auto *LN = cast<LoadSDNode>(Ld);
8874     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8875     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8876     SDValue BCast =
8877         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8878                                 LN->getMemoryVT(), LN->getMemOperand());
8879     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8880     return BCast;
8881   }
8882 
8883   // Unsupported broadcast.
8884   return SDValue();
8885 }
8886 
8887 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
8888 /// underlying vector and index.
8889 ///
8890 /// Modifies \p ExtractedFromVec to the real vector and returns the real
8891 /// index.
getUnderlyingExtractedFromVec(SDValue & ExtractedFromVec,SDValue ExtIdx)8892 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
8893                                          SDValue ExtIdx) {
8894   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
8895   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
8896     return Idx;
8897 
8898   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
8899   // lowered this:
8900   //   (extract_vector_elt (v8f32 %1), Constant<6>)
8901   // to:
8902   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
8903   //                           (extract_subvector (v8f32 %0), Constant<4>),
8904   //                           undef)
8905   //                       Constant<0>)
8906   // In this case the vector is the extract_subvector expression and the index
8907   // is 2, as specified by the shuffle.
8908   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
8909   SDValue ShuffleVec = SVOp->getOperand(0);
8910   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
8911   assert(ShuffleVecVT.getVectorElementType() ==
8912          ExtractedFromVec.getSimpleValueType().getVectorElementType());
8913 
8914   int ShuffleIdx = SVOp->getMaskElt(Idx);
8915   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
8916     ExtractedFromVec = ShuffleVec;
8917     return ShuffleIdx;
8918   }
8919   return Idx;
8920 }
8921 
buildFromShuffleMostly(SDValue Op,SelectionDAG & DAG)8922 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
8923   MVT VT = Op.getSimpleValueType();
8924 
8925   // Skip if insert_vec_elt is not supported.
8926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8927   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
8928     return SDValue();
8929 
8930   SDLoc DL(Op);
8931   unsigned NumElems = Op.getNumOperands();
8932 
8933   SDValue VecIn1;
8934   SDValue VecIn2;
8935   SmallVector<unsigned, 4> InsertIndices;
8936   SmallVector<int, 8> Mask(NumElems, -1);
8937 
8938   for (unsigned i = 0; i != NumElems; ++i) {
8939     unsigned Opc = Op.getOperand(i).getOpcode();
8940 
8941     if (Opc == ISD::UNDEF)
8942       continue;
8943 
8944     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
8945       // Quit if more than 1 elements need inserting.
8946       if (InsertIndices.size() > 1)
8947         return SDValue();
8948 
8949       InsertIndices.push_back(i);
8950       continue;
8951     }
8952 
8953     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
8954     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
8955 
8956     // Quit if non-constant index.
8957     if (!isa<ConstantSDNode>(ExtIdx))
8958       return SDValue();
8959     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
8960 
8961     // Quit if extracted from vector of different type.
8962     if (ExtractedFromVec.getValueType() != VT)
8963       return SDValue();
8964 
8965     if (!VecIn1.getNode())
8966       VecIn1 = ExtractedFromVec;
8967     else if (VecIn1 != ExtractedFromVec) {
8968       if (!VecIn2.getNode())
8969         VecIn2 = ExtractedFromVec;
8970       else if (VecIn2 != ExtractedFromVec)
8971         // Quit if more than 2 vectors to shuffle
8972         return SDValue();
8973     }
8974 
8975     if (ExtractedFromVec == VecIn1)
8976       Mask[i] = Idx;
8977     else if (ExtractedFromVec == VecIn2)
8978       Mask[i] = Idx + NumElems;
8979   }
8980 
8981   if (!VecIn1.getNode())
8982     return SDValue();
8983 
8984   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
8985   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
8986 
8987   for (unsigned Idx : InsertIndices)
8988     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
8989                      DAG.getIntPtrConstant(Idx, DL));
8990 
8991   return NV;
8992 }
8993 
8994 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
LowerBUILD_VECTORvXi1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)8995 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
8996                                      const X86Subtarget &Subtarget) {
8997 
8998   MVT VT = Op.getSimpleValueType();
8999   assert((VT.getVectorElementType() == MVT::i1) &&
9000          "Unexpected type in LowerBUILD_VECTORvXi1!");
9001 
9002   SDLoc dl(Op);
9003   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
9004       ISD::isBuildVectorAllOnes(Op.getNode()))
9005     return Op;
9006 
9007   uint64_t Immediate = 0;
9008   SmallVector<unsigned, 16> NonConstIdx;
9009   bool IsSplat = true;
9010   bool HasConstElts = false;
9011   int SplatIdx = -1;
9012   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
9013     SDValue In = Op.getOperand(idx);
9014     if (In.isUndef())
9015       continue;
9016     if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
9017       Immediate |= (InC->getZExtValue() & 0x1) << idx;
9018       HasConstElts = true;
9019     } else {
9020       NonConstIdx.push_back(idx);
9021     }
9022     if (SplatIdx < 0)
9023       SplatIdx = idx;
9024     else if (In != Op.getOperand(SplatIdx))
9025       IsSplat = false;
9026   }
9027 
9028   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
9029   if (IsSplat) {
9030     // The build_vector allows the scalar element to be larger than the vector
9031     // element type. We need to mask it to use as a condition unless we know
9032     // the upper bits are zero.
9033     // FIXME: Use computeKnownBits instead of checking specific opcode?
9034     SDValue Cond = Op.getOperand(SplatIdx);
9035     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
9036     if (Cond.getOpcode() != ISD::SETCC)
9037       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
9038                          DAG.getConstant(1, dl, MVT::i8));
9039 
9040     // Perform the select in the scalar domain so we can use cmov.
9041     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9042       SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
9043                                      DAG.getAllOnesConstant(dl, MVT::i32),
9044                                      DAG.getConstant(0, dl, MVT::i32));
9045       Select = DAG.getBitcast(MVT::v32i1, Select);
9046       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
9047     } else {
9048       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9049       SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
9050                                      DAG.getAllOnesConstant(dl, ImmVT),
9051                                      DAG.getConstant(0, dl, ImmVT));
9052       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9053       Select = DAG.getBitcast(VecVT, Select);
9054       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
9055                          DAG.getIntPtrConstant(0, dl));
9056     }
9057   }
9058 
9059   // insert elements one by one
9060   SDValue DstVec;
9061   if (HasConstElts) {
9062     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9063       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
9064       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
9065       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
9066       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
9067       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
9068     } else {
9069       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9070       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
9071       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9072       DstVec = DAG.getBitcast(VecVT, Imm);
9073       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
9074                            DAG.getIntPtrConstant(0, dl));
9075     }
9076   } else
9077     DstVec = DAG.getUNDEF(VT);
9078 
9079   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
9080     unsigned InsertIdx = NonConstIdx[i];
9081     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9082                          Op.getOperand(InsertIdx),
9083                          DAG.getIntPtrConstant(InsertIdx, dl));
9084   }
9085   return DstVec;
9086 }
9087 
9088 /// This is a helper function of LowerToHorizontalOp().
9089 /// This function checks that the build_vector \p N in input implements a
9090 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
9091 /// may not match the layout of an x86 256-bit horizontal instruction.
9092 /// In other words, if this returns true, then some extraction/insertion will
9093 /// be required to produce a valid horizontal instruction.
9094 ///
9095 /// Parameter \p Opcode defines the kind of horizontal operation to match.
9096 /// For example, if \p Opcode is equal to ISD::ADD, then this function
9097 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
9098 /// is equal to ISD::SUB, then this function checks if this is a horizontal
9099 /// arithmetic sub.
9100 ///
9101 /// This function only analyzes elements of \p N whose indices are
9102 /// in range [BaseIdx, LastIdx).
9103 ///
9104 /// TODO: This function was originally used to match both real and fake partial
9105 /// horizontal operations, but the index-matching logic is incorrect for that.
9106 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
9107 /// 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)9108 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
9109                                   SelectionDAG &DAG,
9110                                   unsigned BaseIdx, unsigned LastIdx,
9111                                   SDValue &V0, SDValue &V1) {
9112   EVT VT = N->getValueType(0);
9113   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
9114   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
9115   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
9116          "Invalid Vector in input!");
9117 
9118   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
9119   bool CanFold = true;
9120   unsigned ExpectedVExtractIdx = BaseIdx;
9121   unsigned NumElts = LastIdx - BaseIdx;
9122   V0 = DAG.getUNDEF(VT);
9123   V1 = DAG.getUNDEF(VT);
9124 
9125   // Check if N implements a horizontal binop.
9126   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
9127     SDValue Op = N->getOperand(i + BaseIdx);
9128 
9129     // Skip UNDEFs.
9130     if (Op->isUndef()) {
9131       // Update the expected vector extract index.
9132       if (i * 2 == NumElts)
9133         ExpectedVExtractIdx = BaseIdx;
9134       ExpectedVExtractIdx += 2;
9135       continue;
9136     }
9137 
9138     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
9139 
9140     if (!CanFold)
9141       break;
9142 
9143     SDValue Op0 = Op.getOperand(0);
9144     SDValue Op1 = Op.getOperand(1);
9145 
9146     // Try to match the following pattern:
9147     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
9148     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9149         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9150         Op0.getOperand(0) == Op1.getOperand(0) &&
9151         isa<ConstantSDNode>(Op0.getOperand(1)) &&
9152         isa<ConstantSDNode>(Op1.getOperand(1)));
9153     if (!CanFold)
9154       break;
9155 
9156     unsigned I0 = Op0.getConstantOperandVal(1);
9157     unsigned I1 = Op1.getConstantOperandVal(1);
9158 
9159     if (i * 2 < NumElts) {
9160       if (V0.isUndef()) {
9161         V0 = Op0.getOperand(0);
9162         if (V0.getValueType() != VT)
9163           return false;
9164       }
9165     } else {
9166       if (V1.isUndef()) {
9167         V1 = Op0.getOperand(0);
9168         if (V1.getValueType() != VT)
9169           return false;
9170       }
9171       if (i * 2 == NumElts)
9172         ExpectedVExtractIdx = BaseIdx;
9173     }
9174 
9175     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
9176     if (I0 == ExpectedVExtractIdx)
9177       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
9178     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
9179       // Try to match the following dag sequence:
9180       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
9181       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
9182     } else
9183       CanFold = false;
9184 
9185     ExpectedVExtractIdx += 2;
9186   }
9187 
9188   return CanFold;
9189 }
9190 
9191 /// Emit a sequence of two 128-bit horizontal add/sub followed by
9192 /// a concat_vector.
9193 ///
9194 /// This is a helper function of LowerToHorizontalOp().
9195 /// This function expects two 256-bit vectors called V0 and V1.
9196 /// At first, each vector is split into two separate 128-bit vectors.
9197 /// Then, the resulting 128-bit vectors are used to implement two
9198 /// horizontal binary operations.
9199 ///
9200 /// The kind of horizontal binary operation is defined by \p X86Opcode.
9201 ///
9202 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
9203 /// the two new horizontal binop.
9204 /// When Mode is set, the first horizontal binop dag node would take as input
9205 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
9206 /// horizontal binop dag node would take as input the lower 128-bit of V1
9207 /// and the upper 128-bit of V1.
9208 ///   Example:
9209 ///     HADD V0_LO, V0_HI
9210 ///     HADD V1_LO, V1_HI
9211 ///
9212 /// Otherwise, the first horizontal binop dag node takes as input the lower
9213 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
9214 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
9215 ///   Example:
9216 ///     HADD V0_LO, V1_LO
9217 ///     HADD V0_HI, V1_HI
9218 ///
9219 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
9220 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
9221 /// 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)9222 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
9223                                      const SDLoc &DL, SelectionDAG &DAG,
9224                                      unsigned X86Opcode, bool Mode,
9225                                      bool isUndefLO, bool isUndefHI) {
9226   MVT VT = V0.getSimpleValueType();
9227   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
9228          "Invalid nodes in input!");
9229 
9230   unsigned NumElts = VT.getVectorNumElements();
9231   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
9232   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
9233   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
9234   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
9235   MVT NewVT = V0_LO.getSimpleValueType();
9236 
9237   SDValue LO = DAG.getUNDEF(NewVT);
9238   SDValue HI = DAG.getUNDEF(NewVT);
9239 
9240   if (Mode) {
9241     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9242     if (!isUndefLO && !V0->isUndef())
9243       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
9244     if (!isUndefHI && !V1->isUndef())
9245       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
9246   } else {
9247     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9248     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
9249       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
9250 
9251     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
9252       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
9253   }
9254 
9255   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
9256 }
9257 
9258 /// Returns true iff \p BV builds a vector with the result equivalent to
9259 /// the result of ADDSUB/SUBADD operation.
9260 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
9261 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
9262 /// \p Opnd0 and \p Opnd1.
isAddSubOrSubAdd(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,unsigned & NumExtracts,bool & IsSubAdd)9263 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
9264                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
9265                              SDValue &Opnd0, SDValue &Opnd1,
9266                              unsigned &NumExtracts,
9267                              bool &IsSubAdd) {
9268 
9269   MVT VT = BV->getSimpleValueType(0);
9270   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
9271     return false;
9272 
9273   unsigned NumElts = VT.getVectorNumElements();
9274   SDValue InVec0 = DAG.getUNDEF(VT);
9275   SDValue InVec1 = DAG.getUNDEF(VT);
9276 
9277   NumExtracts = 0;
9278 
9279   // Odd-numbered elements in the input build vector are obtained from
9280   // adding/subtracting two integer/float elements.
9281   // Even-numbered elements in the input build vector are obtained from
9282   // subtracting/adding two integer/float elements.
9283   unsigned Opc[2] = {0, 0};
9284   for (unsigned i = 0, e = NumElts; i != e; ++i) {
9285     SDValue Op = BV->getOperand(i);
9286 
9287     // Skip 'undef' values.
9288     unsigned Opcode = Op.getOpcode();
9289     if (Opcode == ISD::UNDEF)
9290       continue;
9291 
9292     // Early exit if we found an unexpected opcode.
9293     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
9294       return false;
9295 
9296     SDValue Op0 = Op.getOperand(0);
9297     SDValue Op1 = Op.getOperand(1);
9298 
9299     // Try to match the following pattern:
9300     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
9301     // Early exit if we cannot match that sequence.
9302     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9303         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9304         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9305         Op0.getOperand(1) != Op1.getOperand(1))
9306       return false;
9307 
9308     unsigned I0 = Op0.getConstantOperandVal(1);
9309     if (I0 != i)
9310       return false;
9311 
9312     // We found a valid add/sub node, make sure its the same opcode as previous
9313     // elements for this parity.
9314     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
9315       return false;
9316     Opc[i % 2] = Opcode;
9317 
9318     // Update InVec0 and InVec1.
9319     if (InVec0.isUndef()) {
9320       InVec0 = Op0.getOperand(0);
9321       if (InVec0.getSimpleValueType() != VT)
9322         return false;
9323     }
9324     if (InVec1.isUndef()) {
9325       InVec1 = Op1.getOperand(0);
9326       if (InVec1.getSimpleValueType() != VT)
9327         return false;
9328     }
9329 
9330     // Make sure that operands in input to each add/sub node always
9331     // come from a same pair of vectors.
9332     if (InVec0 != Op0.getOperand(0)) {
9333       if (Opcode == ISD::FSUB)
9334         return false;
9335 
9336       // FADD is commutable. Try to commute the operands
9337       // and then test again.
9338       std::swap(Op0, Op1);
9339       if (InVec0 != Op0.getOperand(0))
9340         return false;
9341     }
9342 
9343     if (InVec1 != Op1.getOperand(0))
9344       return false;
9345 
9346     // Increment the number of extractions done.
9347     ++NumExtracts;
9348   }
9349 
9350   // Ensure we have found an opcode for both parities and that they are
9351   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
9352   // inputs are undef.
9353   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
9354       InVec0.isUndef() || InVec1.isUndef())
9355     return false;
9356 
9357   IsSubAdd = Opc[0] == ISD::FADD;
9358 
9359   Opnd0 = InVec0;
9360   Opnd1 = InVec1;
9361   return true;
9362 }
9363 
9364 /// Returns true if is possible to fold MUL and an idiom that has already been
9365 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
9366 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
9367 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
9368 ///
9369 /// Prior to calling this function it should be known that there is some
9370 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
9371 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
9372 /// before replacement of such SDNode with ADDSUB operation. Thus the number
9373 /// of \p Opnd0 uses is expected to be equal to 2.
9374 /// For example, this function may be called for the following IR:
9375 ///    %AB = fmul fast <2 x double> %A, %B
9376 ///    %Sub = fsub fast <2 x double> %AB, %C
9377 ///    %Add = fadd fast <2 x double> %AB, %C
9378 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
9379 ///                            <2 x i32> <i32 0, i32 3>
9380 /// There is a def for %Addsub here, which potentially can be replaced by
9381 /// X86ISD::ADDSUB operation:
9382 ///    %Addsub = X86ISD::ADDSUB %AB, %C
9383 /// and such ADDSUB can further be replaced with FMADDSUB:
9384 ///    %Addsub = FMADDSUB %A, %B, %C.
9385 ///
9386 /// The main reason why this method is called before the replacement of the
9387 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
9388 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
9389 /// FMADDSUB is.
isFMAddSubOrFMSubAdd(const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,SDValue & Opnd2,unsigned ExpectedUses)9390 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
9391                                  SelectionDAG &DAG,
9392                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
9393                                  unsigned ExpectedUses) {
9394   if (Opnd0.getOpcode() != ISD::FMUL ||
9395       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
9396     return false;
9397 
9398   // FIXME: These checks must match the similar ones in
9399   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
9400   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
9401   // or MUL + ADDSUB to FMADDSUB.
9402   const TargetOptions &Options = DAG.getTarget().Options;
9403   bool AllowFusion =
9404       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
9405   if (!AllowFusion)
9406     return false;
9407 
9408   Opnd2 = Opnd1;
9409   Opnd1 = Opnd0.getOperand(1);
9410   Opnd0 = Opnd0.getOperand(0);
9411 
9412   return true;
9413 }
9414 
9415 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
9416 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
9417 /// X86ISD::FMSUBADD node.
lowerToAddSubOrFMAddSub(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)9418 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
9419                                        const X86Subtarget &Subtarget,
9420                                        SelectionDAG &DAG) {
9421   SDValue Opnd0, Opnd1;
9422   unsigned NumExtracts;
9423   bool IsSubAdd;
9424   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
9425                         IsSubAdd))
9426     return SDValue();
9427 
9428   MVT VT = BV->getSimpleValueType(0);
9429   SDLoc DL(BV);
9430 
9431   // Try to generate X86ISD::FMADDSUB node here.
9432   SDValue Opnd2;
9433   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
9434     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
9435     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
9436   }
9437 
9438   // We only support ADDSUB.
9439   if (IsSubAdd)
9440     return SDValue();
9441 
9442   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
9443   // the ADDSUB idiom has been successfully recognized. There are no known
9444   // X86 targets with 512-bit ADDSUB instructions!
9445   // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
9446   // recognition.
9447   if (VT.is512BitVector())
9448     return SDValue();
9449 
9450   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
9451 }
9452 
isHopBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned & HOpcode,SDValue & V0,SDValue & V1)9453 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
9454                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
9455   // Initialize outputs to known values.
9456   MVT VT = BV->getSimpleValueType(0);
9457   HOpcode = ISD::DELETED_NODE;
9458   V0 = DAG.getUNDEF(VT);
9459   V1 = DAG.getUNDEF(VT);
9460 
9461   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
9462   // half of the result is calculated independently from the 128-bit halves of
9463   // the inputs, so that makes the index-checking logic below more complicated.
9464   unsigned NumElts = VT.getVectorNumElements();
9465   unsigned GenericOpcode = ISD::DELETED_NODE;
9466   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
9467   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
9468   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
9469   for (unsigned i = 0; i != Num128BitChunks; ++i) {
9470     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
9471       // Ignore undef elements.
9472       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
9473       if (Op.isUndef())
9474         continue;
9475 
9476       // If there's an opcode mismatch, we're done.
9477       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
9478         return false;
9479 
9480       // Initialize horizontal opcode.
9481       if (HOpcode == ISD::DELETED_NODE) {
9482         GenericOpcode = Op.getOpcode();
9483         switch (GenericOpcode) {
9484         case ISD::ADD: HOpcode = X86ISD::HADD; break;
9485         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
9486         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
9487         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
9488         default: return false;
9489         }
9490       }
9491 
9492       SDValue Op0 = Op.getOperand(0);
9493       SDValue Op1 = Op.getOperand(1);
9494       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9495           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9496           Op0.getOperand(0) != Op1.getOperand(0) ||
9497           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9498           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
9499         return false;
9500 
9501       // The source vector is chosen based on which 64-bit half of the
9502       // destination vector is being calculated.
9503       if (j < NumEltsIn64Bits) {
9504         if (V0.isUndef())
9505           V0 = Op0.getOperand(0);
9506       } else {
9507         if (V1.isUndef())
9508           V1 = Op0.getOperand(0);
9509       }
9510 
9511       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
9512       if (SourceVec != Op0.getOperand(0))
9513         return false;
9514 
9515       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
9516       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
9517       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
9518       unsigned ExpectedIndex = i * NumEltsIn128Bits +
9519                                (j % NumEltsIn64Bits) * 2;
9520       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
9521         continue;
9522 
9523       // If this is not a commutative op, this does not match.
9524       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
9525         return false;
9526 
9527       // Addition is commutative, so try swapping the extract indexes.
9528       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
9529       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
9530         continue;
9531 
9532       // Extract indexes do not match horizontal requirement.
9533       return false;
9534     }
9535   }
9536   // We matched. Opcode and operands are returned by reference as arguments.
9537   return true;
9538 }
9539 
getHopForBuildVector(const BuildVectorSDNode * BV,SelectionDAG & DAG,unsigned HOpcode,SDValue V0,SDValue V1)9540 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
9541                                     SelectionDAG &DAG, unsigned HOpcode,
9542                                     SDValue V0, SDValue V1) {
9543   // If either input vector is not the same size as the build vector,
9544   // extract/insert the low bits to the correct size.
9545   // This is free (examples: zmm --> xmm, xmm --> ymm).
9546   MVT VT = BV->getSimpleValueType(0);
9547   unsigned Width = VT.getSizeInBits();
9548   if (V0.getValueSizeInBits() > Width)
9549     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
9550   else if (V0.getValueSizeInBits() < Width)
9551     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
9552 
9553   if (V1.getValueSizeInBits() > Width)
9554     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
9555   else if (V1.getValueSizeInBits() < Width)
9556     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
9557 
9558   unsigned NumElts = VT.getVectorNumElements();
9559   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
9560   for (unsigned i = 0; i != NumElts; ++i)
9561     if (BV->getOperand(i).isUndef())
9562       DemandedElts.clearBit(i);
9563 
9564   // If we don't need the upper xmm, then perform as a xmm hop.
9565   unsigned HalfNumElts = NumElts / 2;
9566   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
9567     MVT HalfVT = VT.getHalfNumVectorElementsVT();
9568     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
9569     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
9570     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
9571     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
9572   }
9573 
9574   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
9575 }
9576 
9577 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
LowerToHorizontalOp(const BuildVectorSDNode * BV,const X86Subtarget & Subtarget,SelectionDAG & DAG)9578 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
9579                                    const X86Subtarget &Subtarget,
9580                                    SelectionDAG &DAG) {
9581   // We need at least 2 non-undef elements to make this worthwhile by default.
9582   unsigned NumNonUndefs =
9583       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
9584   if (NumNonUndefs < 2)
9585     return SDValue();
9586 
9587   // There are 4 sets of horizontal math operations distinguished by type:
9588   // int/FP at 128-bit/256-bit. Each type was introduced with a different
9589   // subtarget feature. Try to match those "native" patterns first.
9590   MVT VT = BV->getSimpleValueType(0);
9591   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
9592       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
9593       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
9594       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
9595     unsigned HOpcode;
9596     SDValue V0, V1;
9597     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
9598       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
9599   }
9600 
9601   // Try harder to match 256-bit ops by using extract/concat.
9602   if (!Subtarget.hasAVX() || !VT.is256BitVector())
9603     return SDValue();
9604 
9605   // Count the number of UNDEF operands in the build_vector in input.
9606   unsigned NumElts = VT.getVectorNumElements();
9607   unsigned Half = NumElts / 2;
9608   unsigned NumUndefsLO = 0;
9609   unsigned NumUndefsHI = 0;
9610   for (unsigned i = 0, e = Half; i != e; ++i)
9611     if (BV->getOperand(i)->isUndef())
9612       NumUndefsLO++;
9613 
9614   for (unsigned i = Half, e = NumElts; i != e; ++i)
9615     if (BV->getOperand(i)->isUndef())
9616       NumUndefsHI++;
9617 
9618   SDLoc DL(BV);
9619   SDValue InVec0, InVec1;
9620   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
9621     SDValue InVec2, InVec3;
9622     unsigned X86Opcode;
9623     bool CanFold = true;
9624 
9625     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
9626         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
9627                               InVec3) &&
9628         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9629         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9630       X86Opcode = X86ISD::HADD;
9631     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
9632                                    InVec1) &&
9633              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
9634                                    InVec3) &&
9635              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9636              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9637       X86Opcode = X86ISD::HSUB;
9638     else
9639       CanFold = false;
9640 
9641     if (CanFold) {
9642       // Do not try to expand this build_vector into a pair of horizontal
9643       // add/sub if we can emit a pair of scalar add/sub.
9644       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9645         return SDValue();
9646 
9647       // Convert this build_vector into a pair of horizontal binops followed by
9648       // a concat vector. We must adjust the outputs from the partial horizontal
9649       // matching calls above to account for undefined vector halves.
9650       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
9651       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
9652       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
9653       bool isUndefLO = NumUndefsLO == Half;
9654       bool isUndefHI = NumUndefsHI == Half;
9655       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
9656                                    isUndefHI);
9657     }
9658   }
9659 
9660   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
9661       VT == MVT::v16i16) {
9662     unsigned X86Opcode;
9663     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
9664       X86Opcode = X86ISD::HADD;
9665     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
9666                                    InVec1))
9667       X86Opcode = X86ISD::HSUB;
9668     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
9669                                    InVec1))
9670       X86Opcode = X86ISD::FHADD;
9671     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
9672                                    InVec1))
9673       X86Opcode = X86ISD::FHSUB;
9674     else
9675       return SDValue();
9676 
9677     // Don't try to expand this build_vector into a pair of horizontal add/sub
9678     // if we can simply emit a pair of scalar add/sub.
9679     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9680       return SDValue();
9681 
9682     // Convert this build_vector into two horizontal add/sub followed by
9683     // a concat vector.
9684     bool isUndefLO = NumUndefsLO == Half;
9685     bool isUndefHI = NumUndefsHI == Half;
9686     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
9687                                  isUndefLO, isUndefHI);
9688   }
9689 
9690   return SDValue();
9691 }
9692 
9693 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
9694                           SelectionDAG &DAG);
9695 
9696 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
9697 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
9698 /// just apply the bit to the vectors.
9699 /// NOTE: Its not in our interest to start make a general purpose vectorizer
9700 /// from this, but enough scalar bit operations are created from the later
9701 /// legalization + scalarization stages to need basic support.
lowerBuildVectorToBitOp(BuildVectorSDNode * Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)9702 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
9703                                        const X86Subtarget &Subtarget,
9704                                        SelectionDAG &DAG) {
9705   SDLoc DL(Op);
9706   MVT VT = Op->getSimpleValueType(0);
9707   unsigned NumElems = VT.getVectorNumElements();
9708   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9709 
9710   // Check that all elements have the same opcode.
9711   // TODO: Should we allow UNDEFS and if so how many?
9712   unsigned Opcode = Op->getOperand(0).getOpcode();
9713   for (unsigned i = 1; i < NumElems; ++i)
9714     if (Opcode != Op->getOperand(i).getOpcode())
9715       return SDValue();
9716 
9717   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
9718   bool IsShift = false;
9719   switch (Opcode) {
9720   default:
9721     return SDValue();
9722   case ISD::SHL:
9723   case ISD::SRL:
9724   case ISD::SRA:
9725     IsShift = true;
9726     break;
9727   case ISD::AND:
9728   case ISD::XOR:
9729   case ISD::OR:
9730     // Don't do this if the buildvector is a splat - we'd replace one
9731     // constant with an entire vector.
9732     if (Op->getSplatValue())
9733       return SDValue();
9734     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
9735       return SDValue();
9736     break;
9737   }
9738 
9739   SmallVector<SDValue, 4> LHSElts, RHSElts;
9740   for (SDValue Elt : Op->ops()) {
9741     SDValue LHS = Elt.getOperand(0);
9742     SDValue RHS = Elt.getOperand(1);
9743 
9744     // We expect the canonicalized RHS operand to be the constant.
9745     if (!isa<ConstantSDNode>(RHS))
9746       return SDValue();
9747 
9748     // Extend shift amounts.
9749     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
9750       if (!IsShift)
9751         return SDValue();
9752       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
9753     }
9754 
9755     LHSElts.push_back(LHS);
9756     RHSElts.push_back(RHS);
9757   }
9758 
9759   // Limit to shifts by uniform immediates.
9760   // TODO: Only accept vXi8/vXi64 special cases?
9761   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
9762   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
9763     return SDValue();
9764 
9765   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
9766   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
9767   SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
9768 
9769   if (!IsShift)
9770     return Res;
9771 
9772   // Immediately lower the shift to ensure the constant build vector doesn't
9773   // get converted to a constant pool before the shift is lowered.
9774   return LowerShift(Res, Subtarget, DAG);
9775 }
9776 
9777 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
9778 /// functionality to do this, so it's all zeros, all ones, or some derivation
9779 /// that is cheap to calculate.
materializeVectorConstant(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)9780 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
9781                                          const X86Subtarget &Subtarget) {
9782   SDLoc DL(Op);
9783   MVT VT = Op.getSimpleValueType();
9784 
9785   // Vectors containing all zeros can be matched by pxor and xorps.
9786   if (ISD::isBuildVectorAllZeros(Op.getNode()))
9787     return Op;
9788 
9789   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9790   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9791   // vpcmpeqd on 256-bit vectors.
9792   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9793     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9794       return Op;
9795 
9796     return getOnesVector(VT, DAG, DL);
9797   }
9798 
9799   return SDValue();
9800 }
9801 
9802 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
9803 /// from a vector of source values and a vector of extraction indices.
9804 /// 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)9805 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
9806                                      SDLoc &DL, SelectionDAG &DAG,
9807                                      const X86Subtarget &Subtarget) {
9808   MVT ShuffleVT = VT;
9809   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9810   unsigned NumElts = VT.getVectorNumElements();
9811   unsigned SizeInBits = VT.getSizeInBits();
9812 
9813   // Adjust IndicesVec to match VT size.
9814   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
9815          "Illegal variable permute mask size");
9816   if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
9817     IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
9818                                   NumElts * VT.getScalarSizeInBits());
9819   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
9820 
9821   // Handle SrcVec that don't match VT type.
9822   if (SrcVec.getValueSizeInBits() != SizeInBits) {
9823     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
9824       // Handle larger SrcVec by treating it as a larger permute.
9825       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
9826       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
9827       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9828       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
9829                                   Subtarget, DAG, SDLoc(IndicesVec));
9830       SDValue NewSrcVec =
9831           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9832       if (NewSrcVec)
9833         return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
9834       return SDValue();
9835     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
9836       // Widen smaller SrcVec to match VT.
9837       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
9838     } else
9839       return SDValue();
9840   }
9841 
9842   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
9843     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
9844     EVT SrcVT = Idx.getValueType();
9845     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
9846     uint64_t IndexScale = 0;
9847     uint64_t IndexOffset = 0;
9848 
9849     // If we're scaling a smaller permute op, then we need to repeat the
9850     // indices, scaling and offsetting them as well.
9851     // e.g. v4i32 -> v16i8 (Scale = 4)
9852     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
9853     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
9854     for (uint64_t i = 0; i != Scale; ++i) {
9855       IndexScale |= Scale << (i * NumDstBits);
9856       IndexOffset |= i << (i * NumDstBits);
9857     }
9858 
9859     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
9860                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
9861     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
9862                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
9863     return Idx;
9864   };
9865 
9866   unsigned Opcode = 0;
9867   switch (VT.SimpleTy) {
9868   default:
9869     break;
9870   case MVT::v16i8:
9871     if (Subtarget.hasSSSE3())
9872       Opcode = X86ISD::PSHUFB;
9873     break;
9874   case MVT::v8i16:
9875     if (Subtarget.hasVLX() && Subtarget.hasBWI())
9876       Opcode = X86ISD::VPERMV;
9877     else if (Subtarget.hasSSSE3()) {
9878       Opcode = X86ISD::PSHUFB;
9879       ShuffleVT = MVT::v16i8;
9880     }
9881     break;
9882   case MVT::v4f32:
9883   case MVT::v4i32:
9884     if (Subtarget.hasAVX()) {
9885       Opcode = X86ISD::VPERMILPV;
9886       ShuffleVT = MVT::v4f32;
9887     } else if (Subtarget.hasSSSE3()) {
9888       Opcode = X86ISD::PSHUFB;
9889       ShuffleVT = MVT::v16i8;
9890     }
9891     break;
9892   case MVT::v2f64:
9893   case MVT::v2i64:
9894     if (Subtarget.hasAVX()) {
9895       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
9896       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9897       Opcode = X86ISD::VPERMILPV;
9898       ShuffleVT = MVT::v2f64;
9899     } else if (Subtarget.hasSSE41()) {
9900       // SSE41 can compare v2i64 - select between indices 0 and 1.
9901       return DAG.getSelectCC(
9902           DL, IndicesVec,
9903           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
9904           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
9905           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
9906           ISD::CondCode::SETEQ);
9907     }
9908     break;
9909   case MVT::v32i8:
9910     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
9911       Opcode = X86ISD::VPERMV;
9912     else if (Subtarget.hasXOP()) {
9913       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
9914       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
9915       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
9916       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
9917       return DAG.getNode(
9918           ISD::CONCAT_VECTORS, DL, VT,
9919           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
9920           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
9921     } else if (Subtarget.hasAVX()) {
9922       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
9923       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
9924       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
9925       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
9926       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
9927                               ArrayRef<SDValue> Ops) {
9928         // Permute Lo and Hi and then select based on index range.
9929         // This works as SHUFB uses bits[3:0] to permute elements and we don't
9930         // care about the bit[7] as its just an index vector.
9931         SDValue Idx = Ops[2];
9932         EVT VT = Idx.getValueType();
9933         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
9934                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
9935                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
9936                                ISD::CondCode::SETGT);
9937       };
9938       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
9939       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
9940                               PSHUFBBuilder);
9941     }
9942     break;
9943   case MVT::v16i16:
9944     if (Subtarget.hasVLX() && Subtarget.hasBWI())
9945       Opcode = X86ISD::VPERMV;
9946     else if (Subtarget.hasAVX()) {
9947       // Scale to v32i8 and perform as v32i8.
9948       IndicesVec = ScaleIndices(IndicesVec, 2);
9949       return DAG.getBitcast(
9950           VT, createVariablePermute(
9951                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
9952                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
9953     }
9954     break;
9955   case MVT::v8f32:
9956   case MVT::v8i32:
9957     if (Subtarget.hasAVX2())
9958       Opcode = X86ISD::VPERMV;
9959     else if (Subtarget.hasAVX()) {
9960       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
9961       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9962                                           {0, 1, 2, 3, 0, 1, 2, 3});
9963       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
9964                                           {4, 5, 6, 7, 4, 5, 6, 7});
9965       if (Subtarget.hasXOP())
9966         return DAG.getBitcast(
9967             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
9968                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
9969       // Permute Lo and Hi and then select based on index range.
9970       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
9971       SDValue Res = DAG.getSelectCC(
9972           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
9973           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
9974           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
9975           ISD::CondCode::SETGT);
9976       return DAG.getBitcast(VT, Res);
9977     }
9978     break;
9979   case MVT::v4i64:
9980   case MVT::v4f64:
9981     if (Subtarget.hasAVX512()) {
9982       if (!Subtarget.hasVLX()) {
9983         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
9984         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
9985                                 SDLoc(SrcVec));
9986         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
9987                                     DAG, SDLoc(IndicesVec));
9988         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
9989                                             DAG, Subtarget);
9990         return extract256BitVector(Res, 0, DAG, DL);
9991       }
9992       Opcode = X86ISD::VPERMV;
9993     } else if (Subtarget.hasAVX()) {
9994       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
9995       SDValue LoLo =
9996           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
9997       SDValue HiHi =
9998           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
9999       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
10000       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10001       if (Subtarget.hasXOP())
10002         return DAG.getBitcast(
10003             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
10004                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10005       // Permute Lo and Hi and then select based on index range.
10006       // This works as VPERMILPD only uses index bit[1] to permute elements.
10007       SDValue Res = DAG.getSelectCC(
10008           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
10009           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
10010           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
10011           ISD::CondCode::SETGT);
10012       return DAG.getBitcast(VT, Res);
10013     }
10014     break;
10015   case MVT::v64i8:
10016     if (Subtarget.hasVBMI())
10017       Opcode = X86ISD::VPERMV;
10018     break;
10019   case MVT::v32i16:
10020     if (Subtarget.hasBWI())
10021       Opcode = X86ISD::VPERMV;
10022     break;
10023   case MVT::v16f32:
10024   case MVT::v16i32:
10025   case MVT::v8f64:
10026   case MVT::v8i64:
10027     if (Subtarget.hasAVX512())
10028       Opcode = X86ISD::VPERMV;
10029     break;
10030   }
10031   if (!Opcode)
10032     return SDValue();
10033 
10034   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
10035          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
10036          "Illegal variable permute shuffle type");
10037 
10038   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
10039   if (Scale > 1)
10040     IndicesVec = ScaleIndices(IndicesVec, Scale);
10041 
10042   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
10043   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
10044 
10045   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
10046   SDValue Res = Opcode == X86ISD::VPERMV
10047                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
10048                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
10049   return DAG.getBitcast(VT, Res);
10050 }
10051 
10052 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
10053 // reasoned to be a permutation of a vector by indices in a non-constant vector.
10054 // (build_vector (extract_elt V, (extract_elt I, 0)),
10055 //               (extract_elt V, (extract_elt I, 1)),
10056 //                    ...
10057 // ->
10058 // (vpermv I, V)
10059 //
10060 // TODO: Handle undefs
10061 // TODO: Utilize pshufb and zero mask blending to support more efficient
10062 // construction of vectors with constant-0 elements.
10063 static SDValue
LowerBUILD_VECTORAsVariablePermute(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)10064 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
10065                                    const X86Subtarget &Subtarget) {
10066   SDValue SrcVec, IndicesVec;
10067   // Check for a match of the permute source vector and permute index elements.
10068   // This is done by checking that the i-th build_vector operand is of the form:
10069   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
10070   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
10071     SDValue Op = V.getOperand(Idx);
10072     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10073       return SDValue();
10074 
10075     // If this is the first extract encountered in V, set the source vector,
10076     // otherwise verify the extract is from the previously defined source
10077     // vector.
10078     if (!SrcVec)
10079       SrcVec = Op.getOperand(0);
10080     else if (SrcVec != Op.getOperand(0))
10081       return SDValue();
10082     SDValue ExtractedIndex = Op->getOperand(1);
10083     // Peek through extends.
10084     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
10085         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
10086       ExtractedIndex = ExtractedIndex.getOperand(0);
10087     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10088       return SDValue();
10089 
10090     // If this is the first extract from the index vector candidate, set the
10091     // indices vector, otherwise verify the extract is from the previously
10092     // defined indices vector.
10093     if (!IndicesVec)
10094       IndicesVec = ExtractedIndex.getOperand(0);
10095     else if (IndicesVec != ExtractedIndex.getOperand(0))
10096       return SDValue();
10097 
10098     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
10099     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
10100       return SDValue();
10101   }
10102 
10103   SDLoc DL(V);
10104   MVT VT = V.getSimpleValueType();
10105   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10106 }
10107 
10108 SDValue
LowerBUILD_VECTOR(SDValue Op,SelectionDAG & DAG) const10109 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
10110   SDLoc dl(Op);
10111 
10112   MVT VT = Op.getSimpleValueType();
10113   MVT EltVT = VT.getVectorElementType();
10114   unsigned NumElems = Op.getNumOperands();
10115 
10116   // Generate vectors for predicate vectors.
10117   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
10118     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
10119 
10120   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
10121     return VectorConstant;
10122 
10123   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
10124   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
10125     return AddSub;
10126   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
10127     return HorizontalOp;
10128   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
10129     return Broadcast;
10130   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
10131     return BitOp;
10132 
10133   unsigned EVTBits = EltVT.getSizeInBits();
10134 
10135   unsigned NumZero  = 0;
10136   unsigned NumNonZero = 0;
10137   uint64_t NonZeros = 0;
10138   bool IsAllConstants = true;
10139   SmallSet<SDValue, 8> Values;
10140   unsigned NumConstants = NumElems;
10141   for (unsigned i = 0; i < NumElems; ++i) {
10142     SDValue Elt = Op.getOperand(i);
10143     if (Elt.isUndef())
10144       continue;
10145     Values.insert(Elt);
10146     if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
10147       IsAllConstants = false;
10148       NumConstants--;
10149     }
10150     if (X86::isZeroNode(Elt))
10151       NumZero++;
10152     else {
10153       assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
10154       NonZeros |= ((uint64_t)1 << i);
10155       NumNonZero++;
10156     }
10157   }
10158 
10159   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
10160   if (NumNonZero == 0)
10161     return DAG.getUNDEF(VT);
10162 
10163   // If we are inserting one variable into a vector of non-zero constants, try
10164   // to avoid loading each constant element as a scalar. Load the constants as a
10165   // vector and then insert the variable scalar element. If insertion is not
10166   // supported, fall back to a shuffle to get the scalar blended with the
10167   // constants. Insertion into a zero vector is handled as a special-case
10168   // somewhere below here.
10169   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
10170       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
10171        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
10172     // Create an all-constant vector. The variable element in the old
10173     // build vector is replaced by undef in the constant vector. Save the
10174     // variable scalar element and its index for use in the insertelement.
10175     LLVMContext &Context = *DAG.getContext();
10176     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
10177     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
10178     SDValue VarElt;
10179     SDValue InsIndex;
10180     for (unsigned i = 0; i != NumElems; ++i) {
10181       SDValue Elt = Op.getOperand(i);
10182       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
10183         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
10184       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
10185         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
10186       else if (!Elt.isUndef()) {
10187         assert(!VarElt.getNode() && !InsIndex.getNode() &&
10188                "Expected one variable element in this vector");
10189         VarElt = Elt;
10190         InsIndex = DAG.getVectorIdxConstant(i, dl);
10191       }
10192     }
10193     Constant *CV = ConstantVector::get(ConstVecOps);
10194     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
10195 
10196     // The constants we just created may not be legal (eg, floating point). We
10197     // must lower the vector right here because we can not guarantee that we'll
10198     // legalize it before loading it. This is also why we could not just create
10199     // a new build vector here. If the build vector contains illegal constants,
10200     // it could get split back up into a series of insert elements.
10201     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
10202     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
10203     MachineFunction &MF = DAG.getMachineFunction();
10204     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
10205     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
10206     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
10207     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
10208     if (InsertC < NumEltsInLow128Bits)
10209       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
10210 
10211     // There's no good way to insert into the high elements of a >128-bit
10212     // vector, so use shuffles to avoid an extract/insert sequence.
10213     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
10214     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
10215     SmallVector<int, 8> ShuffleMask;
10216     unsigned NumElts = VT.getVectorNumElements();
10217     for (unsigned i = 0; i != NumElts; ++i)
10218       ShuffleMask.push_back(i == InsertC ? NumElts : i);
10219     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
10220     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
10221   }
10222 
10223   // Special case for single non-zero, non-undef, element.
10224   if (NumNonZero == 1) {
10225     unsigned Idx = countTrailingZeros(NonZeros);
10226     SDValue Item = Op.getOperand(Idx);
10227 
10228     // If we have a constant or non-constant insertion into the low element of
10229     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
10230     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
10231     // depending on what the source datatype is.
10232     if (Idx == 0) {
10233       if (NumZero == 0)
10234         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10235 
10236       if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
10237           (EltVT == MVT::i64 && Subtarget.is64Bit())) {
10238         assert((VT.is128BitVector() || VT.is256BitVector() ||
10239                 VT.is512BitVector()) &&
10240                "Expected an SSE value type!");
10241         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10242         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
10243         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10244       }
10245 
10246       // We can't directly insert an i8 or i16 into a vector, so zero extend
10247       // it to i32 first.
10248       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
10249         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
10250         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
10251         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
10252         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10253         return DAG.getBitcast(VT, Item);
10254       }
10255     }
10256 
10257     // Is it a vector logical left shift?
10258     if (NumElems == 2 && Idx == 1 &&
10259         X86::isZeroNode(Op.getOperand(0)) &&
10260         !X86::isZeroNode(Op.getOperand(1))) {
10261       unsigned NumBits = VT.getSizeInBits();
10262       return getVShift(true, VT,
10263                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10264                                    VT, Op.getOperand(1)),
10265                        NumBits/2, DAG, *this, dl);
10266     }
10267 
10268     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
10269       return SDValue();
10270 
10271     // Otherwise, if this is a vector with i32 or f32 elements, and the element
10272     // is a non-constant being inserted into an element other than the low one,
10273     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
10274     // movd/movss) to move this into the low element, then shuffle it into
10275     // place.
10276     if (EVTBits == 32) {
10277       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10278       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
10279     }
10280   }
10281 
10282   // Splat is obviously ok. Let legalizer expand it to a shuffle.
10283   if (Values.size() == 1) {
10284     if (EVTBits == 32) {
10285       // Instead of a shuffle like this:
10286       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
10287       // Check if it's possible to issue this instead.
10288       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
10289       unsigned Idx = countTrailingZeros(NonZeros);
10290       SDValue Item = Op.getOperand(Idx);
10291       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
10292         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
10293     }
10294     return SDValue();
10295   }
10296 
10297   // A vector full of immediates; various special cases are already
10298   // handled, so this is best done with a single constant-pool load.
10299   if (IsAllConstants)
10300     return SDValue();
10301 
10302   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
10303       return V;
10304 
10305   // See if we can use a vector load to get all of the elements.
10306   {
10307     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
10308     if (SDValue LD =
10309             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
10310       return LD;
10311   }
10312 
10313   // If this is a splat of pairs of 32-bit elements, we can use a narrower
10314   // build_vector and broadcast it.
10315   // TODO: We could probably generalize this more.
10316   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
10317     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
10318                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
10319     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
10320       // Make sure all the even/odd operands match.
10321       for (unsigned i = 2; i != NumElems; ++i)
10322         if (Ops[i % 2] != Op.getOperand(i))
10323           return false;
10324       return true;
10325     };
10326     if (CanSplat(Op, NumElems, Ops)) {
10327       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
10328       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
10329       // Create a new build vector and cast to v2i64/v2f64.
10330       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
10331                                      DAG.getBuildVector(NarrowVT, dl, Ops));
10332       // Broadcast from v2i64/v2f64 and cast to final VT.
10333       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems/2);
10334       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
10335                                             NewBV));
10336     }
10337   }
10338 
10339   // For AVX-length vectors, build the individual 128-bit pieces and use
10340   // shuffles to put them in place.
10341   if (VT.getSizeInBits() > 128) {
10342     MVT HVT = MVT::getVectorVT(EltVT, NumElems/2);
10343 
10344     // Build both the lower and upper subvector.
10345     SDValue Lower =
10346         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
10347     SDValue Upper = DAG.getBuildVector(
10348         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
10349 
10350     // Recreate the wider vector with the lower and upper part.
10351     return concatSubVectors(Lower, Upper, DAG, dl);
10352   }
10353 
10354   // Let legalizer expand 2-wide build_vectors.
10355   if (EVTBits == 64) {
10356     if (NumNonZero == 1) {
10357       // One half is zero or undef.
10358       unsigned Idx = countTrailingZeros(NonZeros);
10359       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
10360                                Op.getOperand(Idx));
10361       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
10362     }
10363     return SDValue();
10364   }
10365 
10366   // If element VT is < 32 bits, convert it to inserts into a zero vector.
10367   if (EVTBits == 8 && NumElems == 16)
10368     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
10369                                           DAG, Subtarget))
10370       return V;
10371 
10372   if (EVTBits == 16 && NumElems == 8)
10373     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
10374                                           DAG, Subtarget))
10375       return V;
10376 
10377   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
10378   if (EVTBits == 32 && NumElems == 4)
10379     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
10380       return V;
10381 
10382   // If element VT is == 32 bits, turn it into a number of shuffles.
10383   if (NumElems == 4 && NumZero > 0) {
10384     SmallVector<SDValue, 8> Ops(NumElems);
10385     for (unsigned i = 0; i < 4; ++i) {
10386       bool isZero = !(NonZeros & (1ULL << i));
10387       if (isZero)
10388         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
10389       else
10390         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10391     }
10392 
10393     for (unsigned i = 0; i < 2; ++i) {
10394       switch ((NonZeros >> (i*2)) & 0x3) {
10395         default: llvm_unreachable("Unexpected NonZero count");
10396         case 0:
10397           Ops[i] = Ops[i*2];  // Must be a zero vector.
10398           break;
10399         case 1:
10400           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
10401           break;
10402         case 2:
10403           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10404           break;
10405         case 3:
10406           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10407           break;
10408       }
10409     }
10410 
10411     bool Reverse1 = (NonZeros & 0x3) == 2;
10412     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
10413     int MaskVec[] = {
10414       Reverse1 ? 1 : 0,
10415       Reverse1 ? 0 : 1,
10416       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
10417       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
10418     };
10419     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
10420   }
10421 
10422   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
10423 
10424   // Check for a build vector from mostly shuffle plus few inserting.
10425   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
10426     return Sh;
10427 
10428   // For SSE 4.1, use insertps to put the high elements into the low element.
10429   if (Subtarget.hasSSE41()) {
10430     SDValue Result;
10431     if (!Op.getOperand(0).isUndef())
10432       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
10433     else
10434       Result = DAG.getUNDEF(VT);
10435 
10436     for (unsigned i = 1; i < NumElems; ++i) {
10437       if (Op.getOperand(i).isUndef()) continue;
10438       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
10439                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
10440     }
10441     return Result;
10442   }
10443 
10444   // Otherwise, expand into a number of unpckl*, start by extending each of
10445   // our (non-undef) elements to the full vector width with the element in the
10446   // bottom slot of the vector (which generates no code for SSE).
10447   SmallVector<SDValue, 8> Ops(NumElems);
10448   for (unsigned i = 0; i < NumElems; ++i) {
10449     if (!Op.getOperand(i).isUndef())
10450       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10451     else
10452       Ops[i] = DAG.getUNDEF(VT);
10453   }
10454 
10455   // Next, we iteratively mix elements, e.g. for v4f32:
10456   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
10457   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
10458   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
10459   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
10460     // Generate scaled UNPCKL shuffle mask.
10461     SmallVector<int, 16> Mask;
10462     for(unsigned i = 0; i != Scale; ++i)
10463       Mask.push_back(i);
10464     for (unsigned i = 0; i != Scale; ++i)
10465       Mask.push_back(NumElems+i);
10466     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
10467 
10468     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
10469       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
10470   }
10471   return Ops[0];
10472 }
10473 
10474 // 256-bit AVX can use the vinsertf128 instruction
10475 // to create 256-bit vectors from two other 128-bit ones.
10476 // TODO: Detect subvector broadcast here instead of DAG combine?
LowerAVXCONCAT_VECTORS(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)10477 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
10478                                       const X86Subtarget &Subtarget) {
10479   SDLoc dl(Op);
10480   MVT ResVT = Op.getSimpleValueType();
10481 
10482   assert((ResVT.is256BitVector() ||
10483           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
10484 
10485   unsigned NumOperands = Op.getNumOperands();
10486   unsigned NumZero = 0;
10487   unsigned NumNonZero = 0;
10488   unsigned NonZeros = 0;
10489   for (unsigned i = 0; i != NumOperands; ++i) {
10490     SDValue SubVec = Op.getOperand(i);
10491     if (SubVec.isUndef())
10492       continue;
10493     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10494       ++NumZero;
10495     else {
10496       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10497       NonZeros |= 1 << i;
10498       ++NumNonZero;
10499     }
10500   }
10501 
10502   // If we have more than 2 non-zeros, build each half separately.
10503   if (NumNonZero > 2) {
10504     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10505     ArrayRef<SDUse> Ops = Op->ops();
10506     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10507                              Ops.slice(0, NumOperands/2));
10508     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10509                              Ops.slice(NumOperands/2));
10510     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10511   }
10512 
10513   // Otherwise, build it up through insert_subvectors.
10514   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
10515                         : DAG.getUNDEF(ResVT);
10516 
10517   MVT SubVT = Op.getOperand(0).getSimpleValueType();
10518   unsigned NumSubElems = SubVT.getVectorNumElements();
10519   for (unsigned i = 0; i != NumOperands; ++i) {
10520     if ((NonZeros & (1 << i)) == 0)
10521       continue;
10522 
10523     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
10524                       Op.getOperand(i),
10525                       DAG.getIntPtrConstant(i * NumSubElems, dl));
10526   }
10527 
10528   return Vec;
10529 }
10530 
10531 // Returns true if the given node is a type promotion (by concatenating i1
10532 // zeros) of the result of a node that already zeros all upper bits of
10533 // k-register.
10534 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
LowerCONCAT_VECTORSvXi1(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)10535 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
10536                                        const X86Subtarget &Subtarget,
10537                                        SelectionDAG & DAG) {
10538   SDLoc dl(Op);
10539   MVT ResVT = Op.getSimpleValueType();
10540   unsigned NumOperands = Op.getNumOperands();
10541 
10542   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
10543          "Unexpected number of operands in CONCAT_VECTORS");
10544 
10545   uint64_t Zeros = 0;
10546   uint64_t NonZeros = 0;
10547   for (unsigned i = 0; i != NumOperands; ++i) {
10548     SDValue SubVec = Op.getOperand(i);
10549     if (SubVec.isUndef())
10550       continue;
10551     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10552     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10553       Zeros |= (uint64_t)1 << i;
10554     else
10555       NonZeros |= (uint64_t)1 << i;
10556   }
10557 
10558   unsigned NumElems = ResVT.getVectorNumElements();
10559 
10560   // If we are inserting non-zero vector and there are zeros in LSBs and undef
10561   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
10562   // insert_subvector will give us two kshifts.
10563   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
10564       Log2_64(NonZeros) != NumOperands - 1) {
10565     MVT ShiftVT = ResVT;
10566     if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
10567       ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
10568     unsigned Idx = Log2_64(NonZeros);
10569     SDValue SubVec = Op.getOperand(Idx);
10570     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10571     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
10572                          DAG.getUNDEF(ShiftVT), SubVec,
10573                          DAG.getIntPtrConstant(0, dl));
10574     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
10575                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10576     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10577                        DAG.getIntPtrConstant(0, dl));
10578   }
10579 
10580   // If there are zero or one non-zeros we can handle this very simply.
10581   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10582     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10583     if (!NonZeros)
10584       return Vec;
10585     unsigned Idx = Log2_64(NonZeros);
10586     SDValue SubVec = Op.getOperand(Idx);
10587     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10588     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10589                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
10590   }
10591 
10592   if (NumOperands > 2) {
10593     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10594     ArrayRef<SDUse> Ops = Op->ops();
10595     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10596                              Ops.slice(0, NumOperands/2));
10597     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10598                              Ops.slice(NumOperands/2));
10599     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10600   }
10601 
10602   assert(countPopulation(NonZeros) == 2 && "Simple cases not handled?");
10603 
10604   if (ResVT.getVectorNumElements() >= 16)
10605     return Op; // The operation is legal with KUNPCK
10606 
10607   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
10608                             DAG.getUNDEF(ResVT), Op.getOperand(0),
10609                             DAG.getIntPtrConstant(0, dl));
10610   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10611                      DAG.getIntPtrConstant(NumElems/2, dl));
10612 }
10613 
LowerCONCAT_VECTORS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)10614 static SDValue LowerCONCAT_VECTORS(SDValue Op,
10615                                    const X86Subtarget &Subtarget,
10616                                    SelectionDAG &DAG) {
10617   MVT VT = Op.getSimpleValueType();
10618   if (VT.getVectorElementType() == MVT::i1)
10619     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
10620 
10621   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
10622          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
10623           Op.getNumOperands() == 4)));
10624 
10625   // AVX can use the vinsertf128 instruction to create 256-bit vectors
10626   // from two other 128-bit ones.
10627 
10628   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10629   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
10630 }
10631 
10632 //===----------------------------------------------------------------------===//
10633 // Vector shuffle lowering
10634 //
10635 // This is an experimental code path for lowering vector shuffles on x86. It is
10636 // designed to handle arbitrary vector shuffles and blends, gracefully
10637 // degrading performance as necessary. It works hard to recognize idiomatic
10638 // shuffles and lower them to optimal instruction patterns without leaving
10639 // a framework that allows reasonably efficient handling of all vector shuffle
10640 // patterns.
10641 //===----------------------------------------------------------------------===//
10642 
10643 /// Tiny helper function to identify a no-op mask.
10644 ///
10645 /// This is a somewhat boring predicate function. It checks whether the mask
10646 /// array input, which is assumed to be a single-input shuffle mask of the kind
10647 /// used by the X86 shuffle instructions (not a fully general
10648 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10649 /// in-place shuffle are 'no-op's.
isNoopShuffleMask(ArrayRef<int> Mask)10650 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
10651   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10652     assert(Mask[i] >= -1 && "Out of bound mask element!");
10653     if (Mask[i] >= 0 && Mask[i] != i)
10654       return false;
10655   }
10656   return true;
10657 }
10658 
10659 /// Test whether there are elements crossing LaneSizeInBits lanes in this
10660 /// shuffle mask.
10661 ///
10662 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10663 /// and we routinely test for these.
isLaneCrossingShuffleMask(unsigned LaneSizeInBits,unsigned ScalarSizeInBits,ArrayRef<int> Mask)10664 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10665                                       unsigned ScalarSizeInBits,
10666                                       ArrayRef<int> Mask) {
10667   assert(LaneSizeInBits && ScalarSizeInBits &&
10668          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10669          "Illegal shuffle lane size");
10670   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10671   int Size = Mask.size();
10672   for (int i = 0; i < Size; ++i)
10673     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10674       return true;
10675   return false;
10676 }
10677 
10678 /// Test whether there are elements crossing 128-bit lanes in this
10679 /// shuffle mask.
is128BitLaneCrossingShuffleMask(MVT VT,ArrayRef<int> Mask)10680 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
10681   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10682 }
10683 
10684 /// Test whether a shuffle mask is equivalent within each sub-lane.
10685 ///
10686 /// This checks a shuffle mask to see if it is performing the same
10687 /// lane-relative shuffle in each sub-lane. This trivially implies
10688 /// that it is also not lane-crossing. It may however involve a blend from the
10689 /// same lane of a second vector.
10690 ///
10691 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10692 /// non-trivial to compute in the face of undef lanes. The representation is
10693 /// suitable for use with existing 128-bit shuffles as entries from the second
10694 /// vector have been remapped to [LaneSize, 2*LaneSize).
isRepeatedShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10695 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10696                                   ArrayRef<int> Mask,
10697                                   SmallVectorImpl<int> &RepeatedMask) {
10698   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10699   RepeatedMask.assign(LaneSize, -1);
10700   int Size = Mask.size();
10701   for (int i = 0; i < Size; ++i) {
10702     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
10703     if (Mask[i] < 0)
10704       continue;
10705     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10706       // This entry crosses lanes, so there is no way to model this shuffle.
10707       return false;
10708 
10709     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10710     // Adjust second vector indices to start at LaneSize instead of Size.
10711     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10712                                 : Mask[i] % LaneSize + LaneSize;
10713     if (RepeatedMask[i % LaneSize] < 0)
10714       // This is the first non-undef entry in this slot of a 128-bit lane.
10715       RepeatedMask[i % LaneSize] = LocalM;
10716     else if (RepeatedMask[i % LaneSize] != LocalM)
10717       // Found a mismatch with the repeated mask.
10718       return false;
10719   }
10720   return true;
10721 }
10722 
10723 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
10724 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10725 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10726                                 SmallVectorImpl<int> &RepeatedMask) {
10727   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10728 }
10729 
10730 static bool
is128BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask)10731 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
10732   SmallVector<int, 32> RepeatedMask;
10733   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10734 }
10735 
10736 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
10737 static bool
is256BitLaneRepeatedShuffleMask(MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10738 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10739                                 SmallVectorImpl<int> &RepeatedMask) {
10740   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
10741 }
10742 
10743 /// Test whether a target shuffle mask is equivalent within each sub-lane.
10744 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,MVT VT,ArrayRef<int> Mask,SmallVectorImpl<int> & RepeatedMask)10745 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
10746                                         ArrayRef<int> Mask,
10747                                         SmallVectorImpl<int> &RepeatedMask) {
10748   int LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10749   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
10750   int Size = Mask.size();
10751   for (int i = 0; i < Size; ++i) {
10752     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
10753     if (Mask[i] == SM_SentinelUndef)
10754       continue;
10755     if (Mask[i] == SM_SentinelZero) {
10756       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
10757         return false;
10758       RepeatedMask[i % LaneSize] = SM_SentinelZero;
10759       continue;
10760     }
10761     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10762       // This entry crosses lanes, so there is no way to model this shuffle.
10763       return false;
10764 
10765     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10766     // Adjust second vector indices to start at LaneSize instead of Size.
10767     int LocalM =
10768         Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
10769     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
10770       // This is the first non-undef entry in this slot of a 128-bit lane.
10771       RepeatedMask[i % LaneSize] = LocalM;
10772     else if (RepeatedMask[i % LaneSize] != LocalM)
10773       // Found a mismatch with the repeated mask.
10774       return false;
10775   }
10776   return true;
10777 }
10778 
10779 /// Checks whether a shuffle mask is equivalent to an explicit list of
10780 /// arguments.
10781 ///
10782 /// This is a fast way to test a shuffle mask against a fixed pattern:
10783 ///
10784 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
10785 ///
10786 /// It returns true if the mask is exactly as wide as the argument list, and
10787 /// each element of the mask is either -1 (signifying undef) or the value given
10788 /// in the argument.
isShuffleEquivalent(SDValue V1,SDValue V2,ArrayRef<int> Mask,ArrayRef<int> ExpectedMask)10789 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
10790                                 ArrayRef<int> ExpectedMask) {
10791   if (Mask.size() != ExpectedMask.size())
10792     return false;
10793 
10794   int Size = Mask.size();
10795 
10796   // If the values are build vectors, we can look through them to find
10797   // equivalent inputs that make the shuffles equivalent.
10798   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
10799   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
10800 
10801   for (int i = 0; i < Size; ++i) {
10802     assert(Mask[i] >= -1 && "Out of bound mask element!");
10803     if (Mask[i] >= 0 && Mask[i] != ExpectedMask[i]) {
10804       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
10805       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
10806       if (!MaskBV || !ExpectedBV ||
10807           MaskBV->getOperand(Mask[i] % Size) !=
10808               ExpectedBV->getOperand(ExpectedMask[i] % Size))
10809         return false;
10810     }
10811   }
10812 
10813   return true;
10814 }
10815 
10816 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
10817 ///
10818 /// The masks must be exactly the same width.
10819 ///
10820 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
10821 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
10822 ///
10823 /// SM_SentinelZero is accepted as a valid negative index but must match in
10824 /// both.
isTargetShuffleEquivalent(ArrayRef<int> Mask,ArrayRef<int> ExpectedMask,SDValue V1=SDValue (),SDValue V2=SDValue ())10825 static bool isTargetShuffleEquivalent(ArrayRef<int> Mask,
10826                                       ArrayRef<int> ExpectedMask,
10827                                       SDValue V1 = SDValue(),
10828                                       SDValue V2 = SDValue()) {
10829   int Size = Mask.size();
10830   if (Size != (int)ExpectedMask.size())
10831     return false;
10832   assert(isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) &&
10833          "Illegal target shuffle mask");
10834 
10835   // Check for out-of-range target shuffle mask indices.
10836   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
10837     return false;
10838 
10839   // If the values are build vectors, we can look through them to find
10840   // equivalent inputs that make the shuffles equivalent.
10841   auto *BV1 = dyn_cast_or_null<BuildVectorSDNode>(V1);
10842   auto *BV2 = dyn_cast_or_null<BuildVectorSDNode>(V2);
10843   BV1 = ((BV1 && Size != (int)BV1->getNumOperands()) ? nullptr : BV1);
10844   BV2 = ((BV2 && Size != (int)BV2->getNumOperands()) ? nullptr : BV2);
10845 
10846   for (int i = 0; i < Size; ++i) {
10847     if (Mask[i] == SM_SentinelUndef || Mask[i] == ExpectedMask[i])
10848       continue;
10849     if (0 <= Mask[i] && 0 <= ExpectedMask[i]) {
10850       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
10851       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
10852       if (MaskBV && ExpectedBV &&
10853           MaskBV->getOperand(Mask[i] % Size) ==
10854               ExpectedBV->getOperand(ExpectedMask[i] % Size))
10855         continue;
10856     }
10857     // TODO - handle SM_Sentinel equivalences.
10858     return false;
10859   }
10860   return true;
10861 }
10862 
10863 // Attempt to create a shuffle mask from a VSELECT condition mask.
createShuffleMaskFromVSELECT(SmallVectorImpl<int> & Mask,SDValue Cond)10864 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
10865                                          SDValue Cond) {
10866   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10867     return false;
10868 
10869   unsigned Size = Cond.getValueType().getVectorNumElements();
10870   Mask.resize(Size, SM_SentinelUndef);
10871 
10872   for (int i = 0; i != (int)Size; ++i) {
10873     SDValue CondElt = Cond.getOperand(i);
10874     Mask[i] = i;
10875     // Arbitrarily choose from the 2nd operand if the select condition element
10876     // is undef.
10877     // TODO: Can we do better by matching patterns such as even/odd?
10878     if (CondElt.isUndef() || isNullConstant(CondElt))
10879       Mask[i] += Size;
10880   }
10881 
10882   return true;
10883 }
10884 
10885 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
10886 // instructions.
isUnpackWdShuffleMask(ArrayRef<int> Mask,MVT VT)10887 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
10888   if (VT != MVT::v8i32 && VT != MVT::v8f32)
10889     return false;
10890 
10891   SmallVector<int, 8> Unpcklwd;
10892   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
10893                           /* Unary = */ false);
10894   SmallVector<int, 8> Unpckhwd;
10895   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
10896                           /* Unary = */ false);
10897   bool IsUnpackwdMask = (isTargetShuffleEquivalent(Mask, Unpcklwd) ||
10898                          isTargetShuffleEquivalent(Mask, Unpckhwd));
10899   return IsUnpackwdMask;
10900 }
10901 
is128BitUnpackShuffleMask(ArrayRef<int> Mask)10902 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask) {
10903   // Create 128-bit vector type based on mask size.
10904   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
10905   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
10906 
10907   // We can't assume a canonical shuffle mask, so try the commuted version too.
10908   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
10909   ShuffleVectorSDNode::commuteMask(CommutedMask);
10910 
10911   // Match any of unary/binary or low/high.
10912   for (unsigned i = 0; i != 4; ++i) {
10913     SmallVector<int, 16> UnpackMask;
10914     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
10915     if (isTargetShuffleEquivalent(Mask, UnpackMask) ||
10916         isTargetShuffleEquivalent(CommutedMask, UnpackMask))
10917       return true;
10918   }
10919   return false;
10920 }
10921 
10922 /// Return true if a shuffle mask chooses elements identically in its top and
10923 /// bottom halves. For example, any splat mask has the same top and bottom
10924 /// halves. If an element is undefined in only one half of the mask, the halves
10925 /// are not considered identical.
hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask)10926 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
10927   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
10928   unsigned HalfSize = Mask.size() / 2;
10929   for (unsigned i = 0; i != HalfSize; ++i) {
10930     if (Mask[i] != Mask[i + HalfSize])
10931       return false;
10932   }
10933   return true;
10934 }
10935 
10936 /// Get a 4-lane 8-bit shuffle immediate for a mask.
10937 ///
10938 /// This helper function produces an 8-bit shuffle immediate corresponding to
10939 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
10940 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
10941 /// example.
10942 ///
10943 /// NB: We rely heavily on "undef" masks preserving the input lane.
getV4X86ShuffleImm(ArrayRef<int> Mask)10944 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
10945   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
10946   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
10947   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
10948   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
10949   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
10950 
10951   unsigned Imm = 0;
10952   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
10953   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
10954   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
10955   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
10956   return Imm;
10957 }
10958 
getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,const SDLoc & DL,SelectionDAG & DAG)10959 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
10960                                           SelectionDAG &DAG) {
10961   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
10962 }
10963 
10964 // The Shuffle result is as follow:
10965 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
10966 // Each Zeroable's element correspond to a particular Mask's element.
10967 // As described in computeZeroableShuffleElements function.
10968 //
10969 // The function looks for a sub-mask that the nonzero elements are in
10970 // increasing order. If such sub-mask exist. The function returns true.
isNonZeroElementsInOrder(const APInt & Zeroable,ArrayRef<int> Mask,const EVT & VectorType,bool & IsZeroSideLeft)10971 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
10972                                      ArrayRef<int> Mask, const EVT &VectorType,
10973                                      bool &IsZeroSideLeft) {
10974   int NextElement = -1;
10975   // Check if the Mask's nonzero elements are in increasing order.
10976   for (int i = 0, e = Mask.size(); i < e; i++) {
10977     // Checks if the mask's zeros elements are built from only zeros.
10978     assert(Mask[i] >= -1 && "Out of bound mask element!");
10979     if (Mask[i] < 0)
10980       return false;
10981     if (Zeroable[i])
10982       continue;
10983     // Find the lowest non zero element
10984     if (NextElement < 0) {
10985       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
10986       IsZeroSideLeft = NextElement != 0;
10987     }
10988     // Exit if the mask's non zero elements are not in increasing order.
10989     if (NextElement != Mask[i])
10990       return false;
10991     NextElement++;
10992   }
10993   return true;
10994 }
10995 
10996 /// 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)10997 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
10998                                       ArrayRef<int> Mask, SDValue V1,
10999                                       SDValue V2, const APInt &Zeroable,
11000                                       const X86Subtarget &Subtarget,
11001                                       SelectionDAG &DAG) {
11002   int Size = Mask.size();
11003   int LaneSize = 128 / VT.getScalarSizeInBits();
11004   const int NumBytes = VT.getSizeInBits() / 8;
11005   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
11006 
11007   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
11008          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
11009          (Subtarget.hasBWI() && VT.is512BitVector()));
11010 
11011   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
11012   // Sign bit set in i8 mask means zero element.
11013   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
11014 
11015   SDValue V;
11016   for (int i = 0; i < NumBytes; ++i) {
11017     int M = Mask[i / NumEltBytes];
11018     if (M < 0) {
11019       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
11020       continue;
11021     }
11022     if (Zeroable[i / NumEltBytes]) {
11023       PSHUFBMask[i] = ZeroMask;
11024       continue;
11025     }
11026 
11027     // We can only use a single input of V1 or V2.
11028     SDValue SrcV = (M >= Size ? V2 : V1);
11029     if (V && V != SrcV)
11030       return SDValue();
11031     V = SrcV;
11032     M %= Size;
11033 
11034     // PSHUFB can't cross lanes, ensure this doesn't happen.
11035     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
11036       return SDValue();
11037 
11038     M = M % LaneSize;
11039     M = M * NumEltBytes + (i % NumEltBytes);
11040     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
11041   }
11042   assert(V && "Failed to find a source input");
11043 
11044   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
11045   return DAG.getBitcast(
11046       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
11047                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
11048 }
11049 
11050 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
11051                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
11052                            const SDLoc &dl);
11053 
11054 // 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)11055 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
11056                                     const APInt &Zeroable,
11057                                     ArrayRef<int> Mask, SDValue &V1,
11058                                     SDValue &V2, SelectionDAG &DAG,
11059                                     const X86Subtarget &Subtarget) {
11060   bool IsLeftZeroSide = true;
11061   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
11062                                 IsLeftZeroSide))
11063     return SDValue();
11064   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
11065   MVT IntegerType =
11066       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11067   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
11068   unsigned NumElts = VT.getVectorNumElements();
11069   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
11070          "Unexpected number of vector elements");
11071   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
11072                               Subtarget, DAG, DL);
11073   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
11074   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
11075   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
11076 }
11077 
matchShuffleWithUNPCK(MVT VT,SDValue & V1,SDValue & V2,unsigned & UnpackOpcode,bool IsUnary,ArrayRef<int> TargetMask,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)11078 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
11079                                   unsigned &UnpackOpcode, bool IsUnary,
11080                                   ArrayRef<int> TargetMask, const SDLoc &DL,
11081                                   SelectionDAG &DAG,
11082                                   const X86Subtarget &Subtarget) {
11083   int NumElts = VT.getVectorNumElements();
11084 
11085   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
11086   for (int i = 0; i != NumElts; i += 2) {
11087     int M1 = TargetMask[i + 0];
11088     int M2 = TargetMask[i + 1];
11089     Undef1 &= (SM_SentinelUndef == M1);
11090     Undef2 &= (SM_SentinelUndef == M2);
11091     Zero1 &= isUndefOrZero(M1);
11092     Zero2 &= isUndefOrZero(M2);
11093   }
11094   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
11095          "Zeroable shuffle detected");
11096 
11097   // Attempt to match the target mask against the unpack lo/hi mask patterns.
11098   SmallVector<int, 64> Unpckl, Unpckh;
11099   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
11100   if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
11101     UnpackOpcode = X86ISD::UNPCKL;
11102     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11103     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11104     return true;
11105   }
11106 
11107   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
11108   if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
11109     UnpackOpcode = X86ISD::UNPCKH;
11110     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11111     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11112     return true;
11113   }
11114 
11115   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
11116   if (IsUnary && (Zero1 || Zero2)) {
11117     // Don't bother if we can blend instead.
11118     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
11119         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
11120       return false;
11121 
11122     bool MatchLo = true, MatchHi = true;
11123     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
11124       int M = TargetMask[i];
11125 
11126       // Ignore if the input is known to be zero or the index is undef.
11127       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
11128           (M == SM_SentinelUndef))
11129         continue;
11130 
11131       MatchLo &= (M == Unpckl[i]);
11132       MatchHi &= (M == Unpckh[i]);
11133     }
11134 
11135     if (MatchLo || MatchHi) {
11136       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11137       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11138       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11139       return true;
11140     }
11141   }
11142 
11143   // If a binary shuffle, commute and try again.
11144   if (!IsUnary) {
11145     ShuffleVectorSDNode::commuteMask(Unpckl);
11146     if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
11147       UnpackOpcode = X86ISD::UNPCKL;
11148       std::swap(V1, V2);
11149       return true;
11150     }
11151 
11152     ShuffleVectorSDNode::commuteMask(Unpckh);
11153     if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
11154       UnpackOpcode = X86ISD::UNPCKH;
11155       std::swap(V1, V2);
11156       return true;
11157     }
11158   }
11159 
11160   return false;
11161 }
11162 
11163 // X86 has dedicated unpack instructions that can handle specific blend
11164 // operations: UNPCKH and UNPCKL.
lowerShuffleWithUNPCK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)11165 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
11166                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
11167                                      SelectionDAG &DAG) {
11168   SmallVector<int, 8> Unpckl;
11169   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
11170   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
11171     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
11172 
11173   SmallVector<int, 8> Unpckh;
11174   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
11175   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
11176     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
11177 
11178   // Commute and try again.
11179   ShuffleVectorSDNode::commuteMask(Unpckl);
11180   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
11181     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
11182 
11183   ShuffleVectorSDNode::commuteMask(Unpckh);
11184   if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
11185     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
11186 
11187   return SDValue();
11188 }
11189 
11190 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
11191 /// followed by unpack 256-bit.
lowerShuffleWithUNPCK256(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)11192 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
11193                                         ArrayRef<int> Mask, SDValue V1,
11194                                         SDValue V2, SelectionDAG &DAG) {
11195   SmallVector<int, 32> Unpckl, Unpckh;
11196   createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
11197   createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
11198 
11199   unsigned UnpackOpcode;
11200   if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
11201     UnpackOpcode = X86ISD::UNPCKL;
11202   else if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
11203     UnpackOpcode = X86ISD::UNPCKH;
11204   else
11205     return SDValue();
11206 
11207   // This is a "natural" unpack operation (rather than the 128-bit sectored
11208   // operation implemented by AVX). We need to rearrange 64-bit chunks of the
11209   // input in order to use the x86 instruction.
11210   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
11211                             DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
11212   V1 = DAG.getBitcast(VT, V1);
11213   return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
11214 }
11215 
11216 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
11217 // source into the lower elements and zeroing the upper elements.
11218 // TODO: Merge with matchShuffleAsVPMOV.
matchShuffleAsVTRUNC(MVT & SrcVT,MVT & DstVT,MVT VT,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget)11219 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
11220                                  ArrayRef<int> Mask, const APInt &Zeroable,
11221                                  const X86Subtarget &Subtarget) {
11222   if (!VT.is512BitVector() && !Subtarget.hasVLX())
11223     return false;
11224 
11225   unsigned NumElts = Mask.size();
11226   unsigned EltSizeInBits = VT.getScalarSizeInBits();
11227   unsigned MaxScale = 64 / EltSizeInBits;
11228 
11229   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11230     unsigned SrcEltBits = EltSizeInBits * Scale;
11231     if (SrcEltBits < 32 && !Subtarget.hasBWI())
11232       continue;
11233     unsigned NumSrcElts = NumElts / Scale;
11234     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
11235       continue;
11236     unsigned UpperElts = NumElts - NumSrcElts;
11237     if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11238       continue;
11239     SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
11240     SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
11241     DstVT = MVT::getIntegerVT(EltSizeInBits);
11242     if ((NumSrcElts * EltSizeInBits) >= 128) {
11243       // ISD::TRUNCATE
11244       DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
11245     } else {
11246       // X86ISD::VTRUNC
11247       DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
11248     }
11249     return true;
11250   }
11251 
11252   return false;
11253 }
11254 
matchShuffleAsVPMOV(ArrayRef<int> Mask,bool SwappedOps,int Delta)11255 static bool matchShuffleAsVPMOV(ArrayRef<int> Mask, bool SwappedOps,
11256                                 int Delta) {
11257   int Size = (int)Mask.size();
11258   int Split = Size / Delta;
11259   int TruncatedVectorStart = SwappedOps ? Size : 0;
11260 
11261   // Match for mask starting with e.g.: <8, 10, 12, 14,... or <0, 2, 4, 6,...
11262   if (!isSequentialOrUndefInRange(Mask, 0, Split, TruncatedVectorStart, Delta))
11263     return false;
11264 
11265   // The rest of the mask should not refer to the truncated vector's elements.
11266   if (isAnyInRange(Mask.slice(Split, Size - Split), TruncatedVectorStart,
11267                    TruncatedVectorStart + Size))
11268     return false;
11269 
11270   return true;
11271 }
11272 
11273 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
11274 //
11275 // An example is the following:
11276 //
11277 // t0: ch = EntryToken
11278 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
11279 //         t25: v4i32 = truncate t2
11280 //       t41: v8i16 = bitcast t25
11281 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
11282 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
11283 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
11284 //   t18: v2i64 = bitcast t51
11285 //
11286 // Without avx512vl, this is lowered to:
11287 //
11288 // vpmovqd %zmm0, %ymm0
11289 // vpshufb {{.*#+}} xmm0 =
11290 // xmm0[0,1,4,5,8,9,12,13],zero,zero,zero,zero,zero,zero,zero,zero
11291 //
11292 // But when avx512vl is available, one can just use a single vpmovdw
11293 // instruction.
lowerShuffleWithVPMOV(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)11294 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, ArrayRef<int> Mask,
11295                                      MVT VT, SDValue V1, SDValue V2,
11296                                      SelectionDAG &DAG,
11297                                      const X86Subtarget &Subtarget) {
11298   if (VT != MVT::v16i8 && VT != MVT::v8i16)
11299     return SDValue();
11300 
11301   if (Mask.size() != VT.getVectorNumElements())
11302     return SDValue();
11303 
11304   bool SwappedOps = false;
11305 
11306   if (!ISD::isBuildVectorAllZeros(V2.getNode())) {
11307     if (!ISD::isBuildVectorAllZeros(V1.getNode()))
11308       return SDValue();
11309 
11310     std::swap(V1, V2);
11311     SwappedOps = true;
11312   }
11313 
11314   // Look for:
11315   //
11316   // bitcast (truncate <8 x i32> %vec to <8 x i16>) to <16 x i8>
11317   // bitcast (truncate <4 x i64> %vec to <4 x i32>) to <8 x i16>
11318   //
11319   // and similar ones.
11320   if (V1.getOpcode() != ISD::BITCAST)
11321     return SDValue();
11322   if (V1.getOperand(0).getOpcode() != ISD::TRUNCATE)
11323     return SDValue();
11324 
11325   SDValue Src = V1.getOperand(0).getOperand(0);
11326   MVT SrcVT = Src.getSimpleValueType();
11327 
11328   // The vptrunc** instructions truncating 128 bit and 256 bit vectors
11329   // are only available with avx512vl.
11330   if (!SrcVT.is512BitVector() && !Subtarget.hasVLX())
11331     return SDValue();
11332 
11333   // Down Convert Word to Byte is only available with avx512bw. The case with
11334   // 256-bit output doesn't contain a shuffle and is therefore not handled here.
11335   if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
11336       !Subtarget.hasBWI())
11337     return SDValue();
11338 
11339   // The first half/quarter of the mask should refer to every second/fourth
11340   // element of the vector truncated and bitcasted.
11341   if (!matchShuffleAsVPMOV(Mask, SwappedOps, 2) &&
11342       !matchShuffleAsVPMOV(Mask, SwappedOps, 4))
11343     return SDValue();
11344 
11345   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Src);
11346 }
11347 
11348 /// Check whether a compaction lowering can be done by dropping even
11349 /// elements and compute how many times even elements must be dropped.
11350 ///
11351 /// This handles shuffles which take every Nth element where N is a power of
11352 /// two. Example shuffle masks:
11353 ///
11354 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
11355 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
11356 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
11357 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
11358 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
11359 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
11360 ///
11361 /// Any of these lanes can of course be undef.
11362 ///
11363 /// This routine only supports N <= 3.
11364 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
11365 /// for larger N.
11366 ///
11367 /// \returns N above, or the number of times even elements must be dropped if
11368 /// there is such a number. Otherwise returns zero.
canLowerByDroppingEvenElements(ArrayRef<int> Mask,bool IsSingleInput)11369 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
11370                                           bool IsSingleInput) {
11371   // The modulus for the shuffle vector entries is based on whether this is
11372   // a single input or not.
11373   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
11374   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
11375          "We should only be called with masks with a power-of-2 size!");
11376 
11377   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
11378 
11379   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
11380   // and 2^3 simultaneously. This is because we may have ambiguity with
11381   // partially undef inputs.
11382   bool ViableForN[3] = {true, true, true};
11383 
11384   for (int i = 0, e = Mask.size(); i < e; ++i) {
11385     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
11386     // want.
11387     if (Mask[i] < 0)
11388       continue;
11389 
11390     bool IsAnyViable = false;
11391     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
11392       if (ViableForN[j]) {
11393         uint64_t N = j + 1;
11394 
11395         // The shuffle mask must be equal to (i * 2^N) % M.
11396         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
11397           IsAnyViable = true;
11398         else
11399           ViableForN[j] = false;
11400       }
11401     // Early exit if we exhaust the possible powers of two.
11402     if (!IsAnyViable)
11403       break;
11404   }
11405 
11406   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
11407     if (ViableForN[j])
11408       return j + 1;
11409 
11410   // Return 0 as there is no viable power of two.
11411   return 0;
11412 }
11413 
11414 // X86 has dedicated pack instructions that can handle specific truncation
11415 // operations: PACKSS and PACKUS.
11416 // Checks for compaction shuffle masks if MaxStages > 1.
11417 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
matchShuffleWithPACK(MVT VT,MVT & SrcVT,SDValue & V1,SDValue & V2,unsigned & PackOpcode,ArrayRef<int> TargetMask,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned MaxStages=1)11418 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11419                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
11420                                  SelectionDAG &DAG,
11421                                  const X86Subtarget &Subtarget,
11422                                  unsigned MaxStages = 1) {
11423   unsigned NumElts = VT.getVectorNumElements();
11424   unsigned BitSize = VT.getScalarSizeInBits();
11425   assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
11426          "Illegal maximum compaction");
11427 
11428   auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
11429     unsigned NumSrcBits = PackVT.getScalarSizeInBits();
11430     unsigned NumPackedBits = NumSrcBits - BitSize;
11431     SDValue VV1 = DAG.getBitcast(PackVT, N1);
11432     SDValue VV2 = DAG.getBitcast(PackVT, N2);
11433     if (Subtarget.hasSSE41() || BitSize == 8) {
11434       APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
11435       if ((N1.isUndef() || DAG.MaskedValueIsZero(VV1, ZeroMask)) &&
11436           (N2.isUndef() || DAG.MaskedValueIsZero(VV2, ZeroMask))) {
11437         V1 = VV1;
11438         V2 = VV2;
11439         SrcVT = PackVT;
11440         PackOpcode = X86ISD::PACKUS;
11441         return true;
11442       }
11443     }
11444     if ((N1.isUndef() || DAG.ComputeNumSignBits(VV1) > NumPackedBits) &&
11445         (N2.isUndef() || DAG.ComputeNumSignBits(VV2) > NumPackedBits)) {
11446       V1 = VV1;
11447       V2 = VV2;
11448       SrcVT = PackVT;
11449       PackOpcode = X86ISD::PACKSS;
11450       return true;
11451     }
11452     return false;
11453   };
11454 
11455   // Attempt to match against wider and wider compaction patterns.
11456   for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
11457     MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
11458     MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
11459 
11460     // Try binary shuffle.
11461     SmallVector<int, 32> BinaryMask;
11462     createPackShuffleMask(VT, BinaryMask, false, NumStages);
11463     if (isTargetShuffleEquivalent(TargetMask, BinaryMask, V1, V2))
11464       if (MatchPACK(V1, V2, PackVT))
11465         return true;
11466 
11467     // Try unary shuffle.
11468     SmallVector<int, 32> UnaryMask;
11469     createPackShuffleMask(VT, UnaryMask, true, NumStages);
11470     if (isTargetShuffleEquivalent(TargetMask, UnaryMask, V1))
11471       if (MatchPACK(V1, V1, PackVT))
11472         return true;
11473   }
11474 
11475   return false;
11476 }
11477 
lowerShuffleWithPACK(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG,const X86Subtarget & Subtarget)11478 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
11479                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
11480                                     const X86Subtarget &Subtarget) {
11481   MVT PackVT;
11482   unsigned PackOpcode;
11483   unsigned SizeBits = VT.getSizeInBits();
11484   unsigned EltBits = VT.getScalarSizeInBits();
11485   unsigned MaxStages = Log2_32(64 / EltBits);
11486   if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11487                             Subtarget, MaxStages))
11488     return SDValue();
11489 
11490   unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
11491   unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
11492 
11493   // Don't lower multi-stage packs on AVX512, truncation is better.
11494   if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
11495     return SDValue();
11496 
11497   // Pack to the largest type possible:
11498   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
11499   unsigned MaxPackBits = 16;
11500   if (CurrentEltBits > 16 &&
11501       (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
11502     MaxPackBits = 32;
11503 
11504   // Repeatedly pack down to the target size.
11505   SDValue Res;
11506   for (unsigned i = 0; i != NumStages; ++i) {
11507     unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
11508     unsigned NumSrcElts = SizeBits / SrcEltBits;
11509     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11510     MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
11511     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11512     MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
11513     Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
11514                       DAG.getBitcast(SrcVT, V2));
11515     V1 = V2 = Res;
11516     CurrentEltBits /= 2;
11517   }
11518   assert(Res && Res.getValueType() == VT &&
11519          "Failed to lower compaction shuffle");
11520   return Res;
11521 }
11522 
11523 /// Try to emit a bitmask instruction for a shuffle.
11524 ///
11525 /// This handles cases where we can model a blend exactly as a bitmask due to
11526 /// 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)11527 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
11528                                      SDValue V2, ArrayRef<int> Mask,
11529                                      const APInt &Zeroable,
11530                                      const X86Subtarget &Subtarget,
11531                                      SelectionDAG &DAG) {
11532   MVT MaskVT = VT;
11533   MVT EltVT = VT.getVectorElementType();
11534   SDValue Zero, AllOnes;
11535   // Use f64 if i64 isn't legal.
11536   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
11537     EltVT = MVT::f64;
11538     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
11539   }
11540 
11541   MVT LogicVT = VT;
11542   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
11543     Zero = DAG.getConstantFP(0.0, DL, EltVT);
11544     APFloat AllOnesValue = APFloat::getAllOnesValue(
11545         SelectionDAG::EVTToAPFloatSemantics(EltVT), EltVT.getSizeInBits());
11546     AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
11547     LogicVT =
11548         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
11549   } else {
11550     Zero = DAG.getConstant(0, DL, EltVT);
11551     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11552   }
11553 
11554   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
11555   SDValue V;
11556   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11557     if (Zeroable[i])
11558       continue;
11559     if (Mask[i] % Size != i)
11560       return SDValue(); // Not a blend.
11561     if (!V)
11562       V = Mask[i] < Size ? V1 : V2;
11563     else if (V != (Mask[i] < Size ? V1 : V2))
11564       return SDValue(); // Can only let one input through the mask.
11565 
11566     VMaskOps[i] = AllOnes;
11567   }
11568   if (!V)
11569     return SDValue(); // No non-zeroable elements!
11570 
11571   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
11572   VMask = DAG.getBitcast(LogicVT, VMask);
11573   V = DAG.getBitcast(LogicVT, V);
11574   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11575   return DAG.getBitcast(VT, And);
11576 }
11577 
11578 /// Try to emit a blend instruction for a shuffle using bit math.
11579 ///
11580 /// This is used as a fallback approach when first class blend instructions are
11581 /// unavailable. Currently it is only suitable for integer vectors, but could
11582 /// be generalized for floating point vectors if desirable.
lowerShuffleAsBitBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)11583 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
11584                                       SDValue V2, ArrayRef<int> Mask,
11585                                       SelectionDAG &DAG) {
11586   assert(VT.isInteger() && "Only supports integer vector types!");
11587   MVT EltVT = VT.getVectorElementType();
11588   SDValue Zero = DAG.getConstant(0, DL, EltVT);
11589   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11590   SmallVector<SDValue, 16> MaskOps;
11591   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11592     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
11593       return SDValue(); // Shuffled input!
11594     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
11595   }
11596 
11597   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
11598   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
11599   V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
11600   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
11601 }
11602 
11603 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
11604                                     SDValue PreservedSrc,
11605                                     const X86Subtarget &Subtarget,
11606                                     SelectionDAG &DAG);
11607 
matchShuffleAsBlend(SDValue V1,SDValue V2,MutableArrayRef<int> Mask,const APInt & Zeroable,bool & ForceV1Zero,bool & ForceV2Zero,uint64_t & BlendMask)11608 static bool matchShuffleAsBlend(SDValue V1, SDValue V2,
11609                                 MutableArrayRef<int> Mask,
11610                                 const APInt &Zeroable, bool &ForceV1Zero,
11611                                 bool &ForceV2Zero, uint64_t &BlendMask) {
11612   bool V1IsZeroOrUndef =
11613       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
11614   bool V2IsZeroOrUndef =
11615       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
11616 
11617   BlendMask = 0;
11618   ForceV1Zero = false, ForceV2Zero = false;
11619   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
11620 
11621   // Attempt to generate the binary blend mask. If an input is zero then
11622   // we can use any lane.
11623   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11624     int M = Mask[i];
11625     if (M == SM_SentinelUndef)
11626       continue;
11627     if (M == i)
11628       continue;
11629     if (M == i + Size) {
11630       BlendMask |= 1ull << i;
11631       continue;
11632     }
11633     if (Zeroable[i]) {
11634       if (V1IsZeroOrUndef) {
11635         ForceV1Zero = true;
11636         Mask[i] = i;
11637         continue;
11638       }
11639       if (V2IsZeroOrUndef) {
11640         ForceV2Zero = true;
11641         BlendMask |= 1ull << i;
11642         Mask[i] = i + Size;
11643         continue;
11644       }
11645     }
11646     return false;
11647   }
11648   return true;
11649 }
11650 
scaleVectorShuffleBlendMask(uint64_t BlendMask,int Size,int Scale)11651 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
11652                                             int Scale) {
11653   uint64_t ScaledMask = 0;
11654   for (int i = 0; i != Size; ++i)
11655     if (BlendMask & (1ull << i))
11656       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
11657   return ScaledMask;
11658 }
11659 
11660 /// Try to emit a blend instruction for a shuffle.
11661 ///
11662 /// This doesn't do any checks for the availability of instructions for blending
11663 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
11664 /// be matched in the backend with the type given. What it does check for is
11665 /// 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)11666 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
11667                                    SDValue V2, ArrayRef<int> Original,
11668                                    const APInt &Zeroable,
11669                                    const X86Subtarget &Subtarget,
11670                                    SelectionDAG &DAG) {
11671   uint64_t BlendMask = 0;
11672   bool ForceV1Zero = false, ForceV2Zero = false;
11673   SmallVector<int, 64> Mask(Original.begin(), Original.end());
11674   if (!matchShuffleAsBlend(V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
11675                            BlendMask))
11676     return SDValue();
11677 
11678   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
11679   if (ForceV1Zero)
11680     V1 = getZeroVector(VT, Subtarget, DAG, DL);
11681   if (ForceV2Zero)
11682     V2 = getZeroVector(VT, Subtarget, DAG, DL);
11683 
11684   switch (VT.SimpleTy) {
11685   case MVT::v4i64:
11686   case MVT::v8i32:
11687     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
11688     LLVM_FALLTHROUGH;
11689   case MVT::v4f64:
11690   case MVT::v8f32:
11691     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
11692     LLVM_FALLTHROUGH;
11693   case MVT::v2f64:
11694   case MVT::v2i64:
11695   case MVT::v4f32:
11696   case MVT::v4i32:
11697   case MVT::v8i16:
11698     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
11699     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
11700                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11701   case MVT::v16i16: {
11702     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
11703     SmallVector<int, 8> RepeatedMask;
11704     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
11705       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
11706       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
11707       BlendMask = 0;
11708       for (int i = 0; i < 8; ++i)
11709         if (RepeatedMask[i] >= 8)
11710           BlendMask |= 1ull << i;
11711       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11712                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
11713     }
11714     // Use PBLENDW for lower/upper lanes and then blend lanes.
11715     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
11716     // merge to VSELECT where useful.
11717     uint64_t LoMask = BlendMask & 0xFF;
11718     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
11719     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
11720       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11721                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
11722       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
11723                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
11724       return DAG.getVectorShuffle(
11725           MVT::v16i16, DL, Lo, Hi,
11726           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
11727     }
11728     LLVM_FALLTHROUGH;
11729   }
11730   case MVT::v32i8:
11731     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
11732     LLVM_FALLTHROUGH;
11733   case MVT::v16i8: {
11734     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
11735 
11736     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
11737     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
11738                                                Subtarget, DAG))
11739       return Masked;
11740 
11741     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
11742       MVT IntegerType =
11743           MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11744       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11745       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11746     }
11747 
11748     // If we have VPTERNLOG, we can use that as a bit blend.
11749     if (Subtarget.hasVLX())
11750       if (SDValue BitBlend =
11751               lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
11752         return BitBlend;
11753 
11754     // Scale the blend by the number of bytes per element.
11755     int Scale = VT.getScalarSizeInBits() / 8;
11756 
11757     // This form of blend is always done on bytes. Compute the byte vector
11758     // type.
11759     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11760 
11761     // x86 allows load folding with blendvb from the 2nd source operand. But
11762     // we are still using LLVM select here (see comment below), so that's V1.
11763     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
11764     // allow that load-folding possibility.
11765     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
11766       ShuffleVectorSDNode::commuteMask(Mask);
11767       std::swap(V1, V2);
11768     }
11769 
11770     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
11771     // mix of LLVM's code generator and the x86 backend. We tell the code
11772     // generator that boolean values in the elements of an x86 vector register
11773     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
11774     // mapping a select to operand #1, and 'false' mapping to operand #2. The
11775     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
11776     // of the element (the remaining are ignored) and 0 in that high bit would
11777     // mean operand #1 while 1 in the high bit would mean operand #2. So while
11778     // the LLVM model for boolean values in vector elements gets the relevant
11779     // bit set, it is set backwards and over constrained relative to x86's
11780     // actual model.
11781     SmallVector<SDValue, 32> VSELECTMask;
11782     for (int i = 0, Size = Mask.size(); i < Size; ++i)
11783       for (int j = 0; j < Scale; ++j)
11784         VSELECTMask.push_back(
11785             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
11786                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
11787                                           MVT::i8));
11788 
11789     V1 = DAG.getBitcast(BlendVT, V1);
11790     V2 = DAG.getBitcast(BlendVT, V2);
11791     return DAG.getBitcast(
11792         VT,
11793         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
11794                       V1, V2));
11795   }
11796   case MVT::v16f32:
11797   case MVT::v8f64:
11798   case MVT::v8i64:
11799   case MVT::v16i32:
11800   case MVT::v32i16:
11801   case MVT::v64i8: {
11802     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
11803     bool OptForSize = DAG.shouldOptForSize();
11804     if (!OptForSize) {
11805       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
11806                                                  Subtarget, DAG))
11807         return Masked;
11808     }
11809 
11810     // Otherwise load an immediate into a GPR, cast to k-register, and use a
11811     // masked move.
11812     MVT IntegerType =
11813         MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11814     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
11815     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
11816   }
11817   default:
11818     llvm_unreachable("Not a supported integer vector type!");
11819   }
11820 }
11821 
11822 /// Try to lower as a blend of elements from two inputs followed by
11823 /// a single-input permutation.
11824 ///
11825 /// This matches the pattern where we can blend elements from two inputs and
11826 /// 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)11827 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
11828                                              SDValue V1, SDValue V2,
11829                                              ArrayRef<int> Mask,
11830                                              SelectionDAG &DAG,
11831                                              bool ImmBlends = false) {
11832   // We build up the blend mask while checking whether a blend is a viable way
11833   // to reduce the shuffle.
11834   SmallVector<int, 32> BlendMask(Mask.size(), -1);
11835   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
11836 
11837   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11838     if (Mask[i] < 0)
11839       continue;
11840 
11841     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
11842 
11843     if (BlendMask[Mask[i] % Size] < 0)
11844       BlendMask[Mask[i] % Size] = Mask[i];
11845     else if (BlendMask[Mask[i] % Size] != Mask[i])
11846       return SDValue(); // Can't blend in the needed input!
11847 
11848     PermuteMask[i] = Mask[i] % Size;
11849   }
11850 
11851   // If only immediate blends, then bail if the blend mask can't be widened to
11852   // i16.
11853   unsigned EltSize = VT.getScalarSizeInBits();
11854   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
11855     return SDValue();
11856 
11857   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11858   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
11859 }
11860 
11861 /// Try to lower as an unpack of elements from two inputs followed by
11862 /// a single-input permutation.
11863 ///
11864 /// This matches the pattern where we can unpack elements from two inputs and
11865 /// 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)11866 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
11867                                              SDValue V1, SDValue V2,
11868                                              ArrayRef<int> Mask,
11869                                              SelectionDAG &DAG) {
11870   int NumElts = Mask.size();
11871   int NumLanes = VT.getSizeInBits() / 128;
11872   int NumLaneElts = NumElts / NumLanes;
11873   int NumHalfLaneElts = NumLaneElts / 2;
11874 
11875   bool MatchLo = true, MatchHi = true;
11876   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
11877 
11878   // Determine UNPCKL/UNPCKH type and operand order.
11879   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11880     for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
11881       int M = Mask[Lane + Elt];
11882       if (M < 0)
11883         continue;
11884 
11885       SDValue &Op = Ops[Elt & 1];
11886       if (M < NumElts && (Op.isUndef() || Op == V1))
11887         Op = V1;
11888       else if (NumElts <= M && (Op.isUndef() || Op == V2))
11889         Op = V2;
11890       else
11891         return SDValue();
11892 
11893       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
11894       MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
11895                  isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
11896       MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
11897                  isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
11898       if (!MatchLo && !MatchHi)
11899         return SDValue();
11900     }
11901   }
11902   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
11903 
11904   // Now check that each pair of elts come from the same unpack pair
11905   // and set the permute mask based on each pair.
11906   // TODO - Investigate cases where we permute individual elements.
11907   SmallVector<int, 32> PermuteMask(NumElts, -1);
11908   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
11909     for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
11910       int M0 = Mask[Lane + Elt + 0];
11911       int M1 = Mask[Lane + Elt + 1];
11912       if (0 <= M0 && 0 <= M1 &&
11913           (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
11914         return SDValue();
11915       if (0 <= M0)
11916         PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
11917       if (0 <= M1)
11918         PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
11919     }
11920   }
11921 
11922   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11923   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
11924   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
11925 }
11926 
11927 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
11928 /// 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)11929 static SDValue lowerShuffleAsByteRotateAndPermute(
11930     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11931     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11932   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
11933       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
11934       (VT.is512BitVector() && !Subtarget.hasBWI()))
11935     return SDValue();
11936 
11937   // We don't currently support lane crossing permutes.
11938   if (is128BitLaneCrossingShuffleMask(VT, Mask))
11939     return SDValue();
11940 
11941   int Scale = VT.getScalarSizeInBits() / 8;
11942   int NumLanes = VT.getSizeInBits() / 128;
11943   int NumElts = VT.getVectorNumElements();
11944   int NumEltsPerLane = NumElts / NumLanes;
11945 
11946   // Determine range of mask elts.
11947   bool Blend1 = true;
11948   bool Blend2 = true;
11949   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
11950   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
11951   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11952     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11953       int M = Mask[Lane + Elt];
11954       if (M < 0)
11955         continue;
11956       if (M < NumElts) {
11957         Blend1 &= (M == (Lane + Elt));
11958         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11959         M = M % NumEltsPerLane;
11960         Range1.first = std::min(Range1.first, M);
11961         Range1.second = std::max(Range1.second, M);
11962       } else {
11963         M -= NumElts;
11964         Blend2 &= (M == (Lane + Elt));
11965         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
11966         M = M % NumEltsPerLane;
11967         Range2.first = std::min(Range2.first, M);
11968         Range2.second = std::max(Range2.second, M);
11969       }
11970     }
11971   }
11972 
11973   // Bail if we don't need both elements.
11974   // TODO - it might be worth doing this for unary shuffles if the permute
11975   // can be widened.
11976   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
11977       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
11978     return SDValue();
11979 
11980   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
11981     return SDValue();
11982 
11983   // Rotate the 2 ops so we can access both ranges, then permute the result.
11984   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
11985     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11986     SDValue Rotate = DAG.getBitcast(
11987         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
11988                         DAG.getBitcast(ByteVT, Lo),
11989                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
11990     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
11991     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
11992       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
11993         int M = Mask[Lane + Elt];
11994         if (M < 0)
11995           continue;
11996         if (M < NumElts)
11997           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
11998         else
11999           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
12000       }
12001     }
12002     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
12003   };
12004 
12005   // Check if the ranges are small enough to rotate from either direction.
12006   if (Range2.second < Range1.first)
12007     return RotateAndPermute(V1, V2, Range1.first, 0);
12008   if (Range1.second < Range2.first)
12009     return RotateAndPermute(V2, V1, Range2.first, NumElts);
12010   return SDValue();
12011 }
12012 
12013 /// Generic routine to decompose a shuffle and blend into independent
12014 /// blends and permutes.
12015 ///
12016 /// This matches the extremely common pattern for handling combined
12017 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
12018 /// operations. It will try to pick the best arrangement of shuffles and
12019 /// blends.
lowerShuffleAsDecomposedShuffleBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12020 static SDValue lowerShuffleAsDecomposedShuffleBlend(
12021     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12022     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12023   // Shuffle the input elements into the desired positions in V1 and V2 and
12024   // blend them together.
12025   SmallVector<int, 32> V1Mask(Mask.size(), -1);
12026   SmallVector<int, 32> V2Mask(Mask.size(), -1);
12027   SmallVector<int, 32> BlendMask(Mask.size(), -1);
12028   for (int i = 0, Size = Mask.size(); i < Size; ++i)
12029     if (Mask[i] >= 0 && Mask[i] < Size) {
12030       V1Mask[i] = Mask[i];
12031       BlendMask[i] = i;
12032     } else if (Mask[i] >= Size) {
12033       V2Mask[i] = Mask[i] - Size;
12034       BlendMask[i] = i + Size;
12035     }
12036 
12037   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
12038   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
12039   // the shuffle may be able to fold with a load or other benefit. However, when
12040   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
12041   // pre-shuffle first is a better strategy.
12042   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
12043     // Only prefer immediate blends to unpack/rotate.
12044     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12045                                                           DAG, true))
12046       return BlendPerm;
12047     if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
12048                                                            DAG))
12049       return UnpackPerm;
12050     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
12051             DL, VT, V1, V2, Mask, Subtarget, DAG))
12052       return RotatePerm;
12053     // Unpack/rotate failed - try again with variable blends.
12054     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12055                                                           DAG))
12056       return BlendPerm;
12057   }
12058 
12059   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12060   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12061   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
12062 }
12063 
12064 /// Try to lower a vector shuffle as a bit rotation.
12065 ///
12066 /// Look for a repeated rotation pattern in each sub group.
12067 /// Returns a ISD::ROTL element rotation amount or -1 if failed.
matchShuffleAsBitRotate(ArrayRef<int> Mask,int NumSubElts)12068 static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
12069   int NumElts = Mask.size();
12070   assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
12071 
12072   int RotateAmt = -1;
12073   for (int i = 0; i != NumElts; i += NumSubElts) {
12074     for (int j = 0; j != NumSubElts; ++j) {
12075       int M = Mask[i + j];
12076       if (M < 0)
12077         continue;
12078       if (!isInRange(M, i, i + NumSubElts))
12079         return -1;
12080       int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
12081       if (0 <= RotateAmt && Offset != RotateAmt)
12082         return -1;
12083       RotateAmt = Offset;
12084     }
12085   }
12086   return RotateAmt;
12087 }
12088 
matchShuffleAsBitRotate(MVT & RotateVT,int EltSizeInBits,const X86Subtarget & Subtarget,ArrayRef<int> Mask)12089 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12090                                    const X86Subtarget &Subtarget,
12091                                    ArrayRef<int> Mask) {
12092   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12093   assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
12094 
12095   // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12096   int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
12097   int MaxSubElts = 64 / EltSizeInBits;
12098   for (int NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
12099     int RotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
12100     if (RotateAmt < 0)
12101       continue;
12102 
12103     int NumElts = Mask.size();
12104     MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
12105     RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
12106     return RotateAmt * EltSizeInBits;
12107   }
12108 
12109   return -1;
12110 }
12111 
12112 /// Lower shuffle using X86ISD::VROTLI rotations.
lowerShuffleAsBitRotate(const SDLoc & DL,MVT VT,SDValue V1,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12113 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
12114                                        ArrayRef<int> Mask,
12115                                        const X86Subtarget &Subtarget,
12116                                        SelectionDAG &DAG) {
12117   // Only XOP + AVX512 targets have bit rotation instructions.
12118   // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
12119   bool IsLegal =
12120       (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
12121   if (!IsLegal && Subtarget.hasSSE3())
12122     return SDValue();
12123 
12124   MVT RotateVT;
12125   int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
12126                                           Subtarget, Mask);
12127   if (RotateAmt < 0)
12128     return SDValue();
12129 
12130   // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
12131   // expanded to OR(SRL,SHL), will be more efficient, but if they can
12132   // widen to vXi16 or more then existing lowering should will be better.
12133   if (!IsLegal) {
12134     if ((RotateAmt % 16) == 0)
12135       return SDValue();
12136     // TODO: Use getTargetVShiftByConstNode.
12137     unsigned ShlAmt = RotateAmt;
12138     unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
12139     V1 = DAG.getBitcast(RotateVT, V1);
12140     SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
12141                               DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
12142     SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
12143                               DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
12144     SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
12145     return DAG.getBitcast(VT, Rot);
12146   }
12147 
12148   SDValue Rot =
12149       DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
12150                   DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
12151   return DAG.getBitcast(VT, Rot);
12152 }
12153 
12154 /// Try to match a vector shuffle as an element rotation.
12155 ///
12156 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
matchShuffleAsElementRotate(SDValue & V1,SDValue & V2,ArrayRef<int> Mask)12157 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
12158                                        ArrayRef<int> Mask) {
12159   int NumElts = Mask.size();
12160 
12161   // We need to detect various ways of spelling a rotation:
12162   //   [11, 12, 13, 14, 15,  0,  1,  2]
12163   //   [-1, 12, 13, 14, -1, -1,  1, -1]
12164   //   [-1, -1, -1, -1, -1, -1,  1,  2]
12165   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
12166   //   [-1,  4,  5,  6, -1, -1,  9, -1]
12167   //   [-1,  4,  5,  6, -1, -1, -1, -1]
12168   int Rotation = 0;
12169   SDValue Lo, Hi;
12170   for (int i = 0; i < NumElts; ++i) {
12171     int M = Mask[i];
12172     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
12173            "Unexpected mask index.");
12174     if (M < 0)
12175       continue;
12176 
12177     // Determine where a rotated vector would have started.
12178     int StartIdx = i - (M % NumElts);
12179     if (StartIdx == 0)
12180       // The identity rotation isn't interesting, stop.
12181       return -1;
12182 
12183     // If we found the tail of a vector the rotation must be the missing
12184     // front. If we found the head of a vector, it must be how much of the
12185     // head.
12186     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
12187 
12188     if (Rotation == 0)
12189       Rotation = CandidateRotation;
12190     else if (Rotation != CandidateRotation)
12191       // The rotations don't match, so we can't match this mask.
12192       return -1;
12193 
12194     // Compute which value this mask is pointing at.
12195     SDValue MaskV = M < NumElts ? V1 : V2;
12196 
12197     // Compute which of the two target values this index should be assigned
12198     // to. This reflects whether the high elements are remaining or the low
12199     // elements are remaining.
12200     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
12201 
12202     // Either set up this value if we've not encountered it before, or check
12203     // that it remains consistent.
12204     if (!TargetV)
12205       TargetV = MaskV;
12206     else if (TargetV != MaskV)
12207       // This may be a rotation, but it pulls from the inputs in some
12208       // unsupported interleaving.
12209       return -1;
12210   }
12211 
12212   // Check that we successfully analyzed the mask, and normalize the results.
12213   assert(Rotation != 0 && "Failed to locate a viable rotation!");
12214   assert((Lo || Hi) && "Failed to find a rotated input vector!");
12215   if (!Lo)
12216     Lo = Hi;
12217   else if (!Hi)
12218     Hi = Lo;
12219 
12220   V1 = Lo;
12221   V2 = Hi;
12222 
12223   return Rotation;
12224 }
12225 
12226 /// Try to lower a vector shuffle as a byte rotation.
12227 ///
12228 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
12229 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
12230 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
12231 /// try to generically lower a vector shuffle through such an pattern. It
12232 /// does not check for the profitability of lowering either as PALIGNR or
12233 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
12234 /// This matches shuffle vectors that look like:
12235 ///
12236 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
12237 ///
12238 /// Essentially it concatenates V1 and V2, shifts right by some number of
12239 /// elements, and takes the low elements as the result. Note that while this is
12240 /// specified as a *right shift* because x86 is little-endian, it is a *left
12241 /// rotate* of the vector lanes.
matchShuffleAsByteRotate(MVT VT,SDValue & V1,SDValue & V2,ArrayRef<int> Mask)12242 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
12243                                     ArrayRef<int> Mask) {
12244   // Don't accept any shuffles with zero elements.
12245   if (isAnyZero(Mask))
12246     return -1;
12247 
12248   // PALIGNR works on 128-bit lanes.
12249   SmallVector<int, 16> RepeatedMask;
12250   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
12251     return -1;
12252 
12253   int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
12254   if (Rotation <= 0)
12255     return -1;
12256 
12257   // PALIGNR rotates bytes, so we need to scale the
12258   // rotation based on how many bytes are in the vector lane.
12259   int NumElts = RepeatedMask.size();
12260   int Scale = 16 / NumElts;
12261   return Rotation * Scale;
12262 }
12263 
lowerShuffleAsByteRotate(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12264 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
12265                                         SDValue V2, ArrayRef<int> Mask,
12266                                         const X86Subtarget &Subtarget,
12267                                         SelectionDAG &DAG) {
12268   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12269 
12270   SDValue Lo = V1, Hi = V2;
12271   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
12272   if (ByteRotation <= 0)
12273     return SDValue();
12274 
12275   // Cast the inputs to i8 vector of correct length to match PALIGNR or
12276   // PSLLDQ/PSRLDQ.
12277   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12278   Lo = DAG.getBitcast(ByteVT, Lo);
12279   Hi = DAG.getBitcast(ByteVT, Hi);
12280 
12281   // SSSE3 targets can use the palignr instruction.
12282   if (Subtarget.hasSSSE3()) {
12283     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
12284            "512-bit PALIGNR requires BWI instructions");
12285     return DAG.getBitcast(
12286         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
12287                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
12288   }
12289 
12290   assert(VT.is128BitVector() &&
12291          "Rotate-based lowering only supports 128-bit lowering!");
12292   assert(Mask.size() <= 16 &&
12293          "Can shuffle at most 16 bytes in a 128-bit vector!");
12294   assert(ByteVT == MVT::v16i8 &&
12295          "SSE2 rotate lowering only needed for v16i8!");
12296 
12297   // Default SSE2 implementation
12298   int LoByteShift = 16 - ByteRotation;
12299   int HiByteShift = ByteRotation;
12300 
12301   SDValue LoShift =
12302       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
12303                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
12304   SDValue HiShift =
12305       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
12306                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
12307   return DAG.getBitcast(VT,
12308                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
12309 }
12310 
12311 /// Try to lower a vector shuffle as a dword/qword rotation.
12312 ///
12313 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
12314 /// rotation of the concatenation of two vectors; This routine will
12315 /// try to generically lower a vector shuffle through such an pattern.
12316 ///
12317 /// Essentially it concatenates V1 and V2, shifts right by some number of
12318 /// elements, and takes the low elements as the result. Note that while this is
12319 /// specified as a *right shift* because x86 is little-endian, it is a *left
12320 /// rotate* of the vector lanes.
lowerShuffleAsVALIGN(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)12321 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
12322                                     SDValue V2, ArrayRef<int> Mask,
12323                                     const X86Subtarget &Subtarget,
12324                                     SelectionDAG &DAG) {
12325   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
12326          "Only 32-bit and 64-bit elements are supported!");
12327 
12328   // 128/256-bit vectors are only supported with VLX.
12329   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
12330          && "VLX required for 128/256-bit vectors");
12331 
12332   SDValue Lo = V1, Hi = V2;
12333   int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
12334   if (Rotation <= 0)
12335     return SDValue();
12336 
12337   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
12338                      DAG.getTargetConstant(Rotation, DL, MVT::i8));
12339 }
12340 
12341 /// 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)12342 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
12343                                            SDValue V2, ArrayRef<int> Mask,
12344                                            const APInt &Zeroable,
12345                                            const X86Subtarget &Subtarget,
12346                                            SelectionDAG &DAG) {
12347   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12348   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
12349 
12350   // We need a shuffle that has zeros at one/both ends and a sequential
12351   // shuffle from one source within.
12352   unsigned ZeroLo = Zeroable.countTrailingOnes();
12353   unsigned ZeroHi = Zeroable.countLeadingOnes();
12354   if (!ZeroLo && !ZeroHi)
12355     return SDValue();
12356 
12357   unsigned NumElts = Mask.size();
12358   unsigned Len = NumElts - (ZeroLo + ZeroHi);
12359   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
12360     return SDValue();
12361 
12362   unsigned Scale = VT.getScalarSizeInBits() / 8;
12363   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
12364   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
12365       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
12366     return SDValue();
12367 
12368   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12369   Res = DAG.getBitcast(MVT::v16i8, Res);
12370 
12371   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
12372   // inner sequential set of elements, possibly offset:
12373   // 01234567 --> zzzzzz01 --> 1zzzzzzz
12374   // 01234567 --> 4567zzzz --> zzzzz456
12375   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
12376   if (ZeroLo == 0) {
12377     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12378     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12379                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12380     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12381                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
12382   } else if (ZeroHi == 0) {
12383     unsigned Shift = Mask[ZeroLo] % NumElts;
12384     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12385                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12386     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12387                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12388   } else if (!Subtarget.hasSSSE3()) {
12389     // If we don't have PSHUFB then its worth avoiding an AND constant mask
12390     // by performing 3 byte shifts. Shuffle combining can kick in above that.
12391     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
12392     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12393     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12394                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12395     Shift += Mask[ZeroLo] % NumElts;
12396     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12397                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12398     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12399                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12400   } else
12401     return SDValue();
12402 
12403   return DAG.getBitcast(VT, Res);
12404 }
12405 
12406 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
12407 ///
12408 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
12409 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
12410 /// matches elements from one of the input vectors shuffled to the left or
12411 /// right with zeroable elements 'shifted in'. It handles both the strictly
12412 /// bit-wise element shifts and the byte shift across an entire 128-bit double
12413 /// quad word lane.
12414 ///
12415 /// PSHL : (little-endian) left bit shift.
12416 /// [ zz, 0, zz,  2 ]
12417 /// [ -1, 4, zz, -1 ]
12418 /// PSRL : (little-endian) right bit shift.
12419 /// [  1, zz,  3, zz]
12420 /// [ -1, -1,  7, zz]
12421 /// PSLLDQ : (little-endian) left byte shift
12422 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
12423 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
12424 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
12425 /// PSRLDQ : (little-endian) right byte shift
12426 /// [  5, 6,  7, zz, zz, zz, zz, zz]
12427 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
12428 /// [  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)12429 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
12430                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
12431                                int MaskOffset, const APInt &Zeroable,
12432                                const X86Subtarget &Subtarget) {
12433   int Size = Mask.size();
12434   unsigned SizeInBits = Size * ScalarSizeInBits;
12435 
12436   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
12437     for (int i = 0; i < Size; i += Scale)
12438       for (int j = 0; j < Shift; ++j)
12439         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
12440           return false;
12441 
12442     return true;
12443   };
12444 
12445   auto MatchShift = [&](int Shift, int Scale, bool Left) {
12446     for (int i = 0; i != Size; i += Scale) {
12447       unsigned Pos = Left ? i + Shift : i;
12448       unsigned Low = Left ? i : i + Shift;
12449       unsigned Len = Scale - Shift;
12450       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
12451         return -1;
12452     }
12453 
12454     int ShiftEltBits = ScalarSizeInBits * Scale;
12455     bool ByteShift = ShiftEltBits > 64;
12456     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
12457                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
12458     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
12459 
12460     // Normalize the scale for byte shifts to still produce an i64 element
12461     // type.
12462     Scale = ByteShift ? Scale / 2 : Scale;
12463 
12464     // We need to round trip through the appropriate type for the shift.
12465     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12466     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
12467                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
12468     return (int)ShiftAmt;
12469   };
12470 
12471   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
12472   // keep doubling the size of the integer elements up to that. We can
12473   // then shift the elements of the integer vector by whole multiples of
12474   // their width within the elements of the larger integer vector. Test each
12475   // multiple to see if we can find a match with the moved element indices
12476   // and that the shifted in elements are all zeroable.
12477   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
12478   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
12479     for (int Shift = 1; Shift != Scale; ++Shift)
12480       for (bool Left : {true, false})
12481         if (CheckZeros(Shift, Scale, Left)) {
12482           int ShiftAmt = MatchShift(Shift, Scale, Left);
12483           if (0 < ShiftAmt)
12484             return ShiftAmt;
12485         }
12486 
12487   // no match
12488   return -1;
12489 }
12490 
lowerShuffleAsShift(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)12491 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
12492                                    SDValue V2, ArrayRef<int> Mask,
12493                                    const APInt &Zeroable,
12494                                    const X86Subtarget &Subtarget,
12495                                    SelectionDAG &DAG) {
12496   int Size = Mask.size();
12497   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12498 
12499   MVT ShiftVT;
12500   SDValue V = V1;
12501   unsigned Opcode;
12502 
12503   // Try to match shuffle against V1 shift.
12504   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12505                                      Mask, 0, Zeroable, Subtarget);
12506 
12507   // If V1 failed, try to match shuffle against V2 shift.
12508   if (ShiftAmt < 0) {
12509     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12510                                    Mask, Size, Zeroable, Subtarget);
12511     V = V2;
12512   }
12513 
12514   if (ShiftAmt < 0)
12515     return SDValue();
12516 
12517   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
12518          "Illegal integer vector type");
12519   V = DAG.getBitcast(ShiftVT, V);
12520   V = DAG.getNode(Opcode, DL, ShiftVT, V,
12521                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
12522   return DAG.getBitcast(VT, V);
12523 }
12524 
12525 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
12526 // 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)12527 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
12528                                 ArrayRef<int> Mask, uint64_t &BitLen,
12529                                 uint64_t &BitIdx, const APInt &Zeroable) {
12530   int Size = Mask.size();
12531   int HalfSize = Size / 2;
12532   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12533   assert(!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask");
12534 
12535   // Upper half must be undefined.
12536   if (!isUndefUpperHalf(Mask))
12537     return false;
12538 
12539   // Determine the extraction length from the part of the
12540   // lower half that isn't zeroable.
12541   int Len = HalfSize;
12542   for (; Len > 0; --Len)
12543     if (!Zeroable[Len - 1])
12544       break;
12545   assert(Len > 0 && "Zeroable shuffle mask");
12546 
12547   // Attempt to match first Len sequential elements from the lower half.
12548   SDValue Src;
12549   int Idx = -1;
12550   for (int i = 0; i != Len; ++i) {
12551     int M = Mask[i];
12552     if (M == SM_SentinelUndef)
12553       continue;
12554     SDValue &V = (M < Size ? V1 : V2);
12555     M = M % Size;
12556 
12557     // The extracted elements must start at a valid index and all mask
12558     // elements must be in the lower half.
12559     if (i > M || M >= HalfSize)
12560       return false;
12561 
12562     if (Idx < 0 || (Src == V && Idx == (M - i))) {
12563       Src = V;
12564       Idx = M - i;
12565       continue;
12566     }
12567     return false;
12568   }
12569 
12570   if (!Src || Idx < 0)
12571     return false;
12572 
12573   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
12574   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12575   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12576   V1 = Src;
12577   return true;
12578 }
12579 
12580 // INSERTQ: Extract lowest Len elements from lower half of second source and
12581 // insert over first source, starting at Idx.
12582 // { 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)12583 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
12584                                   ArrayRef<int> Mask, uint64_t &BitLen,
12585                                   uint64_t &BitIdx) {
12586   int Size = Mask.size();
12587   int HalfSize = Size / 2;
12588   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12589 
12590   // Upper half must be undefined.
12591   if (!isUndefUpperHalf(Mask))
12592     return false;
12593 
12594   for (int Idx = 0; Idx != HalfSize; ++Idx) {
12595     SDValue Base;
12596 
12597     // Attempt to match first source from mask before insertion point.
12598     if (isUndefInRange(Mask, 0, Idx)) {
12599       /* EMPTY */
12600     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
12601       Base = V1;
12602     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
12603       Base = V2;
12604     } else {
12605       continue;
12606     }
12607 
12608     // Extend the extraction length looking to match both the insertion of
12609     // the second source and the remaining elements of the first.
12610     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12611       SDValue Insert;
12612       int Len = Hi - Idx;
12613 
12614       // Match insertion.
12615       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12616         Insert = V1;
12617       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12618         Insert = V2;
12619       } else {
12620         continue;
12621       }
12622 
12623       // Match the remaining elements of the lower half.
12624       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12625         /* EMPTY */
12626       } else if ((!Base || (Base == V1)) &&
12627                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12628         Base = V1;
12629       } else if ((!Base || (Base == V2)) &&
12630                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12631                                             Size + Hi)) {
12632         Base = V2;
12633       } else {
12634         continue;
12635       }
12636 
12637       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12638       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12639       V1 = Base;
12640       V2 = Insert;
12641       return true;
12642     }
12643   }
12644 
12645   return false;
12646 }
12647 
12648 /// 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)12649 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
12650                                      SDValue V2, ArrayRef<int> Mask,
12651                                      const APInt &Zeroable, SelectionDAG &DAG) {
12652   uint64_t BitLen, BitIdx;
12653   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12654     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12655                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
12656                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12657 
12658   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12659     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12660                        V2 ? V2 : DAG.getUNDEF(VT),
12661                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
12662                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12663 
12664   return SDValue();
12665 }
12666 
12667 /// Lower a vector shuffle as a zero or any extension.
12668 ///
12669 /// Given a specific number of elements, element bit width, and extension
12670 /// stride, produce either a zero or any extension based on the available
12671 /// features of the subtarget. The extended elements are consecutive and
12672 /// begin and can start from an offsetted element index in the input; to
12673 /// avoid excess shuffling the offset must either being in the bottom lane
12674 /// or at the start of a higher lane. All extended elements must be from
12675 /// 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)12676 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
12677     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
12678     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12679   assert(Scale > 1 && "Need a scale to extend.");
12680   int EltBits = VT.getScalarSizeInBits();
12681   int NumElements = VT.getVectorNumElements();
12682   int NumEltsPerLane = 128 / EltBits;
12683   int OffsetLane = Offset / NumEltsPerLane;
12684   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
12685          "Only 8, 16, and 32 bit elements can be extended.");
12686   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
12687   assert(0 <= Offset && "Extension offset must be positive.");
12688   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
12689          "Extension offset must be in the first lane or start an upper lane.");
12690 
12691   // Check that an index is in same lane as the base offset.
12692   auto SafeOffset = [&](int Idx) {
12693     return OffsetLane == (Idx / NumEltsPerLane);
12694   };
12695 
12696   // Shift along an input so that the offset base moves to the first element.
12697   auto ShuffleOffset = [&](SDValue V) {
12698     if (!Offset)
12699       return V;
12700 
12701     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12702     for (int i = 0; i * Scale < NumElements; ++i) {
12703       int SrcIdx = i + Offset;
12704       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
12705     }
12706     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
12707   };
12708 
12709   // Found a valid a/zext mask! Try various lowering strategies based on the
12710   // input type and available ISA extensions.
12711   if (Subtarget.hasSSE41()) {
12712     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
12713     // PUNPCK will catch this in a later shuffle match.
12714     if (Offset && Scale == 2 && VT.is128BitVector())
12715       return SDValue();
12716     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
12717                                  NumElements / Scale);
12718     InputV = ShuffleOffset(InputV);
12719     InputV = getExtendInVec(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND, DL,
12720                             ExtVT, InputV, DAG);
12721     return DAG.getBitcast(VT, InputV);
12722   }
12723 
12724   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
12725 
12726   // For any extends we can cheat for larger element sizes and use shuffle
12727   // instructions that can fold with a load and/or copy.
12728   if (AnyExt && EltBits == 32) {
12729     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
12730                          -1};
12731     return DAG.getBitcast(
12732         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12733                         DAG.getBitcast(MVT::v4i32, InputV),
12734                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
12735   }
12736   if (AnyExt && EltBits == 16 && Scale > 2) {
12737     int PSHUFDMask[4] = {Offset / 2, -1,
12738                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
12739     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
12740                          DAG.getBitcast(MVT::v4i32, InputV),
12741                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
12742     int PSHUFWMask[4] = {1, -1, -1, -1};
12743     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
12744     return DAG.getBitcast(
12745         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
12746                         DAG.getBitcast(MVT::v8i16, InputV),
12747                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
12748   }
12749 
12750   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
12751   // to 64-bits.
12752   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
12753     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
12754     assert(VT.is128BitVector() && "Unexpected vector width!");
12755 
12756     int LoIdx = Offset * EltBits;
12757     SDValue Lo = DAG.getBitcast(
12758         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12759                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12760                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
12761 
12762     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
12763       return DAG.getBitcast(VT, Lo);
12764 
12765     int HiIdx = (Offset + 1) * EltBits;
12766     SDValue Hi = DAG.getBitcast(
12767         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
12768                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
12769                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
12770     return DAG.getBitcast(VT,
12771                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
12772   }
12773 
12774   // If this would require more than 2 unpack instructions to expand, use
12775   // pshufb when available. We can only use more than 2 unpack instructions
12776   // when zero extending i8 elements which also makes it easier to use pshufb.
12777   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
12778     assert(NumElements == 16 && "Unexpected byte vector width!");
12779     SDValue PSHUFBMask[16];
12780     for (int i = 0; i < 16; ++i) {
12781       int Idx = Offset + (i / Scale);
12782       if ((i % Scale == 0 && SafeOffset(Idx))) {
12783         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
12784         continue;
12785       }
12786       PSHUFBMask[i] =
12787           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
12788     }
12789     InputV = DAG.getBitcast(MVT::v16i8, InputV);
12790     return DAG.getBitcast(
12791         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
12792                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
12793   }
12794 
12795   // If we are extending from an offset, ensure we start on a boundary that
12796   // we can unpack from.
12797   int AlignToUnpack = Offset % (NumElements / Scale);
12798   if (AlignToUnpack) {
12799     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
12800     for (int i = AlignToUnpack; i < NumElements; ++i)
12801       ShMask[i - AlignToUnpack] = i;
12802     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
12803     Offset -= AlignToUnpack;
12804   }
12805 
12806   // Otherwise emit a sequence of unpacks.
12807   do {
12808     unsigned UnpackLoHi = X86ISD::UNPCKL;
12809     if (Offset >= (NumElements / 2)) {
12810       UnpackLoHi = X86ISD::UNPCKH;
12811       Offset -= (NumElements / 2);
12812     }
12813 
12814     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
12815     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
12816                          : getZeroVector(InputVT, Subtarget, DAG, DL);
12817     InputV = DAG.getBitcast(InputVT, InputV);
12818     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
12819     Scale /= 2;
12820     EltBits *= 2;
12821     NumElements /= 2;
12822   } while (Scale > 1);
12823   return DAG.getBitcast(VT, InputV);
12824 }
12825 
12826 /// Try to lower a vector shuffle as a zero extension on any microarch.
12827 ///
12828 /// This routine will try to do everything in its power to cleverly lower
12829 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
12830 /// check for the profitability of this lowering,  it tries to aggressively
12831 /// match this pattern. It will use all of the micro-architectural details it
12832 /// can to emit an efficient lowering. It handles both blends with all-zero
12833 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
12834 /// masking out later).
12835 ///
12836 /// The reason we have dedicated lowering for zext-style shuffles is that they
12837 /// 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)12838 static SDValue lowerShuffleAsZeroOrAnyExtend(
12839     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12840     const APInt &Zeroable, const X86Subtarget &Subtarget,
12841     SelectionDAG &DAG) {
12842   int Bits = VT.getSizeInBits();
12843   int NumLanes = Bits / 128;
12844   int NumElements = VT.getVectorNumElements();
12845   int NumEltsPerLane = NumElements / NumLanes;
12846   assert(VT.getScalarSizeInBits() <= 32 &&
12847          "Exceeds 32-bit integer zero extension limit");
12848   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
12849 
12850   // Define a helper function to check a particular ext-scale and lower to it if
12851   // valid.
12852   auto Lower = [&](int Scale) -> SDValue {
12853     SDValue InputV;
12854     bool AnyExt = true;
12855     int Offset = 0;
12856     int Matches = 0;
12857     for (int i = 0; i < NumElements; ++i) {
12858       int M = Mask[i];
12859       if (M < 0)
12860         continue; // Valid anywhere but doesn't tell us anything.
12861       if (i % Scale != 0) {
12862         // Each of the extended elements need to be zeroable.
12863         if (!Zeroable[i])
12864           return SDValue();
12865 
12866         // We no longer are in the anyext case.
12867         AnyExt = false;
12868         continue;
12869       }
12870 
12871       // Each of the base elements needs to be consecutive indices into the
12872       // same input vector.
12873       SDValue V = M < NumElements ? V1 : V2;
12874       M = M % NumElements;
12875       if (!InputV) {
12876         InputV = V;
12877         Offset = M - (i / Scale);
12878       } else if (InputV != V)
12879         return SDValue(); // Flip-flopping inputs.
12880 
12881       // Offset must start in the lowest 128-bit lane or at the start of an
12882       // upper lane.
12883       // FIXME: Is it ever worth allowing a negative base offset?
12884       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
12885             (Offset % NumEltsPerLane) == 0))
12886         return SDValue();
12887 
12888       // If we are offsetting, all referenced entries must come from the same
12889       // lane.
12890       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
12891         return SDValue();
12892 
12893       if ((M % NumElements) != (Offset + (i / Scale)))
12894         return SDValue(); // Non-consecutive strided elements.
12895       Matches++;
12896     }
12897 
12898     // If we fail to find an input, we have a zero-shuffle which should always
12899     // have already been handled.
12900     // FIXME: Maybe handle this here in case during blending we end up with one?
12901     if (!InputV)
12902       return SDValue();
12903 
12904     // If we are offsetting, don't extend if we only match a single input, we
12905     // can always do better by using a basic PSHUF or PUNPCK.
12906     if (Offset != 0 && Matches < 2)
12907       return SDValue();
12908 
12909     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
12910                                                  InputV, Mask, Subtarget, DAG);
12911   };
12912 
12913   // The widest scale possible for extending is to a 64-bit integer.
12914   assert(Bits % 64 == 0 &&
12915          "The number of bits in a vector must be divisible by 64 on x86!");
12916   int NumExtElements = Bits / 64;
12917 
12918   // Each iteration, try extending the elements half as much, but into twice as
12919   // many elements.
12920   for (; NumExtElements < NumElements; NumExtElements *= 2) {
12921     assert(NumElements % NumExtElements == 0 &&
12922            "The input vector size must be divisible by the extended size.");
12923     if (SDValue V = Lower(NumElements / NumExtElements))
12924       return V;
12925   }
12926 
12927   // General extends failed, but 128-bit vectors may be able to use MOVQ.
12928   if (Bits != 128)
12929     return SDValue();
12930 
12931   // Returns one of the source operands if the shuffle can be reduced to a
12932   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
12933   auto CanZExtLowHalf = [&]() {
12934     for (int i = NumElements / 2; i != NumElements; ++i)
12935       if (!Zeroable[i])
12936         return SDValue();
12937     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
12938       return V1;
12939     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
12940       return V2;
12941     return SDValue();
12942   };
12943 
12944   if (SDValue V = CanZExtLowHalf()) {
12945     V = DAG.getBitcast(MVT::v2i64, V);
12946     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
12947     return DAG.getBitcast(VT, V);
12948   }
12949 
12950   // No viable ext lowering found.
12951   return SDValue();
12952 }
12953 
12954 /// Try to get a scalar value for a specific element of a vector.
12955 ///
12956 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
getScalarValueForVectorElement(SDValue V,int Idx,SelectionDAG & DAG)12957 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
12958                                               SelectionDAG &DAG) {
12959   MVT VT = V.getSimpleValueType();
12960   MVT EltVT = VT.getVectorElementType();
12961   V = peekThroughBitcasts(V);
12962 
12963   // If the bitcasts shift the element size, we can't extract an equivalent
12964   // element from it.
12965   MVT NewVT = V.getSimpleValueType();
12966   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
12967     return SDValue();
12968 
12969   if (V.getOpcode() == ISD::BUILD_VECTOR ||
12970       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
12971     // Ensure the scalar operand is the same size as the destination.
12972     // FIXME: Add support for scalar truncation where possible.
12973     SDValue S = V.getOperand(Idx);
12974     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
12975       return DAG.getBitcast(EltVT, S);
12976   }
12977 
12978   return SDValue();
12979 }
12980 
12981 /// Helper to test for a load that can be folded with x86 shuffles.
12982 ///
12983 /// This is particularly important because the set of instructions varies
12984 /// significantly based on whether the operand is a load or not.
isShuffleFoldableLoad(SDValue V)12985 static bool isShuffleFoldableLoad(SDValue V) {
12986   V = peekThroughBitcasts(V);
12987   return ISD::isNON_EXTLoad(V.getNode());
12988 }
12989 
12990 /// Try to lower insertion of a single element into a zero vector.
12991 ///
12992 /// This is a common pattern that we have especially efficient patterns to lower
12993 /// 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)12994 static SDValue lowerShuffleAsElementInsertion(
12995     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12996     const APInt &Zeroable, const X86Subtarget &Subtarget,
12997     SelectionDAG &DAG) {
12998   MVT ExtVT = VT;
12999   MVT EltVT = VT.getVectorElementType();
13000 
13001   int V2Index =
13002       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13003       Mask.begin();
13004   bool IsV1Zeroable = true;
13005   for (int i = 0, Size = Mask.size(); i < Size; ++i)
13006     if (i != V2Index && !Zeroable[i]) {
13007       IsV1Zeroable = false;
13008       break;
13009     }
13010 
13011   // Check for a single input from a SCALAR_TO_VECTOR node.
13012   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13013   // all the smarts here sunk into that routine. However, the current
13014   // lowering of BUILD_VECTOR makes that nearly impossible until the old
13015   // vector shuffle lowering is dead.
13016   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13017                                                DAG);
13018   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13019     // We need to zext the scalar if it is smaller than an i32.
13020     V2S = DAG.getBitcast(EltVT, V2S);
13021     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
13022       // Using zext to expand a narrow element won't work for non-zero
13023       // insertions.
13024       if (!IsV1Zeroable)
13025         return SDValue();
13026 
13027       // Zero-extend directly to i32.
13028       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13029       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13030     }
13031     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13032   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13033              EltVT == MVT::i16) {
13034     // Either not inserting from the low element of the input or the input
13035     // element size is too small to use VZEXT_MOVL to clear the high bits.
13036     return SDValue();
13037   }
13038 
13039   if (!IsV1Zeroable) {
13040     // If V1 can't be treated as a zero vector we have fewer options to lower
13041     // this. We can't support integer vectors or non-zero targets cheaply, and
13042     // the V1 elements can't be permuted in any way.
13043     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
13044     if (!VT.isFloatingPoint() || V2Index != 0)
13045       return SDValue();
13046     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
13047     V1Mask[V2Index] = -1;
13048     if (!isNoopShuffleMask(V1Mask))
13049       return SDValue();
13050     if (!VT.is128BitVector())
13051       return SDValue();
13052 
13053     // Otherwise, use MOVSD or MOVSS.
13054     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
13055            "Only two types of floating point element types to handle!");
13056     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
13057                        ExtVT, V1, V2);
13058   }
13059 
13060   // This lowering only works for the low element with floating point vectors.
13061   if (VT.isFloatingPoint() && V2Index != 0)
13062     return SDValue();
13063 
13064   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13065   if (ExtVT != VT)
13066     V2 = DAG.getBitcast(VT, V2);
13067 
13068   if (V2Index != 0) {
13069     // If we have 4 or fewer lanes we can cheaply shuffle the element into
13070     // the desired position. Otherwise it is more efficient to do a vector
13071     // shift left. We know that we can do a vector shift left because all
13072     // the inputs are zero.
13073     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
13074       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13075       V2Shuffle[V2Index] = 0;
13076       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13077     } else {
13078       V2 = DAG.getBitcast(MVT::v16i8, V2);
13079       V2 = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13080                        DAG.getTargetConstant(
13081                            V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
13082       V2 = DAG.getBitcast(VT, V2);
13083     }
13084   }
13085   return V2;
13086 }
13087 
13088 /// Try to lower broadcast of a single - truncated - integer element,
13089 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13090 ///
13091 /// This assumes we have AVX2.
lowerShuffleAsTruncBroadcast(const SDLoc & DL,MVT VT,SDValue V0,int BroadcastIdx,const X86Subtarget & Subtarget,SelectionDAG & DAG)13092 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
13093                                             int BroadcastIdx,
13094                                             const X86Subtarget &Subtarget,
13095                                             SelectionDAG &DAG) {
13096   assert(Subtarget.hasAVX2() &&
13097          "We can only lower integer broadcasts with AVX2!");
13098 
13099   MVT EltVT = VT.getVectorElementType();
13100   MVT V0VT = V0.getSimpleValueType();
13101 
13102   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
13103   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
13104 
13105   MVT V0EltVT = V0VT.getVectorElementType();
13106   if (!V0EltVT.isInteger())
13107     return SDValue();
13108 
13109   const unsigned EltSize = EltVT.getSizeInBits();
13110   const unsigned V0EltSize = V0EltVT.getSizeInBits();
13111 
13112   // This is only a truncation if the original element type is larger.
13113   if (V0EltSize <= EltSize)
13114     return SDValue();
13115 
13116   assert(((V0EltSize % EltSize) == 0) &&
13117          "Scalar type sizes must all be powers of 2 on x86!");
13118 
13119   const unsigned V0Opc = V0.getOpcode();
13120   const unsigned Scale = V0EltSize / EltSize;
13121   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
13122 
13123   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
13124       V0Opc != ISD::BUILD_VECTOR)
13125     return SDValue();
13126 
13127   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
13128 
13129   // If we're extracting non-least-significant bits, shift so we can truncate.
13130   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
13131   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
13132   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
13133   if (const int OffsetIdx = BroadcastIdx % Scale)
13134     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
13135                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
13136 
13137   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
13138                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
13139 }
13140 
13141 /// Test whether this can be lowered with a single SHUFPS instruction.
13142 ///
13143 /// This is used to disable more specialized lowerings when the shufps lowering
13144 /// will happen to be efficient.
isSingleSHUFPSMask(ArrayRef<int> Mask)13145 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
13146   // This routine only handles 128-bit shufps.
13147   assert(Mask.size() == 4 && "Unsupported mask size!");
13148   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
13149   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
13150   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
13151   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
13152 
13153   // To lower with a single SHUFPS we need to have the low half and high half
13154   // each requiring a single input.
13155   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
13156     return false;
13157   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
13158     return false;
13159 
13160   return true;
13161 }
13162 
13163 /// If we are extracting two 128-bit halves of a vector and shuffling the
13164 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
13165 /// multi-shuffle lowering.
lowerShuffleOfExtractsAsVperm(const SDLoc & DL,SDValue N0,SDValue N1,ArrayRef<int> Mask,SelectionDAG & DAG)13166 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
13167                                              SDValue N1, ArrayRef<int> Mask,
13168                                              SelectionDAG &DAG) {
13169   MVT VT = N0.getSimpleValueType();
13170   assert((VT.is128BitVector() &&
13171           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
13172          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
13173 
13174   // Check that both sources are extracts of the same source vector.
13175   if (!N0.hasOneUse() || !N1.hasOneUse() ||
13176       N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13177       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13178       N0.getOperand(0) != N1.getOperand(0))
13179     return SDValue();
13180 
13181   SDValue WideVec = N0.getOperand(0);
13182   MVT WideVT = WideVec.getSimpleValueType();
13183   if (!WideVT.is256BitVector())
13184     return SDValue();
13185 
13186   // Match extracts of each half of the wide source vector. Commute the shuffle
13187   // if the extract of the low half is N1.
13188   unsigned NumElts = VT.getVectorNumElements();
13189   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
13190   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
13191   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
13192   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
13193     ShuffleVectorSDNode::commuteMask(NewMask);
13194   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
13195     return SDValue();
13196 
13197   // Final bailout: if the mask is simple, we are better off using an extract
13198   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
13199   // because that avoids a constant load from memory.
13200   if (NumElts == 4 &&
13201       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask)))
13202     return SDValue();
13203 
13204   // Extend the shuffle mask with undef elements.
13205   NewMask.append(NumElts, -1);
13206 
13207   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
13208   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
13209                                       NewMask);
13210   // This is free: ymm -> xmm.
13211   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
13212                      DAG.getIntPtrConstant(0, DL));
13213 }
13214 
13215 /// Try to lower broadcast of a single element.
13216 ///
13217 /// For convenience, this code also bundles all of the subtarget feature set
13218 /// filtering. While a little annoying to re-dispatch on type here, there isn't
13219 /// 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)13220 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
13221                                        SDValue V2, ArrayRef<int> Mask,
13222                                        const X86Subtarget &Subtarget,
13223                                        SelectionDAG &DAG) {
13224   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
13225         (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
13226         (Subtarget.hasAVX2() && VT.isInteger())))
13227     return SDValue();
13228 
13229   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
13230   // we can only broadcast from a register with AVX2.
13231   unsigned NumEltBits = VT.getScalarSizeInBits();
13232   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
13233                         ? X86ISD::MOVDDUP
13234                         : X86ISD::VBROADCAST;
13235   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
13236 
13237   // Check that the mask is a broadcast.
13238   int BroadcastIdx = getSplatIndex(Mask);
13239   if (BroadcastIdx < 0)
13240     return SDValue();
13241   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
13242                                             "a sorted mask where the broadcast "
13243                                             "comes from V1.");
13244 
13245   // Go up the chain of (vector) values to find a scalar load that we can
13246   // combine with the broadcast.
13247   // TODO: Combine this logic with findEltLoadSrc() used by
13248   //       EltsFromConsecutiveLoads().
13249   int BitOffset = BroadcastIdx * NumEltBits;
13250   SDValue V = V1;
13251   for (;;) {
13252     switch (V.getOpcode()) {
13253     case ISD::BITCAST: {
13254       V = V.getOperand(0);
13255       continue;
13256     }
13257     case ISD::CONCAT_VECTORS: {
13258       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
13259       int OpIdx = BitOffset / OpBitWidth;
13260       V = V.getOperand(OpIdx);
13261       BitOffset %= OpBitWidth;
13262       continue;
13263     }
13264     case ISD::EXTRACT_SUBVECTOR: {
13265       // The extraction index adds to the existing offset.
13266       unsigned EltBitWidth = V.getScalarValueSizeInBits();
13267       unsigned Idx = V.getConstantOperandVal(1);
13268       unsigned BeginOffset = Idx * EltBitWidth;
13269       BitOffset += BeginOffset;
13270       V = V.getOperand(0);
13271       continue;
13272     }
13273     case ISD::INSERT_SUBVECTOR: {
13274       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
13275       int EltBitWidth = VOuter.getScalarValueSizeInBits();
13276       int Idx = (int)V.getConstantOperandVal(2);
13277       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
13278       int BeginOffset = Idx * EltBitWidth;
13279       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
13280       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
13281         BitOffset -= BeginOffset;
13282         V = VInner;
13283       } else {
13284         V = VOuter;
13285       }
13286       continue;
13287     }
13288     }
13289     break;
13290   }
13291   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
13292   BroadcastIdx = BitOffset / NumEltBits;
13293 
13294   // Do we need to bitcast the source to retrieve the original broadcast index?
13295   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
13296 
13297   // Check if this is a broadcast of a scalar. We special case lowering
13298   // for scalars so that we can more effectively fold with loads.
13299   // If the original value has a larger element type than the shuffle, the
13300   // broadcast element is in essence truncated. Make that explicit to ease
13301   // folding.
13302   if (BitCastSrc && VT.isInteger())
13303     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
13304             DL, VT, V, BroadcastIdx, Subtarget, DAG))
13305       return TruncBroadcast;
13306 
13307   // Also check the simpler case, where we can directly reuse the scalar.
13308   if (!BitCastSrc &&
13309       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
13310        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
13311     V = V.getOperand(BroadcastIdx);
13312 
13313     // If we can't broadcast from a register, check that the input is a load.
13314     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
13315       return SDValue();
13316   } else if (ISD::isNormalLoad(V.getNode()) &&
13317              cast<LoadSDNode>(V)->isSimple()) {
13318     // We do not check for one-use of the vector load because a broadcast load
13319     // is expected to be a win for code size, register pressure, and possibly
13320     // uops even if the original vector load is not eliminated.
13321 
13322     // Reduce the vector load and shuffle to a broadcasted scalar load.
13323     LoadSDNode *Ld = cast<LoadSDNode>(V);
13324     SDValue BaseAddr = Ld->getOperand(1);
13325     MVT SVT = VT.getScalarType();
13326     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
13327     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
13328     SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
13329 
13330     // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
13331     // than MOVDDUP.
13332     // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
13333     if (Opcode == X86ISD::VBROADCAST) {
13334       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
13335       SDValue Ops[] = {Ld->getChain(), NewAddr};
13336       V = DAG.getMemIntrinsicNode(
13337           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
13338           DAG.getMachineFunction().getMachineMemOperand(
13339               Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13340       DAG.makeEquivalentMemoryOrdering(Ld, V);
13341       return DAG.getBitcast(VT, V);
13342     }
13343     assert(SVT == MVT::f64 && "Unexpected VT!");
13344     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
13345                     DAG.getMachineFunction().getMachineMemOperand(
13346                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13347     DAG.makeEquivalentMemoryOrdering(Ld, V);
13348   } else if (!BroadcastFromReg) {
13349     // We can't broadcast from a vector register.
13350     return SDValue();
13351   } else if (BitOffset != 0) {
13352     // We can only broadcast from the zero-element of a vector register,
13353     // but it can be advantageous to broadcast from the zero-element of a
13354     // subvector.
13355     if (!VT.is256BitVector() && !VT.is512BitVector())
13356       return SDValue();
13357 
13358     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
13359     if (VT == MVT::v4f64 || VT == MVT::v4i64)
13360       return SDValue();
13361 
13362     // Only broadcast the zero-element of a 128-bit subvector.
13363     if ((BitOffset % 128) != 0)
13364       return SDValue();
13365 
13366     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13367            "Unexpected bit-offset");
13368     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
13369            "Unexpected vector size");
13370     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
13371     V = extract128BitVector(V, ExtractIdx, DAG, DL);
13372   }
13373 
13374   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector())
13375     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
13376                     DAG.getBitcast(MVT::f64, V));
13377 
13378   // If this is a scalar, do the broadcast on this type and bitcast.
13379   if (!V.getValueType().isVector()) {
13380     assert(V.getScalarValueSizeInBits() == NumEltBits &&
13381            "Unexpected scalar size");
13382     MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
13383                                        VT.getVectorNumElements());
13384     return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
13385   }
13386 
13387   // We only support broadcasting from 128-bit vectors to minimize the
13388   // number of patterns we need to deal with in isel. So extract down to
13389   // 128-bits, removing as many bitcasts as possible.
13390   if (V.getValueSizeInBits() > 128)
13391     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
13392 
13393   // Otherwise cast V to a vector with the same element type as VT, but
13394   // possibly narrower than VT. Then perform the broadcast.
13395   unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
13396   MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
13397   return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
13398 }
13399 
13400 // Check for whether we can use INSERTPS to perform the shuffle. We only use
13401 // INSERTPS when the V1 elements are already in the correct locations
13402 // because otherwise we can just always use two SHUFPS instructions which
13403 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
13404 // perform INSERTPS if a single V1 element is out of place and all V2
13405 // elements are zeroable.
matchShuffleAsInsertPS(SDValue & V1,SDValue & V2,unsigned & InsertPSMask,const APInt & Zeroable,ArrayRef<int> Mask,SelectionDAG & DAG)13406 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
13407                                    unsigned &InsertPSMask,
13408                                    const APInt &Zeroable,
13409                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
13410   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
13411   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
13412   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13413 
13414   // Attempt to match INSERTPS with one element from VA or VB being
13415   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
13416   // are updated.
13417   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
13418                              ArrayRef<int> CandidateMask) {
13419     unsigned ZMask = 0;
13420     int VADstIndex = -1;
13421     int VBDstIndex = -1;
13422     bool VAUsedInPlace = false;
13423 
13424     for (int i = 0; i < 4; ++i) {
13425       // Synthesize a zero mask from the zeroable elements (includes undefs).
13426       if (Zeroable[i]) {
13427         ZMask |= 1 << i;
13428         continue;
13429       }
13430 
13431       // Flag if we use any VA inputs in place.
13432       if (i == CandidateMask[i]) {
13433         VAUsedInPlace = true;
13434         continue;
13435       }
13436 
13437       // We can only insert a single non-zeroable element.
13438       if (VADstIndex >= 0 || VBDstIndex >= 0)
13439         return false;
13440 
13441       if (CandidateMask[i] < 4) {
13442         // VA input out of place for insertion.
13443         VADstIndex = i;
13444       } else {
13445         // VB input for insertion.
13446         VBDstIndex = i;
13447       }
13448     }
13449 
13450     // Don't bother if we have no (non-zeroable) element for insertion.
13451     if (VADstIndex < 0 && VBDstIndex < 0)
13452       return false;
13453 
13454     // Determine element insertion src/dst indices. The src index is from the
13455     // start of the inserted vector, not the start of the concatenated vector.
13456     unsigned VBSrcIndex = 0;
13457     if (VADstIndex >= 0) {
13458       // If we have a VA input out of place, we use VA as the V2 element
13459       // insertion and don't use the original V2 at all.
13460       VBSrcIndex = CandidateMask[VADstIndex];
13461       VBDstIndex = VADstIndex;
13462       VB = VA;
13463     } else {
13464       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
13465     }
13466 
13467     // If no V1 inputs are used in place, then the result is created only from
13468     // the zero mask and the V2 insertion - so remove V1 dependency.
13469     if (!VAUsedInPlace)
13470       VA = DAG.getUNDEF(MVT::v4f32);
13471 
13472     // Update V1, V2 and InsertPSMask accordingly.
13473     V1 = VA;
13474     V2 = VB;
13475 
13476     // Insert the V2 element into the desired position.
13477     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
13478     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
13479     return true;
13480   };
13481 
13482   if (matchAsInsertPS(V1, V2, Mask))
13483     return true;
13484 
13485   // Commute and try again.
13486   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
13487   ShuffleVectorSDNode::commuteMask(CommutedMask);
13488   if (matchAsInsertPS(V2, V1, CommutedMask))
13489     return true;
13490 
13491   return false;
13492 }
13493 
lowerShuffleAsInsertPS(const SDLoc & DL,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)13494 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
13495                                       ArrayRef<int> Mask, const APInt &Zeroable,
13496                                       SelectionDAG &DAG) {
13497   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13498   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13499 
13500   // Attempt to match the insertps pattern.
13501   unsigned InsertPSMask;
13502   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
13503     return SDValue();
13504 
13505   // Insert the V2 element into the desired position.
13506   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
13507                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
13508 }
13509 
13510 /// Try to lower a shuffle as a permute of the inputs followed by an
13511 /// UNPCK instruction.
13512 ///
13513 /// This specifically targets cases where we end up with alternating between
13514 /// the two inputs, and so can permute them into something that feeds a single
13515 /// UNPCK instruction. Note that this routine only targets integer vectors
13516 /// because for floating point vectors we have a generalized SHUFPS lowering
13517 /// strategy that handles everything that doesn't *exactly* match an unpack,
13518 /// making this clever lowering unnecessary.
lowerShuffleAsPermuteAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)13519 static SDValue lowerShuffleAsPermuteAndUnpack(
13520     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13521     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13522   assert(!VT.isFloatingPoint() &&
13523          "This routine only supports integer vectors.");
13524   assert(VT.is128BitVector() &&
13525          "This routine only works on 128-bit vectors.");
13526   assert(!V2.isUndef() &&
13527          "This routine should only be used when blending two inputs.");
13528   assert(Mask.size() >= 2 && "Single element masks are invalid.");
13529 
13530   int Size = Mask.size();
13531 
13532   int NumLoInputs =
13533       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
13534   int NumHiInputs =
13535       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
13536 
13537   bool UnpackLo = NumLoInputs >= NumHiInputs;
13538 
13539   auto TryUnpack = [&](int ScalarSize, int Scale) {
13540     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
13541     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
13542 
13543     for (int i = 0; i < Size; ++i) {
13544       if (Mask[i] < 0)
13545         continue;
13546 
13547       // Each element of the unpack contains Scale elements from this mask.
13548       int UnpackIdx = i / Scale;
13549 
13550       // We only handle the case where V1 feeds the first slots of the unpack.
13551       // We rely on canonicalization to ensure this is the case.
13552       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
13553         return SDValue();
13554 
13555       // Setup the mask for this input. The indexing is tricky as we have to
13556       // handle the unpack stride.
13557       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
13558       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
13559           Mask[i] % Size;
13560     }
13561 
13562     // If we will have to shuffle both inputs to use the unpack, check whether
13563     // we can just unpack first and shuffle the result. If so, skip this unpack.
13564     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
13565         !isNoopShuffleMask(V2Mask))
13566       return SDValue();
13567 
13568     // Shuffle the inputs into place.
13569     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
13570     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
13571 
13572     // Cast the inputs to the type we will use to unpack them.
13573     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
13574     V1 = DAG.getBitcast(UnpackVT, V1);
13575     V2 = DAG.getBitcast(UnpackVT, V2);
13576 
13577     // Unpack the inputs and cast the result back to the desired type.
13578     return DAG.getBitcast(
13579         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
13580                         UnpackVT, V1, V2));
13581   };
13582 
13583   // We try each unpack from the largest to the smallest to try and find one
13584   // that fits this mask.
13585   int OrigScalarSize = VT.getScalarSizeInBits();
13586   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
13587     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
13588       return Unpack;
13589 
13590   // If we're shuffling with a zero vector then we're better off not doing
13591   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
13592   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
13593       ISD::isBuildVectorAllZeros(V2.getNode()))
13594     return SDValue();
13595 
13596   // If none of the unpack-rooted lowerings worked (or were profitable) try an
13597   // initial unpack.
13598   if (NumLoInputs == 0 || NumHiInputs == 0) {
13599     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
13600            "We have to have *some* inputs!");
13601     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
13602 
13603     // FIXME: We could consider the total complexity of the permute of each
13604     // possible unpacking. Or at the least we should consider how many
13605     // half-crossings are created.
13606     // FIXME: We could consider commuting the unpacks.
13607 
13608     SmallVector<int, 32> PermMask((unsigned)Size, -1);
13609     for (int i = 0; i < Size; ++i) {
13610       if (Mask[i] < 0)
13611         continue;
13612 
13613       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
13614 
13615       PermMask[i] =
13616           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
13617     }
13618     return DAG.getVectorShuffle(
13619         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
13620                             DL, VT, V1, V2),
13621         DAG.getUNDEF(VT), PermMask);
13622   }
13623 
13624   return SDValue();
13625 }
13626 
13627 /// Handle lowering of 2-lane 64-bit floating point shuffles.
13628 ///
13629 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
13630 /// support for floating point shuffles but not integer shuffles. These
13631 /// instructions will incur a domain crossing penalty on some chips though so
13632 /// it is better to avoid lowering through this for integer vectors where
13633 /// possible.
lowerV2F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13634 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13635                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13636                                  const X86Subtarget &Subtarget,
13637                                  SelectionDAG &DAG) {
13638   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13639   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13640   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13641 
13642   if (V2.isUndef()) {
13643     // Check for being able to broadcast a single element.
13644     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
13645                                                     Mask, Subtarget, DAG))
13646       return Broadcast;
13647 
13648     // Straight shuffle of a single input vector. Simulate this by using the
13649     // single input as both of the "inputs" to this instruction..
13650     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
13651 
13652     if (Subtarget.hasAVX()) {
13653       // If we have AVX, we can use VPERMILPS which will allow folding a load
13654       // into the shuffle.
13655       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13656                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13657     }
13658 
13659     return DAG.getNode(
13660         X86ISD::SHUFP, DL, MVT::v2f64,
13661         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13662         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13663         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13664   }
13665   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13666   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13667   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13668   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13669 
13670   if (Subtarget.hasAVX2())
13671     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13672       return Extract;
13673 
13674   // When loading a scalar and then shuffling it into a vector we can often do
13675   // the insertion cheaply.
13676   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13677           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13678     return Insertion;
13679   // Try inverting the insertion since for v2 masks it is easy to do and we
13680   // can't reliably sort the mask one way or the other.
13681   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
13682                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
13683   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13684           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13685     return Insertion;
13686 
13687   // Try to use one of the special instruction patterns to handle two common
13688   // blend patterns if a zero-blend above didn't work.
13689   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
13690       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
13691     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
13692       // We can either use a special instruction to load over the low double or
13693       // to move just the low double.
13694       return DAG.getNode(
13695           X86ISD::MOVSD, DL, MVT::v2f64, V2,
13696           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
13697 
13698   if (Subtarget.hasSSE41())
13699     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
13700                                             Zeroable, Subtarget, DAG))
13701       return Blend;
13702 
13703   // Use dedicated unpack instructions for masks that match their pattern.
13704   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
13705     return V;
13706 
13707   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
13708   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
13709                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13710 }
13711 
13712 /// Handle lowering of 2-lane 64-bit integer shuffles.
13713 ///
13714 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
13715 /// the integer unit to minimize domain crossing penalties. However, for blends
13716 /// it falls back to the floating point shuffle operation with appropriate bit
13717 /// casting.
lowerV2I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13718 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13719                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13720                                  const X86Subtarget &Subtarget,
13721                                  SelectionDAG &DAG) {
13722   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13723   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
13724   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13725 
13726   if (V2.isUndef()) {
13727     // Check for being able to broadcast a single element.
13728     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
13729                                                     Mask, Subtarget, DAG))
13730       return Broadcast;
13731 
13732     // Straight shuffle of a single input vector. For everything from SSE2
13733     // onward this has a single fast instruction with no scary immediates.
13734     // We have to map the mask as it is actually a v4i32 shuffle instruction.
13735     V1 = DAG.getBitcast(MVT::v4i32, V1);
13736     int WidenedMask[4] = {
13737         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
13738         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
13739     return DAG.getBitcast(
13740         MVT::v2i64,
13741         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
13742                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
13743   }
13744   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
13745   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
13746   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
13747   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
13748 
13749   if (Subtarget.hasAVX2())
13750     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13751       return Extract;
13752 
13753   // Try to use shift instructions.
13754   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
13755                                           Zeroable, Subtarget, DAG))
13756     return Shift;
13757 
13758   // When loading a scalar and then shuffling it into a vector we can often do
13759   // the insertion cheaply.
13760   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13761           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
13762     return Insertion;
13763   // Try inverting the insertion since for v2 masks it is easy to do and we
13764   // can't reliably sort the mask one way or the other.
13765   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
13766   if (SDValue Insertion = lowerShuffleAsElementInsertion(
13767           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
13768     return Insertion;
13769 
13770   // We have different paths for blend lowering, but they all must use the
13771   // *exact* same predicate.
13772   bool IsBlendSupported = Subtarget.hasSSE41();
13773   if (IsBlendSupported)
13774     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
13775                                             Zeroable, Subtarget, DAG))
13776       return Blend;
13777 
13778   // Use dedicated unpack instructions for masks that match their pattern.
13779   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
13780     return V;
13781 
13782   // Try to use byte rotation instructions.
13783   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
13784   if (Subtarget.hasSSSE3()) {
13785     if (Subtarget.hasVLX())
13786       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
13787                                                 Subtarget, DAG))
13788         return Rotate;
13789 
13790     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
13791                                                   Subtarget, DAG))
13792       return Rotate;
13793   }
13794 
13795   // If we have direct support for blends, we should lower by decomposing into
13796   // a permute. That will be faster than the domain cross.
13797   if (IsBlendSupported)
13798     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2, Mask,
13799                                                 Subtarget, DAG);
13800 
13801   // We implement this with SHUFPD which is pretty lame because it will likely
13802   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
13803   // However, all the alternatives are still more cycles and newer chips don't
13804   // have this problem. It would be really nice if x86 had better shuffles here.
13805   V1 = DAG.getBitcast(MVT::v2f64, V1);
13806   V2 = DAG.getBitcast(MVT::v2f64, V2);
13807   return DAG.getBitcast(MVT::v2i64,
13808                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
13809 }
13810 
13811 /// Lower a vector shuffle using the SHUFPS instruction.
13812 ///
13813 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
13814 /// It makes no assumptions about whether this is the *best* lowering, it simply
13815 /// uses it.
lowerShuffleWithSHUFPS(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)13816 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
13817                                       ArrayRef<int> Mask, SDValue V1,
13818                                       SDValue V2, SelectionDAG &DAG) {
13819   SDValue LowV = V1, HighV = V2;
13820   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
13821   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13822 
13823   if (NumV2Elements == 1) {
13824     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
13825 
13826     // Compute the index adjacent to V2Index and in the same half by toggling
13827     // the low bit.
13828     int V2AdjIndex = V2Index ^ 1;
13829 
13830     if (Mask[V2AdjIndex] < 0) {
13831       // Handles all the cases where we have a single V2 element and an undef.
13832       // This will only ever happen in the high lanes because we commute the
13833       // vector otherwise.
13834       if (V2Index < 2)
13835         std::swap(LowV, HighV);
13836       NewMask[V2Index] -= 4;
13837     } else {
13838       // Handle the case where the V2 element ends up adjacent to a V1 element.
13839       // To make this work, blend them together as the first step.
13840       int V1Index = V2AdjIndex;
13841       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
13842       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
13843                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13844 
13845       // Now proceed to reconstruct the final blend as we have the necessary
13846       // high or low half formed.
13847       if (V2Index < 2) {
13848         LowV = V2;
13849         HighV = V1;
13850       } else {
13851         HighV = V2;
13852       }
13853       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
13854       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
13855     }
13856   } else if (NumV2Elements == 2) {
13857     if (Mask[0] < 4 && Mask[1] < 4) {
13858       // Handle the easy case where we have V1 in the low lanes and V2 in the
13859       // high lanes.
13860       NewMask[2] -= 4;
13861       NewMask[3] -= 4;
13862     } else if (Mask[2] < 4 && Mask[3] < 4) {
13863       // We also handle the reversed case because this utility may get called
13864       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
13865       // arrange things in the right direction.
13866       NewMask[0] -= 4;
13867       NewMask[1] -= 4;
13868       HighV = V1;
13869       LowV = V2;
13870     } else {
13871       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
13872       // trying to place elements directly, just blend them and set up the final
13873       // shuffle to place them.
13874 
13875       // The first two blend mask elements are for V1, the second two are for
13876       // V2.
13877       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
13878                           Mask[2] < 4 ? Mask[2] : Mask[3],
13879                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
13880                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
13881       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
13882                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
13883 
13884       // Now we do a normal shuffle of V1 by giving V1 as both operands to
13885       // a blend.
13886       LowV = HighV = V1;
13887       NewMask[0] = Mask[0] < 4 ? 0 : 2;
13888       NewMask[1] = Mask[0] < 4 ? 2 : 0;
13889       NewMask[2] = Mask[2] < 4 ? 1 : 3;
13890       NewMask[3] = Mask[2] < 4 ? 3 : 1;
13891     }
13892   }
13893   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
13894                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
13895 }
13896 
13897 /// Lower 4-lane 32-bit floating point shuffles.
13898 ///
13899 /// Uses instructions exclusively from the floating point unit to minimize
13900 /// domain crossing penalties, as these are sufficient to implement all v4f32
13901 /// shuffles.
lowerV4F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)13902 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13903                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13904                                  const X86Subtarget &Subtarget,
13905                                  SelectionDAG &DAG) {
13906   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13907   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13908   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13909 
13910   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
13911 
13912   if (NumV2Elements == 0) {
13913     // Check for being able to broadcast a single element.
13914     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
13915                                                     Mask, Subtarget, DAG))
13916       return Broadcast;
13917 
13918     // Use even/odd duplicate instructions for masks that match their pattern.
13919     if (Subtarget.hasSSE3()) {
13920       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
13921         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
13922       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
13923         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
13924     }
13925 
13926     if (Subtarget.hasAVX()) {
13927       // If we have AVX, we can use VPERMILPS which will allow folding a load
13928       // into the shuffle.
13929       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
13930                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13931     }
13932 
13933     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
13934     // in SSE1 because otherwise they are widened to v2f64 and never get here.
13935     if (!Subtarget.hasSSE2()) {
13936       if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}))
13937         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
13938       if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 2, 3}))
13939         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
13940     }
13941 
13942     // Otherwise, use a straight shuffle of a single input vector. We pass the
13943     // input vector to both operands to simulate this with a SHUFPS.
13944     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
13945                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
13946   }
13947 
13948   if (Subtarget.hasAVX2())
13949     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
13950       return Extract;
13951 
13952   // There are special ways we can lower some single-element blends. However, we
13953   // have custom ways we can lower more complex single-element blends below that
13954   // we defer to if both this and BLENDPS fail to match, so restrict this to
13955   // when the V2 input is targeting element 0 of the mask -- that is the fast
13956   // case here.
13957   if (NumV2Elements == 1 && Mask[0] >= 4)
13958     if (SDValue V = lowerShuffleAsElementInsertion(
13959             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
13960       return V;
13961 
13962   if (Subtarget.hasSSE41()) {
13963     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
13964                                             Zeroable, Subtarget, DAG))
13965       return Blend;
13966 
13967     // Use INSERTPS if we can complete the shuffle efficiently.
13968     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
13969       return V;
13970 
13971     if (!isSingleSHUFPSMask(Mask))
13972       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
13973                                                             V2, Mask, DAG))
13974         return BlendPerm;
13975   }
13976 
13977   // Use low/high mov instructions. These are only valid in SSE1 because
13978   // otherwise they are widened to v2f64 and never get here.
13979   if (!Subtarget.hasSSE2()) {
13980     if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5}))
13981       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
13982     if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 6, 7}))
13983       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
13984   }
13985 
13986   // Use dedicated unpack instructions for masks that match their pattern.
13987   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
13988     return V;
13989 
13990   // Otherwise fall back to a SHUFPS lowering strategy.
13991   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
13992 }
13993 
13994 /// Lower 4-lane i32 vector shuffles.
13995 ///
13996 /// We try to handle these with integer-domain shuffles where we can, but for
13997 /// 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)13998 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13999                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14000                                  const X86Subtarget &Subtarget,
14001                                  SelectionDAG &DAG) {
14002   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14003   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14004   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14005 
14006   // Whenever we can lower this as a zext, that instruction is strictly faster
14007   // than any alternative. It also allows us to fold memory operands into the
14008   // shuffle in many cases.
14009   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14010                                                    Zeroable, Subtarget, DAG))
14011     return ZExt;
14012 
14013   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14014 
14015   if (NumV2Elements == 0) {
14016     // Try to use broadcast unless the mask only has one non-undef element.
14017     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14018       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14019                                                       Mask, Subtarget, DAG))
14020         return Broadcast;
14021     }
14022 
14023     // Straight shuffle of a single input vector. For everything from SSE2
14024     // onward this has a single fast instruction with no scary immediates.
14025     // We coerce the shuffle pattern to be compatible with UNPCK instructions
14026     // but we aren't actually going to use the UNPCK instruction because doing
14027     // so prevents folding a load into this instruction or making a copy.
14028     const int UnpackLoMask[] = {0, 0, 1, 1};
14029     const int UnpackHiMask[] = {2, 2, 3, 3};
14030     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
14031       Mask = UnpackLoMask;
14032     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
14033       Mask = UnpackHiMask;
14034 
14035     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14036                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14037   }
14038 
14039   if (Subtarget.hasAVX2())
14040     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14041       return Extract;
14042 
14043   // Try to use shift instructions.
14044   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
14045                                           Zeroable, Subtarget, DAG))
14046     return Shift;
14047 
14048   // There are special ways we can lower some single-element blends.
14049   if (NumV2Elements == 1)
14050     if (SDValue V = lowerShuffleAsElementInsertion(
14051             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14052       return V;
14053 
14054   // We have different paths for blend lowering, but they all must use the
14055   // *exact* same predicate.
14056   bool IsBlendSupported = Subtarget.hasSSE41();
14057   if (IsBlendSupported)
14058     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14059                                             Zeroable, Subtarget, DAG))
14060       return Blend;
14061 
14062   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
14063                                              Zeroable, Subtarget, DAG))
14064     return Masked;
14065 
14066   // Use dedicated unpack instructions for masks that match their pattern.
14067   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
14068     return V;
14069 
14070   // Try to use byte rotation instructions.
14071   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14072   if (Subtarget.hasSSSE3()) {
14073     if (Subtarget.hasVLX())
14074       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14075                                                 Subtarget, DAG))
14076         return Rotate;
14077 
14078     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
14079                                                   Subtarget, DAG))
14080       return Rotate;
14081   }
14082 
14083   // Assume that a single SHUFPS is faster than an alternative sequence of
14084   // multiple instructions (even if the CPU has a domain penalty).
14085   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
14086   if (!isSingleSHUFPSMask(Mask)) {
14087     // If we have direct support for blends, we should lower by decomposing into
14088     // a permute. That will be faster than the domain cross.
14089     if (IsBlendSupported)
14090       return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2, Mask,
14091                                                   Subtarget, DAG);
14092 
14093     // Try to lower by permuting the inputs into an unpack instruction.
14094     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
14095                                                         Mask, Subtarget, DAG))
14096       return Unpack;
14097   }
14098 
14099   // We implement this with SHUFPS because it can blend from two vectors.
14100   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
14101   // up the inputs, bypassing domain shift penalties that we would incur if we
14102   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
14103   // relevant.
14104   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
14105   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
14106   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
14107   return DAG.getBitcast(MVT::v4i32, ShufPS);
14108 }
14109 
14110 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
14111 /// shuffle lowering, and the most complex part.
14112 ///
14113 /// The lowering strategy is to try to form pairs of input lanes which are
14114 /// targeted at the same half of the final vector, and then use a dword shuffle
14115 /// to place them onto the right half, and finally unpack the paired lanes into
14116 /// their final position.
14117 ///
14118 /// The exact breakdown of how to form these dword pairs and align them on the
14119 /// correct sides is really tricky. See the comments within the function for
14120 /// more of the details.
14121 ///
14122 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
14123 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
14124 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
14125 /// 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)14126 static SDValue lowerV8I16GeneralSingleInputShuffle(
14127     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
14128     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14129   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
14130   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
14131 
14132   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
14133   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
14134   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
14135 
14136   // Attempt to directly match PSHUFLW or PSHUFHW.
14137   if (isUndefOrInRange(LoMask, 0, 4) &&
14138       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
14139     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14140                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14141   }
14142   if (isUndefOrInRange(HiMask, 4, 8) &&
14143       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
14144     for (int i = 0; i != 4; ++i)
14145       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
14146     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14147                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14148   }
14149 
14150   SmallVector<int, 4> LoInputs;
14151   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
14152   array_pod_sort(LoInputs.begin(), LoInputs.end());
14153   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
14154   SmallVector<int, 4> HiInputs;
14155   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
14156   array_pod_sort(HiInputs.begin(), HiInputs.end());
14157   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
14158   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
14159   int NumHToL = LoInputs.size() - NumLToL;
14160   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
14161   int NumHToH = HiInputs.size() - NumLToH;
14162   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
14163   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
14164   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
14165   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
14166 
14167   // If we are shuffling values from one half - check how many different DWORD
14168   // pairs we need to create. If only 1 or 2 then we can perform this as a
14169   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
14170   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
14171                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
14172     V = DAG.getNode(ShufWOp, DL, VT, V,
14173                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14174     V = DAG.getBitcast(PSHUFDVT, V);
14175     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
14176                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14177     return DAG.getBitcast(VT, V);
14178   };
14179 
14180   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
14181     int PSHUFDMask[4] = { -1, -1, -1, -1 };
14182     SmallVector<std::pair<int, int>, 4> DWordPairs;
14183     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
14184 
14185     // Collect the different DWORD pairs.
14186     for (int DWord = 0; DWord != 4; ++DWord) {
14187       int M0 = Mask[2 * DWord + 0];
14188       int M1 = Mask[2 * DWord + 1];
14189       M0 = (M0 >= 0 ? M0 % 4 : M0);
14190       M1 = (M1 >= 0 ? M1 % 4 : M1);
14191       if (M0 < 0 && M1 < 0)
14192         continue;
14193 
14194       bool Match = false;
14195       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
14196         auto &DWordPair = DWordPairs[j];
14197         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
14198             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
14199           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
14200           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
14201           PSHUFDMask[DWord] = DOffset + j;
14202           Match = true;
14203           break;
14204         }
14205       }
14206       if (!Match) {
14207         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
14208         DWordPairs.push_back(std::make_pair(M0, M1));
14209       }
14210     }
14211 
14212     if (DWordPairs.size() <= 2) {
14213       DWordPairs.resize(2, std::make_pair(-1, -1));
14214       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
14215                               DWordPairs[1].first, DWordPairs[1].second};
14216       if ((NumHToL + NumHToH) == 0)
14217         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
14218       if ((NumLToL + NumLToH) == 0)
14219         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
14220     }
14221   }
14222 
14223   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
14224   // such inputs we can swap two of the dwords across the half mark and end up
14225   // with <=2 inputs to each half in each half. Once there, we can fall through
14226   // to the generic code below. For example:
14227   //
14228   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14229   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
14230   //
14231   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
14232   // and an existing 2-into-2 on the other half. In this case we may have to
14233   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
14234   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
14235   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
14236   // because any other situation (including a 3-into-1 or 1-into-3 in the other
14237   // half than the one we target for fixing) will be fixed when we re-enter this
14238   // path. We will also combine away any sequence of PSHUFD instructions that
14239   // result into a single instruction. Here is an example of the tricky case:
14240   //
14241   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14242   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
14243   //
14244   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
14245   //
14246   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
14247   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
14248   //
14249   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
14250   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
14251   //
14252   // The result is fine to be handled by the generic logic.
14253   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
14254                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
14255                           int AOffset, int BOffset) {
14256     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
14257            "Must call this with A having 3 or 1 inputs from the A half.");
14258     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
14259            "Must call this with B having 1 or 3 inputs from the B half.");
14260     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
14261            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
14262 
14263     bool ThreeAInputs = AToAInputs.size() == 3;
14264 
14265     // Compute the index of dword with only one word among the three inputs in
14266     // a half by taking the sum of the half with three inputs and subtracting
14267     // the sum of the actual three inputs. The difference is the remaining
14268     // slot.
14269     int ADWord = 0, BDWord = 0;
14270     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
14271     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
14272     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
14273     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
14274     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
14275     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
14276     int TripleNonInputIdx =
14277         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
14278     TripleDWord = TripleNonInputIdx / 2;
14279 
14280     // We use xor with one to compute the adjacent DWord to whichever one the
14281     // OneInput is in.
14282     OneInputDWord = (OneInput / 2) ^ 1;
14283 
14284     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
14285     // and BToA inputs. If there is also such a problem with the BToB and AToB
14286     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
14287     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
14288     // is essential that we don't *create* a 3<-1 as then we might oscillate.
14289     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
14290       // Compute how many inputs will be flipped by swapping these DWords. We
14291       // need
14292       // to balance this to ensure we don't form a 3-1 shuffle in the other
14293       // half.
14294       int NumFlippedAToBInputs =
14295           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
14296           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
14297       int NumFlippedBToBInputs =
14298           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
14299           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
14300       if ((NumFlippedAToBInputs == 1 &&
14301            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
14302           (NumFlippedBToBInputs == 1 &&
14303            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
14304         // We choose whether to fix the A half or B half based on whether that
14305         // half has zero flipped inputs. At zero, we may not be able to fix it
14306         // with that half. We also bias towards fixing the B half because that
14307         // will more commonly be the high half, and we have to bias one way.
14308         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
14309                                                        ArrayRef<int> Inputs) {
14310           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
14311           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
14312           // Determine whether the free index is in the flipped dword or the
14313           // unflipped dword based on where the pinned index is. We use this bit
14314           // in an xor to conditionally select the adjacent dword.
14315           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
14316           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14317           if (IsFixIdxInput == IsFixFreeIdxInput)
14318             FixFreeIdx += 1;
14319           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14320           assert(IsFixIdxInput != IsFixFreeIdxInput &&
14321                  "We need to be changing the number of flipped inputs!");
14322           int PSHUFHalfMask[] = {0, 1, 2, 3};
14323           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
14324           V = DAG.getNode(
14325               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
14326               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
14327               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14328 
14329           for (int &M : Mask)
14330             if (M >= 0 && M == FixIdx)
14331               M = FixFreeIdx;
14332             else if (M >= 0 && M == FixFreeIdx)
14333               M = FixIdx;
14334         };
14335         if (NumFlippedBToBInputs != 0) {
14336           int BPinnedIdx =
14337               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
14338           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
14339         } else {
14340           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
14341           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
14342           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
14343         }
14344       }
14345     }
14346 
14347     int PSHUFDMask[] = {0, 1, 2, 3};
14348     PSHUFDMask[ADWord] = BDWord;
14349     PSHUFDMask[BDWord] = ADWord;
14350     V = DAG.getBitcast(
14351         VT,
14352         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14353                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14354 
14355     // Adjust the mask to match the new locations of A and B.
14356     for (int &M : Mask)
14357       if (M >= 0 && M/2 == ADWord)
14358         M = 2 * BDWord + M % 2;
14359       else if (M >= 0 && M/2 == BDWord)
14360         M = 2 * ADWord + M % 2;
14361 
14362     // Recurse back into this routine to re-compute state now that this isn't
14363     // a 3 and 1 problem.
14364     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
14365   };
14366   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
14367     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
14368   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
14369     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
14370 
14371   // At this point there are at most two inputs to the low and high halves from
14372   // each half. That means the inputs can always be grouped into dwords and
14373   // those dwords can then be moved to the correct half with a dword shuffle.
14374   // We use at most one low and one high word shuffle to collect these paired
14375   // inputs into dwords, and finally a dword shuffle to place them.
14376   int PSHUFLMask[4] = {-1, -1, -1, -1};
14377   int PSHUFHMask[4] = {-1, -1, -1, -1};
14378   int PSHUFDMask[4] = {-1, -1, -1, -1};
14379 
14380   // First fix the masks for all the inputs that are staying in their
14381   // original halves. This will then dictate the targets of the cross-half
14382   // shuffles.
14383   auto fixInPlaceInputs =
14384       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
14385                     MutableArrayRef<int> SourceHalfMask,
14386                     MutableArrayRef<int> HalfMask, int HalfOffset) {
14387     if (InPlaceInputs.empty())
14388       return;
14389     if (InPlaceInputs.size() == 1) {
14390       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14391           InPlaceInputs[0] - HalfOffset;
14392       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
14393       return;
14394     }
14395     if (IncomingInputs.empty()) {
14396       // Just fix all of the in place inputs.
14397       for (int Input : InPlaceInputs) {
14398         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
14399         PSHUFDMask[Input / 2] = Input / 2;
14400       }
14401       return;
14402     }
14403 
14404     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
14405     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14406         InPlaceInputs[0] - HalfOffset;
14407     // Put the second input next to the first so that they are packed into
14408     // a dword. We find the adjacent index by toggling the low bit.
14409     int AdjIndex = InPlaceInputs[0] ^ 1;
14410     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
14411     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
14412     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
14413   };
14414   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
14415   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
14416 
14417   // Now gather the cross-half inputs and place them into a free dword of
14418   // their target half.
14419   // FIXME: This operation could almost certainly be simplified dramatically to
14420   // look more like the 3-1 fixing operation.
14421   auto moveInputsToRightHalf = [&PSHUFDMask](
14422       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
14423       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
14424       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
14425       int DestOffset) {
14426     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
14427       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
14428     };
14429     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
14430                                                int Word) {
14431       int LowWord = Word & ~1;
14432       int HighWord = Word | 1;
14433       return isWordClobbered(SourceHalfMask, LowWord) ||
14434              isWordClobbered(SourceHalfMask, HighWord);
14435     };
14436 
14437     if (IncomingInputs.empty())
14438       return;
14439 
14440     if (ExistingInputs.empty()) {
14441       // Map any dwords with inputs from them into the right half.
14442       for (int Input : IncomingInputs) {
14443         // If the source half mask maps over the inputs, turn those into
14444         // swaps and use the swapped lane.
14445         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
14446           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
14447             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
14448                 Input - SourceOffset;
14449             // We have to swap the uses in our half mask in one sweep.
14450             for (int &M : HalfMask)
14451               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
14452                 M = Input;
14453               else if (M == Input)
14454                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14455           } else {
14456             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
14457                        Input - SourceOffset &&
14458                    "Previous placement doesn't match!");
14459           }
14460           // Note that this correctly re-maps both when we do a swap and when
14461           // we observe the other side of the swap above. We rely on that to
14462           // avoid swapping the members of the input list directly.
14463           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14464         }
14465 
14466         // Map the input's dword into the correct half.
14467         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
14468           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
14469         else
14470           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
14471                      Input / 2 &&
14472                  "Previous placement doesn't match!");
14473       }
14474 
14475       // And just directly shift any other-half mask elements to be same-half
14476       // as we will have mirrored the dword containing the element into the
14477       // same position within that half.
14478       for (int &M : HalfMask)
14479         if (M >= SourceOffset && M < SourceOffset + 4) {
14480           M = M - SourceOffset + DestOffset;
14481           assert(M >= 0 && "This should never wrap below zero!");
14482         }
14483       return;
14484     }
14485 
14486     // Ensure we have the input in a viable dword of its current half. This
14487     // is particularly tricky because the original position may be clobbered
14488     // by inputs being moved and *staying* in that half.
14489     if (IncomingInputs.size() == 1) {
14490       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14491         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
14492                          SourceOffset;
14493         SourceHalfMask[InputFixed - SourceOffset] =
14494             IncomingInputs[0] - SourceOffset;
14495         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
14496                      InputFixed);
14497         IncomingInputs[0] = InputFixed;
14498       }
14499     } else if (IncomingInputs.size() == 2) {
14500       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
14501           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14502         // We have two non-adjacent or clobbered inputs we need to extract from
14503         // the source half. To do this, we need to map them into some adjacent
14504         // dword slot in the source mask.
14505         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
14506                               IncomingInputs[1] - SourceOffset};
14507 
14508         // If there is a free slot in the source half mask adjacent to one of
14509         // the inputs, place the other input in it. We use (Index XOR 1) to
14510         // compute an adjacent index.
14511         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
14512             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
14513           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
14514           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14515           InputsFixed[1] = InputsFixed[0] ^ 1;
14516         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
14517                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
14518           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
14519           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14520           InputsFixed[0] = InputsFixed[1] ^ 1;
14521         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14522                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14523           // The two inputs are in the same DWord but it is clobbered and the
14524           // adjacent DWord isn't used at all. Move both inputs to the free
14525           // slot.
14526           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14527           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14528           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14529           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14530         } else {
14531           // The only way we hit this point is if there is no clobbering
14532           // (because there are no off-half inputs to this half) and there is no
14533           // free slot adjacent to one of the inputs. In this case, we have to
14534           // swap an input with a non-input.
14535           for (int i = 0; i < 4; ++i)
14536             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
14537                    "We can't handle any clobbers here!");
14538           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
14539                  "Cannot have adjacent inputs here!");
14540 
14541           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14542           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
14543 
14544           // We also have to update the final source mask in this case because
14545           // it may need to undo the above swap.
14546           for (int &M : FinalSourceHalfMask)
14547             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
14548               M = InputsFixed[1] + SourceOffset;
14549             else if (M == InputsFixed[1] + SourceOffset)
14550               M = (InputsFixed[0] ^ 1) + SourceOffset;
14551 
14552           InputsFixed[1] = InputsFixed[0] ^ 1;
14553         }
14554 
14555         // Point everything at the fixed inputs.
14556         for (int &M : HalfMask)
14557           if (M == IncomingInputs[0])
14558             M = InputsFixed[0] + SourceOffset;
14559           else if (M == IncomingInputs[1])
14560             M = InputsFixed[1] + SourceOffset;
14561 
14562         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
14563         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
14564       }
14565     } else {
14566       llvm_unreachable("Unhandled input size!");
14567     }
14568 
14569     // Now hoist the DWord down to the right half.
14570     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
14571     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
14572     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
14573     for (int &M : HalfMask)
14574       for (int Input : IncomingInputs)
14575         if (M == Input)
14576           M = FreeDWord * 2 + Input % 2;
14577   };
14578   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
14579                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
14580   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
14581                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
14582 
14583   // Now enact all the shuffles we've computed to move the inputs into their
14584   // target half.
14585   if (!isNoopShuffleMask(PSHUFLMask))
14586     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14587                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
14588   if (!isNoopShuffleMask(PSHUFHMask))
14589     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14590                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
14591   if (!isNoopShuffleMask(PSHUFDMask))
14592     V = DAG.getBitcast(
14593         VT,
14594         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14595                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14596 
14597   // At this point, each half should contain all its inputs, and we can then
14598   // just shuffle them into their final position.
14599   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
14600          "Failed to lift all the high half inputs to the low mask!");
14601   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
14602          "Failed to lift all the low half inputs to the high mask!");
14603 
14604   // Do a half shuffle for the low mask.
14605   if (!isNoopShuffleMask(LoMask))
14606     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14607                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14608 
14609   // Do a half shuffle with the high mask after shifting its values down.
14610   for (int &M : HiMask)
14611     if (M >= 0)
14612       M -= 4;
14613   if (!isNoopShuffleMask(HiMask))
14614     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14615                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14616 
14617   return V;
14618 }
14619 
14620 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
14621 /// 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)14622 static SDValue lowerShuffleAsBlendOfPSHUFBs(
14623     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14624     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
14625   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
14626          "Lane crossing shuffle masks not supported");
14627 
14628   int NumBytes = VT.getSizeInBits() / 8;
14629   int Size = Mask.size();
14630   int Scale = NumBytes / Size;
14631 
14632   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14633   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14634   V1InUse = false;
14635   V2InUse = false;
14636 
14637   for (int i = 0; i < NumBytes; ++i) {
14638     int M = Mask[i / Scale];
14639     if (M < 0)
14640       continue;
14641 
14642     const int ZeroMask = 0x80;
14643     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14644     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14645     if (Zeroable[i / Scale])
14646       V1Idx = V2Idx = ZeroMask;
14647 
14648     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14649     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14650     V1InUse |= (ZeroMask != V1Idx);
14651     V2InUse |= (ZeroMask != V2Idx);
14652   }
14653 
14654   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14655   if (V1InUse)
14656     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14657                      DAG.getBuildVector(ShufVT, DL, V1Mask));
14658   if (V2InUse)
14659     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14660                      DAG.getBuildVector(ShufVT, DL, V2Mask));
14661 
14662   // If we need shuffled inputs from both, blend the two.
14663   SDValue V;
14664   if (V1InUse && V2InUse)
14665     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
14666   else
14667     V = V1InUse ? V1 : V2;
14668 
14669   // Cast the result back to the correct type.
14670   return DAG.getBitcast(VT, V);
14671 }
14672 
14673 /// Generic lowering of 8-lane i16 shuffles.
14674 ///
14675 /// This handles both single-input shuffles and combined shuffle/blends with
14676 /// two inputs. The single input shuffles are immediately delegated to
14677 /// a dedicated lowering routine.
14678 ///
14679 /// The blends are lowered in one of three fundamental ways. If there are few
14680 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
14681 /// of the input is significantly cheaper when lowered as an interleaving of
14682 /// the two inputs, try to interleave them. Otherwise, blend the low and high
14683 /// halves of the inputs separately (making them have relatively few inputs)
14684 /// and then concatenate them.
lowerV8I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14685 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14686                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14687                                  const X86Subtarget &Subtarget,
14688                                  SelectionDAG &DAG) {
14689   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14690   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
14691   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
14692 
14693   // Whenever we can lower this as a zext, that instruction is strictly faster
14694   // than any alternative.
14695   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
14696                                                    Zeroable, Subtarget, DAG))
14697     return ZExt;
14698 
14699   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
14700 
14701   if (NumV2Inputs == 0) {
14702     // Try to use shift instructions.
14703     if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
14704                                             Zeroable, Subtarget, DAG))
14705       return Shift;
14706 
14707     // Check for being able to broadcast a single element.
14708     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
14709                                                     Mask, Subtarget, DAG))
14710       return Broadcast;
14711 
14712     // Try to use bit rotation instructions.
14713     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
14714                                                  Subtarget, DAG))
14715       return Rotate;
14716 
14717     // Use dedicated unpack instructions for masks that match their pattern.
14718     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
14719       return V;
14720 
14721     // Use dedicated pack instructions for masks that match their pattern.
14722     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
14723                                          Subtarget))
14724       return V;
14725 
14726     // Try to use byte rotation instructions.
14727     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
14728                                                   Subtarget, DAG))
14729       return Rotate;
14730 
14731     // Make a copy of the mask so it can be modified.
14732     SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
14733     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
14734                                                Subtarget, DAG);
14735   }
14736 
14737   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
14738          "All single-input shuffles should be canonicalized to be V1-input "
14739          "shuffles.");
14740 
14741   // Try to use shift instructions.
14742   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
14743                                           Zeroable, Subtarget, DAG))
14744     return Shift;
14745 
14746   // See if we can use SSE4A Extraction / Insertion.
14747   if (Subtarget.hasSSE4A())
14748     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
14749                                           Zeroable, DAG))
14750       return V;
14751 
14752   // There are special ways we can lower some single-element blends.
14753   if (NumV2Inputs == 1)
14754     if (SDValue V = lowerShuffleAsElementInsertion(
14755             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
14756       return V;
14757 
14758   // We have different paths for blend lowering, but they all must use the
14759   // *exact* same predicate.
14760   bool IsBlendSupported = Subtarget.hasSSE41();
14761   if (IsBlendSupported)
14762     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
14763                                             Zeroable, Subtarget, DAG))
14764       return Blend;
14765 
14766   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
14767                                              Zeroable, Subtarget, DAG))
14768     return Masked;
14769 
14770   // Use dedicated unpack instructions for masks that match their pattern.
14771   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
14772     return V;
14773 
14774   // Use dedicated pack instructions for masks that match their pattern.
14775   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
14776                                        Subtarget))
14777     return V;
14778 
14779   // Try to use byte rotation instructions.
14780   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
14781                                                 Subtarget, DAG))
14782     return Rotate;
14783 
14784   if (SDValue BitBlend =
14785           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
14786     return BitBlend;
14787 
14788   // Try to use byte shift instructions to mask.
14789   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
14790                                               Zeroable, Subtarget, DAG))
14791     return V;
14792 
14793   // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
14794   // We could use SIGN_EXTEND_INREG+PACKSSDW for older targets but this seems to
14795   // be slower than a PSHUFLW+PSHUFHW+PSHUFD chain.
14796   int NumEvenDrops = canLowerByDroppingEvenElements(Mask, false);
14797   if ((NumEvenDrops == 1 || NumEvenDrops == 2) && Subtarget.hasSSE41() &&
14798       !Subtarget.hasVLX()) {
14799     SmallVector<SDValue, 8> DWordClearOps(4, DAG.getConstant(0, DL, MVT::i32));
14800     for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
14801       DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
14802     SDValue DWordClearMask = DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
14803     V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
14804                      DWordClearMask);
14805     V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
14806                      DWordClearMask);
14807     // Now pack things back together.
14808     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, V1, V2);
14809     if (NumEvenDrops == 2) {
14810       Result = DAG.getBitcast(MVT::v4i32, Result);
14811       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, Result, Result);
14812     }
14813     return Result;
14814   }
14815 
14816   // Try to lower by permuting the inputs into an unpack instruction.
14817   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
14818                                                       Mask, Subtarget, DAG))
14819     return Unpack;
14820 
14821   // If we can't directly blend but can use PSHUFB, that will be better as it
14822   // can both shuffle and set up the inefficient blend.
14823   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
14824     bool V1InUse, V2InUse;
14825     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
14826                                         Zeroable, DAG, V1InUse, V2InUse);
14827   }
14828 
14829   // We can always bit-blend if we have to so the fallback strategy is to
14830   // decompose into single-input permutes and blends.
14831   return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
14832                                               Mask, Subtarget, DAG);
14833 }
14834 
lowerShuffleWithPERMV(const SDLoc & DL,MVT VT,ArrayRef<int> Mask,SDValue V1,SDValue V2,SelectionDAG & DAG)14835 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
14836                                      ArrayRef<int> Mask, SDValue V1,
14837                                      SDValue V2, SelectionDAG &DAG) {
14838   MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
14839   MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
14840 
14841   SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
14842   if (V2.isUndef())
14843     return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
14844 
14845   return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
14846 }
14847 
14848 /// Generic lowering of v16i8 shuffles.
14849 ///
14850 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
14851 /// detect any complexity reducing interleaving. If that doesn't help, it uses
14852 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
14853 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
14854 /// back together.
lowerV16I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)14855 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14856                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14857                                  const X86Subtarget &Subtarget,
14858                                  SelectionDAG &DAG) {
14859   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14860   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
14861   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
14862 
14863   // Try to use shift instructions.
14864   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
14865                                           Zeroable, Subtarget, DAG))
14866     return Shift;
14867 
14868   // Try to use byte rotation instructions.
14869   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
14870                                                 Subtarget, DAG))
14871     return Rotate;
14872 
14873   // Use dedicated pack instructions for masks that match their pattern.
14874   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
14875                                        Subtarget))
14876     return V;
14877 
14878   // Try to use a zext lowering.
14879   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
14880                                                    Zeroable, Subtarget, DAG))
14881     return ZExt;
14882 
14883   // See if we can use SSE4A Extraction / Insertion.
14884   if (Subtarget.hasSSE4A())
14885     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
14886                                           Zeroable, DAG))
14887       return V;
14888 
14889   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
14890 
14891   // For single-input shuffles, there are some nicer lowering tricks we can use.
14892   if (NumV2Elements == 0) {
14893     // Check for being able to broadcast a single element.
14894     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
14895                                                     Mask, Subtarget, DAG))
14896       return Broadcast;
14897 
14898     // Try to use bit rotation instructions.
14899     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
14900                                                  Subtarget, DAG))
14901       return Rotate;
14902 
14903     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
14904       return V;
14905 
14906     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
14907     // Notably, this handles splat and partial-splat shuffles more efficiently.
14908     // However, it only makes sense if the pre-duplication shuffle simplifies
14909     // things significantly. Currently, this means we need to be able to
14910     // express the pre-duplication shuffle as an i16 shuffle.
14911     //
14912     // FIXME: We should check for other patterns which can be widened into an
14913     // i16 shuffle as well.
14914     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
14915       for (int i = 0; i < 16; i += 2)
14916         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
14917           return false;
14918 
14919       return true;
14920     };
14921     auto tryToWidenViaDuplication = [&]() -> SDValue {
14922       if (!canWidenViaDuplication(Mask))
14923         return SDValue();
14924       SmallVector<int, 4> LoInputs;
14925       copy_if(Mask, std::back_inserter(LoInputs),
14926               [](int M) { return M >= 0 && M < 8; });
14927       array_pod_sort(LoInputs.begin(), LoInputs.end());
14928       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
14929                      LoInputs.end());
14930       SmallVector<int, 4> HiInputs;
14931       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
14932       array_pod_sort(HiInputs.begin(), HiInputs.end());
14933       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
14934                      HiInputs.end());
14935 
14936       bool TargetLo = LoInputs.size() >= HiInputs.size();
14937       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
14938       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
14939 
14940       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
14941       SmallDenseMap<int, int, 8> LaneMap;
14942       for (int I : InPlaceInputs) {
14943         PreDupI16Shuffle[I/2] = I/2;
14944         LaneMap[I] = I;
14945       }
14946       int j = TargetLo ? 0 : 4, je = j + 4;
14947       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
14948         // Check if j is already a shuffle of this input. This happens when
14949         // there are two adjacent bytes after we move the low one.
14950         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
14951           // If we haven't yet mapped the input, search for a slot into which
14952           // we can map it.
14953           while (j < je && PreDupI16Shuffle[j] >= 0)
14954             ++j;
14955 
14956           if (j == je)
14957             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
14958             return SDValue();
14959 
14960           // Map this input with the i16 shuffle.
14961           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
14962         }
14963 
14964         // Update the lane map based on the mapping we ended up with.
14965         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
14966       }
14967       V1 = DAG.getBitcast(
14968           MVT::v16i8,
14969           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14970                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
14971 
14972       // Unpack the bytes to form the i16s that will be shuffled into place.
14973       bool EvenInUse = false, OddInUse = false;
14974       for (int i = 0; i < 16; i += 2) {
14975         EvenInUse |= (Mask[i + 0] >= 0);
14976         OddInUse |= (Mask[i + 1] >= 0);
14977         if (EvenInUse && OddInUse)
14978           break;
14979       }
14980       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
14981                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
14982                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
14983 
14984       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
14985       for (int i = 0; i < 16; ++i)
14986         if (Mask[i] >= 0) {
14987           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
14988           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
14989           if (PostDupI16Shuffle[i / 2] < 0)
14990             PostDupI16Shuffle[i / 2] = MappedMask;
14991           else
14992             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
14993                    "Conflicting entries in the original shuffle!");
14994         }
14995       return DAG.getBitcast(
14996           MVT::v16i8,
14997           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
14998                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
14999     };
15000     if (SDValue V = tryToWidenViaDuplication())
15001       return V;
15002   }
15003 
15004   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
15005                                              Zeroable, Subtarget, DAG))
15006     return Masked;
15007 
15008   // Use dedicated unpack instructions for masks that match their pattern.
15009   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
15010     return V;
15011 
15012   // Try to use byte shift instructions to mask.
15013   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
15014                                               Zeroable, Subtarget, DAG))
15015     return V;
15016 
15017   // Check for compaction patterns.
15018   bool IsSingleInput = V2.isUndef();
15019   int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput);
15020 
15021   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
15022   // with PSHUFB. It is important to do this before we attempt to generate any
15023   // blends but after all of the single-input lowerings. If the single input
15024   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
15025   // want to preserve that and we can DAG combine any longer sequences into
15026   // a PSHUFB in the end. But once we start blending from multiple inputs,
15027   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
15028   // and there are *very* few patterns that would actually be faster than the
15029   // PSHUFB approach because of its ability to zero lanes.
15030   //
15031   // If the mask is a binary compaction, we can more efficiently perform this
15032   // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
15033   //
15034   // FIXME: The only exceptions to the above are blends which are exact
15035   // interleavings with direct instructions supporting them. We currently don't
15036   // handle those well here.
15037   if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
15038     bool V1InUse = false;
15039     bool V2InUse = false;
15040 
15041     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
15042         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
15043 
15044     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
15045     // do so. This avoids using them to handle blends-with-zero which is
15046     // important as a single pshufb is significantly faster for that.
15047     if (V1InUse && V2InUse) {
15048       if (Subtarget.hasSSE41())
15049         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
15050                                                 Zeroable, Subtarget, DAG))
15051           return Blend;
15052 
15053       // We can use an unpack to do the blending rather than an or in some
15054       // cases. Even though the or may be (very minorly) more efficient, we
15055       // preference this lowering because there are common cases where part of
15056       // the complexity of the shuffles goes away when we do the final blend as
15057       // an unpack.
15058       // FIXME: It might be worth trying to detect if the unpack-feeding
15059       // shuffles will both be pshufb, in which case we shouldn't bother with
15060       // this.
15061       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
15062               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15063         return Unpack;
15064 
15065       // If we have VBMI we can use one VPERM instead of multiple PSHUFBs.
15066       if (Subtarget.hasVBMI() && Subtarget.hasVLX())
15067         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, DAG);
15068 
15069       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
15070       // PALIGNR will be cheaper than the second PSHUFB+OR.
15071       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
15072               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15073         return V;
15074     }
15075 
15076     return PSHUFB;
15077   }
15078 
15079   // There are special ways we can lower some single-element blends.
15080   if (NumV2Elements == 1)
15081     if (SDValue V = lowerShuffleAsElementInsertion(
15082             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15083       return V;
15084 
15085   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
15086     return Blend;
15087 
15088   // Check whether a compaction lowering can be done. This handles shuffles
15089   // which take every Nth element for some even N. See the helper function for
15090   // details.
15091   //
15092   // We special case these as they can be particularly efficiently handled with
15093   // the PACKUSB instruction on x86 and they show up in common patterns of
15094   // rearranging bytes to truncate wide elements.
15095   if (NumEvenDrops) {
15096     // NumEvenDrops is the power of two stride of the elements. Another way of
15097     // thinking about it is that we need to drop the even elements this many
15098     // times to get the original input.
15099 
15100     // First we need to zero all the dropped bytes.
15101     assert(NumEvenDrops <= 3 &&
15102            "No support for dropping even elements more than 3 times.");
15103     SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
15104     for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
15105       WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
15106     SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
15107     V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
15108                      WordClearMask);
15109     if (!IsSingleInput)
15110       V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
15111                        WordClearMask);
15112 
15113     // Now pack things back together.
15114     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15115                                  IsSingleInput ? V1 : V2);
15116     for (int i = 1; i < NumEvenDrops; ++i) {
15117       Result = DAG.getBitcast(MVT::v8i16, Result);
15118       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
15119     }
15120     return Result;
15121   }
15122 
15123   // Handle multi-input cases by blending single-input shuffles.
15124   if (NumV2Elements > 0)
15125     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2, Mask,
15126                                                 Subtarget, DAG);
15127 
15128   // The fallback path for single-input shuffles widens this into two v8i16
15129   // vectors with unpacks, shuffles those, and then pulls them back together
15130   // with a pack.
15131   SDValue V = V1;
15132 
15133   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15134   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15135   for (int i = 0; i < 16; ++i)
15136     if (Mask[i] >= 0)
15137       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
15138 
15139   SDValue VLoHalf, VHiHalf;
15140   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
15141   // them out and avoid using UNPCK{L,H} to extract the elements of V as
15142   // i16s.
15143   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
15144       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
15145     // Use a mask to drop the high bytes.
15146     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
15147     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
15148                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
15149 
15150     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
15151     VHiHalf = DAG.getUNDEF(MVT::v8i16);
15152 
15153     // Squash the masks to point directly into VLoHalf.
15154     for (int &M : LoBlendMask)
15155       if (M >= 0)
15156         M /= 2;
15157     for (int &M : HiBlendMask)
15158       if (M >= 0)
15159         M /= 2;
15160   } else {
15161     // Otherwise just unpack the low half of V into VLoHalf and the high half into
15162     // VHiHalf so that we can blend them as i16s.
15163     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
15164 
15165     VLoHalf = DAG.getBitcast(
15166         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
15167     VHiHalf = DAG.getBitcast(
15168         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
15169   }
15170 
15171   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
15172   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
15173 
15174   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
15175 }
15176 
15177 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
15178 ///
15179 /// This routine breaks down the specific type of 128-bit shuffle and
15180 /// 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)15181 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15182                                   MVT VT, SDValue V1, SDValue V2,
15183                                   const APInt &Zeroable,
15184                                   const X86Subtarget &Subtarget,
15185                                   SelectionDAG &DAG) {
15186   switch (VT.SimpleTy) {
15187   case MVT::v2i64:
15188     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15189   case MVT::v2f64:
15190     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15191   case MVT::v4i32:
15192     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15193   case MVT::v4f32:
15194     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15195   case MVT::v8i16:
15196     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15197   case MVT::v16i8:
15198     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15199 
15200   default:
15201     llvm_unreachable("Unimplemented!");
15202   }
15203 }
15204 
15205 /// Generic routine to split vector shuffle into half-sized shuffles.
15206 ///
15207 /// This routine just extracts two subvectors, shuffles them independently, and
15208 /// then concatenates them back together. This should work effectively with all
15209 /// AVX vector shuffle types.
splitAndLowerShuffle(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)15210 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
15211                                     SDValue V2, ArrayRef<int> Mask,
15212                                     SelectionDAG &DAG) {
15213   assert(VT.getSizeInBits() >= 256 &&
15214          "Only for 256-bit or wider vector shuffles!");
15215   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
15216   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
15217 
15218   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
15219   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
15220 
15221   int NumElements = VT.getVectorNumElements();
15222   int SplitNumElements = NumElements / 2;
15223   MVT ScalarVT = VT.getVectorElementType();
15224   MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
15225 
15226   // Use splitVector/extractSubVector so that split build-vectors just build two
15227   // narrower build vectors. This helps shuffling with splats and zeros.
15228   auto SplitVector = [&](SDValue V) {
15229     SDValue LoV, HiV;
15230     std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
15231     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
15232                           DAG.getBitcast(SplitVT, HiV));
15233   };
15234 
15235   SDValue LoV1, HiV1, LoV2, HiV2;
15236   std::tie(LoV1, HiV1) = SplitVector(V1);
15237   std::tie(LoV2, HiV2) = SplitVector(V2);
15238 
15239   // Now create two 4-way blends of these half-width vectors.
15240   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
15241     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
15242     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
15243     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
15244     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
15245     for (int i = 0; i < SplitNumElements; ++i) {
15246       int M = HalfMask[i];
15247       if (M >= NumElements) {
15248         if (M >= NumElements + SplitNumElements)
15249           UseHiV2 = true;
15250         else
15251           UseLoV2 = true;
15252         V2BlendMask[i] = M - NumElements;
15253         BlendMask[i] = SplitNumElements + i;
15254       } else if (M >= 0) {
15255         if (M >= SplitNumElements)
15256           UseHiV1 = true;
15257         else
15258           UseLoV1 = true;
15259         V1BlendMask[i] = M;
15260         BlendMask[i] = i;
15261       }
15262     }
15263 
15264     // Because the lowering happens after all combining takes place, we need to
15265     // manually combine these blend masks as much as possible so that we create
15266     // a minimal number of high-level vector shuffle nodes.
15267 
15268     // First try just blending the halves of V1 or V2.
15269     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
15270       return DAG.getUNDEF(SplitVT);
15271     if (!UseLoV2 && !UseHiV2)
15272       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15273     if (!UseLoV1 && !UseHiV1)
15274       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15275 
15276     SDValue V1Blend, V2Blend;
15277     if (UseLoV1 && UseHiV1) {
15278       V1Blend =
15279         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15280     } else {
15281       // We only use half of V1 so map the usage down into the final blend mask.
15282       V1Blend = UseLoV1 ? LoV1 : HiV1;
15283       for (int i = 0; i < SplitNumElements; ++i)
15284         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
15285           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
15286     }
15287     if (UseLoV2 && UseHiV2) {
15288       V2Blend =
15289         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15290     } else {
15291       // We only use half of V2 so map the usage down into the final blend mask.
15292       V2Blend = UseLoV2 ? LoV2 : HiV2;
15293       for (int i = 0; i < SplitNumElements; ++i)
15294         if (BlendMask[i] >= SplitNumElements)
15295           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
15296     }
15297     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
15298   };
15299   SDValue Lo = HalfBlend(LoMask);
15300   SDValue Hi = HalfBlend(HiMask);
15301   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
15302 }
15303 
15304 /// Either split a vector in halves or decompose the shuffles and the
15305 /// blend.
15306 ///
15307 /// This is provided as a good fallback for many lowerings of non-single-input
15308 /// shuffles with more than one 128-bit lane. In those cases, we want to select
15309 /// between splitting the shuffle into 128-bit components and stitching those
15310 /// back together vs. extracting the single-input shuffles and blending those
15311 /// results.
lowerShuffleAsSplitOrBlend(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15312 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
15313                                           SDValue V2, ArrayRef<int> Mask,
15314                                           const X86Subtarget &Subtarget,
15315                                           SelectionDAG &DAG) {
15316   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
15317          "shuffles as it could then recurse on itself.");
15318   int Size = Mask.size();
15319 
15320   // If this can be modeled as a broadcast of two elements followed by a blend,
15321   // prefer that lowering. This is especially important because broadcasts can
15322   // often fold with memory operands.
15323   auto DoBothBroadcast = [&] {
15324     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
15325     for (int M : Mask)
15326       if (M >= Size) {
15327         if (V2BroadcastIdx < 0)
15328           V2BroadcastIdx = M - Size;
15329         else if (M - Size != V2BroadcastIdx)
15330           return false;
15331       } else if (M >= 0) {
15332         if (V1BroadcastIdx < 0)
15333           V1BroadcastIdx = M;
15334         else if (M != V1BroadcastIdx)
15335           return false;
15336       }
15337     return true;
15338   };
15339   if (DoBothBroadcast())
15340     return lowerShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
15341                                                 Subtarget, DAG);
15342 
15343   // If the inputs all stem from a single 128-bit lane of each input, then we
15344   // split them rather than blending because the split will decompose to
15345   // unusually few instructions.
15346   int LaneCount = VT.getSizeInBits() / 128;
15347   int LaneSize = Size / LaneCount;
15348   SmallBitVector LaneInputs[2];
15349   LaneInputs[0].resize(LaneCount, false);
15350   LaneInputs[1].resize(LaneCount, false);
15351   for (int i = 0; i < Size; ++i)
15352     if (Mask[i] >= 0)
15353       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
15354   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
15355     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15356 
15357   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
15358   // that the decomposed single-input shuffles don't end up here.
15359   return lowerShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, Subtarget,
15360                                               DAG);
15361 }
15362 
15363 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15364 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
lowerShuffleAsLanePermuteAndSHUFP(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG)15365 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
15366                                                  SDValue V1, SDValue V2,
15367                                                  ArrayRef<int> Mask,
15368                                                  SelectionDAG &DAG) {
15369   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
15370 
15371   int LHSMask[4] = {-1, -1, -1, -1};
15372   int RHSMask[4] = {-1, -1, -1, -1};
15373   unsigned SHUFPMask = 0;
15374 
15375   // As SHUFPD uses a single LHS/RHS element per lane, we can always
15376   // perform the shuffle once the lanes have been shuffled in place.
15377   for (int i = 0; i != 4; ++i) {
15378     int M = Mask[i];
15379     if (M < 0)
15380       continue;
15381     int LaneBase = i & ~1;
15382     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
15383     LaneMask[LaneBase + (M & 1)] = M;
15384     SHUFPMask |= (M & 1) << i;
15385   }
15386 
15387   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
15388   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
15389   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
15390                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
15391 }
15392 
15393 /// Lower a vector shuffle crossing multiple 128-bit lanes as
15394 /// a lane permutation followed by a per-lane permutation.
15395 ///
15396 /// This is mainly for cases where we can have non-repeating permutes
15397 /// in each lane.
15398 ///
15399 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
15400 /// we should investigate merging them.
lowerShuffleAsLanePermuteAndPermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,SelectionDAG & DAG,const X86Subtarget & Subtarget)15401 static SDValue lowerShuffleAsLanePermuteAndPermute(
15402     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15403     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15404   int NumElts = VT.getVectorNumElements();
15405   int NumLanes = VT.getSizeInBits() / 128;
15406   int NumEltsPerLane = NumElts / NumLanes;
15407 
15408   SmallVector<int, 4> SrcLaneMask(NumLanes, SM_SentinelUndef);
15409   SmallVector<int, 16> PermMask(NumElts, SM_SentinelUndef);
15410 
15411   for (int i = 0; i != NumElts; ++i) {
15412     int M = Mask[i];
15413     if (M < 0)
15414       continue;
15415 
15416     // Ensure that each lane comes from a single source lane.
15417     int SrcLane = M / NumEltsPerLane;
15418     int DstLane = i / NumEltsPerLane;
15419     if (!isUndefOrEqual(SrcLaneMask[DstLane], SrcLane))
15420       return SDValue();
15421     SrcLaneMask[DstLane] = SrcLane;
15422 
15423     PermMask[i] = (DstLane * NumEltsPerLane) + (M % NumEltsPerLane);
15424   }
15425 
15426   // Make sure we set all elements of the lane mask, to avoid undef propagation.
15427   SmallVector<int, 16> LaneMask(NumElts, SM_SentinelUndef);
15428   for (int DstLane = 0; DstLane != NumLanes; ++DstLane) {
15429     int SrcLane = SrcLaneMask[DstLane];
15430     if (0 <= SrcLane)
15431       for (int j = 0; j != NumEltsPerLane; ++j) {
15432         LaneMask[(DstLane * NumEltsPerLane) + j] =
15433             (SrcLane * NumEltsPerLane) + j;
15434       }
15435   }
15436 
15437   // If we're only shuffling a single lowest lane and the rest are identity
15438   // then don't bother.
15439   // TODO - isShuffleMaskInputInPlace could be extended to something like this.
15440   int NumIdentityLanes = 0;
15441   bool OnlyShuffleLowestLane = true;
15442   for (int i = 0; i != NumLanes; ++i) {
15443     if (isSequentialOrUndefInRange(PermMask, i * NumEltsPerLane, NumEltsPerLane,
15444                                    i * NumEltsPerLane))
15445       NumIdentityLanes++;
15446     else if (SrcLaneMask[i] != 0 && SrcLaneMask[i] != NumLanes)
15447       OnlyShuffleLowestLane = false;
15448   }
15449   if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15450     return SDValue();
15451 
15452   SDValue LanePermute = DAG.getVectorShuffle(VT, DL, V1, V2, LaneMask);
15453   return DAG.getVectorShuffle(VT, DL, LanePermute, DAG.getUNDEF(VT), PermMask);
15454 }
15455 
15456 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
15457 /// source with a lane permutation.
15458 ///
15459 /// This lowering strategy results in four instructions in the worst case for a
15460 /// single-input cross lane shuffle which is lower than any other fully general
15461 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
15462 /// 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)15463 static SDValue lowerShuffleAsLanePermuteAndShuffle(
15464     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15465     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15466   // FIXME: This should probably be generalized for 512-bit vectors as well.
15467   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
15468   int Size = Mask.size();
15469   int LaneSize = Size / 2;
15470 
15471   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15472   // Only do this if the elements aren't all from the lower lane,
15473   // otherwise we're (probably) better off doing a split.
15474   if (VT == MVT::v4f64 &&
15475       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15476     if (SDValue V =
15477             lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG))
15478       return V;
15479 
15480   // If there are only inputs from one 128-bit lane, splitting will in fact be
15481   // less expensive. The flags track whether the given lane contains an element
15482   // that crosses to another lane.
15483   if (!Subtarget.hasAVX2()) {
15484     bool LaneCrossing[2] = {false, false};
15485     for (int i = 0; i < Size; ++i)
15486       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15487         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15488     if (!LaneCrossing[0] || !LaneCrossing[1])
15489       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15490   } else {
15491     bool LaneUsed[2] = {false, false};
15492     for (int i = 0; i < Size; ++i)
15493       if (Mask[i] >= 0)
15494         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15495     if (!LaneUsed[0] || !LaneUsed[1])
15496       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15497   }
15498 
15499   // TODO - we could support shuffling V2 in the Flipped input.
15500   assert(V2.isUndef() &&
15501          "This last part of this routine only works on single input shuffles");
15502 
15503   SmallVector<int, 32> InLaneMask(Mask.begin(), Mask.end());
15504   for (int i = 0; i < Size; ++i) {
15505     int &M = InLaneMask[i];
15506     if (M < 0)
15507       continue;
15508     if (((M % Size) / LaneSize) != (i / LaneSize))
15509       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15510   }
15511   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15512          "In-lane shuffle mask expected");
15513 
15514   // Flip the lanes, and shuffle the results which should now be in-lane.
15515   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15516   SDValue Flipped = DAG.getBitcast(PVT, V1);
15517   Flipped =
15518       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15519   Flipped = DAG.getBitcast(VT, Flipped);
15520   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15521 }
15522 
15523 /// 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)15524 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
15525                                   SDValue V2, ArrayRef<int> Mask,
15526                                   const APInt &Zeroable,
15527                                   const X86Subtarget &Subtarget,
15528                                   SelectionDAG &DAG) {
15529   // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15530   if (Subtarget.hasAVX2() && V2.isUndef())
15531     return SDValue();
15532 
15533   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15534 
15535   SmallVector<int, 4> WidenedMask;
15536   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15537     return SDValue();
15538 
15539   bool IsLowZero = (Zeroable & 0x3) == 0x3;
15540   bool IsHighZero = (Zeroable & 0xc) == 0xc;
15541 
15542   // Try to use an insert into a zero vector.
15543   if (WidenedMask[0] == 0 && IsHighZero) {
15544     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15545     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15546                               DAG.getIntPtrConstant(0, DL));
15547     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15548                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
15549                        DAG.getIntPtrConstant(0, DL));
15550   }
15551 
15552   // TODO: If minimizing size and one of the inputs is a zero vector and the
15553   // the zero vector has only one use, we could use a VPERM2X128 to save the
15554   // instruction bytes needed to explicitly generate the zero vector.
15555 
15556   // Blends are faster and handle all the non-lane-crossing cases.
15557   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15558                                           Subtarget, DAG))
15559     return Blend;
15560 
15561   // If either input operand is a zero vector, use VPERM2X128 because its mask
15562   // allows us to replace the zero input with an implicit zero.
15563   if (!IsLowZero && !IsHighZero) {
15564     // Check for patterns which can be matched with a single insert of a 128-bit
15565     // subvector.
15566     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
15567     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
15568 
15569       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
15570       // this will likely become vinsertf128 which can't fold a 256-bit memop.
15571       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
15572         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15573         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
15574                                      OnlyUsesV1 ? V1 : V2,
15575                                      DAG.getIntPtrConstant(0, DL));
15576         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15577                            DAG.getIntPtrConstant(2, DL));
15578       }
15579     }
15580 
15581     // Try to use SHUF128 if possible.
15582     if (Subtarget.hasVLX()) {
15583       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
15584         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
15585                             ((WidenedMask[1] % 2) << 1);
15586         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
15587                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
15588       }
15589     }
15590   }
15591 
15592   // Otherwise form a 128-bit permutation. After accounting for undefs,
15593   // convert the 64-bit shuffle mask selection values into 128-bit
15594   // selection bits by dividing the indexes by 2 and shifting into positions
15595   // defined by a vperm2*128 instruction's immediate control byte.
15596 
15597   // The immediate permute control byte looks like this:
15598   //    [1:0] - select 128 bits from sources for low half of destination
15599   //    [2]   - ignore
15600   //    [3]   - zero low half of destination
15601   //    [5:4] - select 128 bits from sources for high half of destination
15602   //    [6]   - ignore
15603   //    [7]   - zero high half of destination
15604 
15605   assert((WidenedMask[0] >= 0 || IsLowZero) &&
15606          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
15607 
15608   unsigned PermMask = 0;
15609   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
15610   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
15611 
15612   // Check the immediate mask and replace unused sources with undef.
15613   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
15614     V1 = DAG.getUNDEF(VT);
15615   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
15616     V2 = DAG.getUNDEF(VT);
15617 
15618   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
15619                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
15620 }
15621 
15622 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
15623 /// shuffling each lane.
15624 ///
15625 /// This attempts to create a repeated lane shuffle where each lane uses one
15626 /// or two of the lanes of the inputs. The lanes of the input vectors are
15627 /// shuffled in one or two independent shuffles to get the lanes into the
15628 /// position needed by the final shuffle.
lowerShuffleAsLanePermuteAndRepeatedMask(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)15629 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
15630     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15631     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
15632   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
15633 
15634   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
15635     return SDValue();
15636 
15637   int NumElts = Mask.size();
15638   int NumLanes = VT.getSizeInBits() / 128;
15639   int NumLaneElts = 128 / VT.getScalarSizeInBits();
15640   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
15641   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
15642 
15643   // First pass will try to fill in the RepeatMask from lanes that need two
15644   // sources.
15645   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15646     int Srcs[2] = {-1, -1};
15647     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
15648     for (int i = 0; i != NumLaneElts; ++i) {
15649       int M = Mask[(Lane * NumLaneElts) + i];
15650       if (M < 0)
15651         continue;
15652       // Determine which of the possible input lanes (NumLanes from each source)
15653       // this element comes from. Assign that as one of the sources for this
15654       // lane. We can assign up to 2 sources for this lane. If we run out
15655       // sources we can't do anything.
15656       int LaneSrc = M / NumLaneElts;
15657       int Src;
15658       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
15659         Src = 0;
15660       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
15661         Src = 1;
15662       else
15663         return SDValue();
15664 
15665       Srcs[Src] = LaneSrc;
15666       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
15667     }
15668 
15669     // If this lane has two sources, see if it fits with the repeat mask so far.
15670     if (Srcs[1] < 0)
15671       continue;
15672 
15673     LaneSrcs[Lane][0] = Srcs[0];
15674     LaneSrcs[Lane][1] = Srcs[1];
15675 
15676     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
15677       assert(M1.size() == M2.size() && "Unexpected mask size");
15678       for (int i = 0, e = M1.size(); i != e; ++i)
15679         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
15680           return false;
15681       return true;
15682     };
15683 
15684     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
15685       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
15686       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
15687         int M = Mask[i];
15688         if (M < 0)
15689           continue;
15690         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
15691                "Unexpected mask element");
15692         MergedMask[i] = M;
15693       }
15694     };
15695 
15696     if (MatchMasks(InLaneMask, RepeatMask)) {
15697       // Merge this lane mask into the final repeat mask.
15698       MergeMasks(InLaneMask, RepeatMask);
15699       continue;
15700     }
15701 
15702     // Didn't find a match. Swap the operands and try again.
15703     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
15704     ShuffleVectorSDNode::commuteMask(InLaneMask);
15705 
15706     if (MatchMasks(InLaneMask, RepeatMask)) {
15707       // Merge this lane mask into the final repeat mask.
15708       MergeMasks(InLaneMask, RepeatMask);
15709       continue;
15710     }
15711 
15712     // Couldn't find a match with the operands in either order.
15713     return SDValue();
15714   }
15715 
15716   // Now handle any lanes with only one source.
15717   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15718     // If this lane has already been processed, skip it.
15719     if (LaneSrcs[Lane][0] >= 0)
15720       continue;
15721 
15722     for (int i = 0; i != NumLaneElts; ++i) {
15723       int M = Mask[(Lane * NumLaneElts) + i];
15724       if (M < 0)
15725         continue;
15726 
15727       // If RepeatMask isn't defined yet we can define it ourself.
15728       if (RepeatMask[i] < 0)
15729         RepeatMask[i] = M % NumLaneElts;
15730 
15731       if (RepeatMask[i] < NumElts) {
15732         if (RepeatMask[i] != M % NumLaneElts)
15733           return SDValue();
15734         LaneSrcs[Lane][0] = M / NumLaneElts;
15735       } else {
15736         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
15737           return SDValue();
15738         LaneSrcs[Lane][1] = M / NumLaneElts;
15739       }
15740     }
15741 
15742     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
15743       return SDValue();
15744   }
15745 
15746   SmallVector<int, 16> NewMask(NumElts, -1);
15747   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15748     int Src = LaneSrcs[Lane][0];
15749     for (int i = 0; i != NumLaneElts; ++i) {
15750       int M = -1;
15751       if (Src >= 0)
15752         M = Src * NumLaneElts + i;
15753       NewMask[Lane * NumLaneElts + i] = M;
15754     }
15755   }
15756   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15757   // Ensure we didn't get back the shuffle we started with.
15758   // FIXME: This is a hack to make up for some splat handling code in
15759   // getVectorShuffle.
15760   if (isa<ShuffleVectorSDNode>(NewV1) &&
15761       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
15762     return SDValue();
15763 
15764   for (int Lane = 0; Lane != NumLanes; ++Lane) {
15765     int Src = LaneSrcs[Lane][1];
15766     for (int i = 0; i != NumLaneElts; ++i) {
15767       int M = -1;
15768       if (Src >= 0)
15769         M = Src * NumLaneElts + i;
15770       NewMask[Lane * NumLaneElts + i] = M;
15771     }
15772   }
15773   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
15774   // Ensure we didn't get back the shuffle we started with.
15775   // FIXME: This is a hack to make up for some splat handling code in
15776   // getVectorShuffle.
15777   if (isa<ShuffleVectorSDNode>(NewV2) &&
15778       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
15779     return SDValue();
15780 
15781   for (int i = 0; i != NumElts; ++i) {
15782     NewMask[i] = RepeatMask[i % NumLaneElts];
15783     if (NewMask[i] < 0)
15784       continue;
15785 
15786     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
15787   }
15788   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
15789 }
15790 
15791 /// If the input shuffle mask results in a vector that is undefined in all upper
15792 /// or lower half elements and that mask accesses only 2 halves of the
15793 /// shuffle's operands, return true. A mask of half the width with mask indexes
15794 /// adjusted to access the extracted halves of the original shuffle operands is
15795 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
15796 /// lower half of each input operand is accessed.
15797 static bool
getHalfShuffleMask(ArrayRef<int> Mask,MutableArrayRef<int> HalfMask,int & HalfIdx1,int & HalfIdx2)15798 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
15799                    int &HalfIdx1, int &HalfIdx2) {
15800   assert((Mask.size() == HalfMask.size() * 2) &&
15801          "Expected input mask to be twice as long as output");
15802 
15803   // Exactly one half of the result must be undef to allow narrowing.
15804   bool UndefLower = isUndefLowerHalf(Mask);
15805   bool UndefUpper = isUndefUpperHalf(Mask);
15806   if (UndefLower == UndefUpper)
15807     return false;
15808 
15809   unsigned HalfNumElts = HalfMask.size();
15810   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
15811   HalfIdx1 = -1;
15812   HalfIdx2 = -1;
15813   for (unsigned i = 0; i != HalfNumElts; ++i) {
15814     int M = Mask[i + MaskIndexOffset];
15815     if (M < 0) {
15816       HalfMask[i] = M;
15817       continue;
15818     }
15819 
15820     // Determine which of the 4 half vectors this element is from.
15821     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
15822     int HalfIdx = M / HalfNumElts;
15823 
15824     // Determine the element index into its half vector source.
15825     int HalfElt = M % HalfNumElts;
15826 
15827     // We can shuffle with up to 2 half vectors, set the new 'half'
15828     // shuffle mask accordingly.
15829     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
15830       HalfMask[i] = HalfElt;
15831       HalfIdx1 = HalfIdx;
15832       continue;
15833     }
15834     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
15835       HalfMask[i] = HalfElt + HalfNumElts;
15836       HalfIdx2 = HalfIdx;
15837       continue;
15838     }
15839 
15840     // Too many half vectors referenced.
15841     return false;
15842   }
15843 
15844   return true;
15845 }
15846 
15847 /// Given the output values from getHalfShuffleMask(), create a half width
15848 /// 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)15849 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
15850                                      ArrayRef<int> HalfMask, int HalfIdx1,
15851                                      int HalfIdx2, bool UndefLower,
15852                                      SelectionDAG &DAG, bool UseConcat = false) {
15853   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
15854   assert(V1.getValueType().isSimple() && "Expecting only simple types");
15855 
15856   MVT VT = V1.getSimpleValueType();
15857   MVT HalfVT = VT.getHalfNumVectorElementsVT();
15858   unsigned HalfNumElts = HalfVT.getVectorNumElements();
15859 
15860   auto getHalfVector = [&](int HalfIdx) {
15861     if (HalfIdx < 0)
15862       return DAG.getUNDEF(HalfVT);
15863     SDValue V = (HalfIdx < 2 ? V1 : V2);
15864     HalfIdx = (HalfIdx % 2) * HalfNumElts;
15865     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
15866                        DAG.getIntPtrConstant(HalfIdx, DL));
15867   };
15868 
15869   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
15870   SDValue Half1 = getHalfVector(HalfIdx1);
15871   SDValue Half2 = getHalfVector(HalfIdx2);
15872   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
15873   if (UseConcat) {
15874     SDValue Op0 = V;
15875     SDValue Op1 = DAG.getUNDEF(HalfVT);
15876     if (UndefLower)
15877       std::swap(Op0, Op1);
15878     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
15879   }
15880 
15881   unsigned Offset = UndefLower ? HalfNumElts : 0;
15882   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
15883                      DAG.getIntPtrConstant(Offset, DL));
15884 }
15885 
15886 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
15887 /// This allows for fast cases such as subvector extraction/insertion
15888 /// 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)15889 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
15890                                          SDValue V2, ArrayRef<int> Mask,
15891                                          const X86Subtarget &Subtarget,
15892                                          SelectionDAG &DAG) {
15893   assert((VT.is256BitVector() || VT.is512BitVector()) &&
15894          "Expected 256-bit or 512-bit vector");
15895 
15896   bool UndefLower = isUndefLowerHalf(Mask);
15897   if (!UndefLower && !isUndefUpperHalf(Mask))
15898     return SDValue();
15899 
15900   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
15901          "Completely undef shuffle mask should have been simplified already");
15902 
15903   // Upper half is undef and lower half is whole upper subvector.
15904   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15905   MVT HalfVT = VT.getHalfNumVectorElementsVT();
15906   unsigned HalfNumElts = HalfVT.getVectorNumElements();
15907   if (!UndefLower &&
15908       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
15909     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15910                              DAG.getIntPtrConstant(HalfNumElts, DL));
15911     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15912                        DAG.getIntPtrConstant(0, DL));
15913   }
15914 
15915   // Lower half is undef and upper half is whole lower subvector.
15916   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15917   if (UndefLower &&
15918       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
15919     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
15920                              DAG.getIntPtrConstant(0, DL));
15921     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
15922                        DAG.getIntPtrConstant(HalfNumElts, DL));
15923   }
15924 
15925   int HalfIdx1, HalfIdx2;
15926   SmallVector<int, 8> HalfMask(HalfNumElts);
15927   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
15928     return SDValue();
15929 
15930   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
15931 
15932   // Only shuffle the halves of the inputs when useful.
15933   unsigned NumLowerHalves =
15934       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
15935   unsigned NumUpperHalves =
15936       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
15937   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
15938 
15939   // Determine the larger pattern of undef/halves, then decide if it's worth
15940   // splitting the shuffle based on subtarget capabilities and types.
15941   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
15942   if (!UndefLower) {
15943     // XXXXuuuu: no insert is needed.
15944     // Always extract lowers when setting lower - these are all free subreg ops.
15945     if (NumUpperHalves == 0)
15946       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15947                                    UndefLower, DAG);
15948 
15949     if (NumUpperHalves == 1) {
15950       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
15951       if (Subtarget.hasAVX2()) {
15952         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
15953         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
15954             !is128BitUnpackShuffleMask(HalfMask) &&
15955             (!isSingleSHUFPSMask(HalfMask) ||
15956              Subtarget.hasFastVariableShuffle()))
15957           return SDValue();
15958         // If this is a unary shuffle (assume that the 2nd operand is
15959         // canonicalized to undef), then we can use vpermpd. Otherwise, we
15960         // are better off extracting the upper half of 1 operand and using a
15961         // narrow shuffle.
15962         if (EltWidth == 64 && V2.isUndef())
15963           return SDValue();
15964       }
15965       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15966       if (Subtarget.hasAVX512() && VT.is512BitVector())
15967         return SDValue();
15968       // Extract + narrow shuffle is better than the wide alternative.
15969       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15970                                    UndefLower, DAG);
15971     }
15972 
15973     // Don't extract both uppers, instead shuffle and then extract.
15974     assert(NumUpperHalves == 2 && "Half vector count went wrong");
15975     return SDValue();
15976   }
15977 
15978   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
15979   if (NumUpperHalves == 0) {
15980     // AVX2 has efficient 64-bit element cross-lane shuffles.
15981     // TODO: Refine to account for unary shuffle, splat, and other masks?
15982     if (Subtarget.hasAVX2() && EltWidth == 64)
15983       return SDValue();
15984     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
15985     if (Subtarget.hasAVX512() && VT.is512BitVector())
15986       return SDValue();
15987     // Narrow shuffle + insert is better than the wide alternative.
15988     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
15989                                  UndefLower, DAG);
15990   }
15991 
15992   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
15993   return SDValue();
15994 }
15995 
15996 /// Test whether the specified input (0 or 1) is in-place blended by the
15997 /// given mask.
15998 ///
15999 /// This returns true if the elements from a particular input are already in the
16000 /// slot required by the given mask and require no permutation.
isShuffleMaskInputInPlace(int Input,ArrayRef<int> Mask)16001 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
16002   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
16003   int Size = Mask.size();
16004   for (int i = 0; i < Size; ++i)
16005     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
16006       return false;
16007 
16008   return true;
16009 }
16010 
16011 /// Handle case where shuffle sources are coming from the same 128-bit lane and
16012 /// every lane can be represented as the same repeating mask - allowing us to
16013 /// shuffle the sources with the repeating shuffle and then permute the result
16014 /// to the destination lanes.
lowerShuffleAsRepeatedMaskAndLanePermute(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG)16015 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
16016     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16017     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16018   int NumElts = VT.getVectorNumElements();
16019   int NumLanes = VT.getSizeInBits() / 128;
16020   int NumLaneElts = NumElts / NumLanes;
16021 
16022   // On AVX2 we may be able to just shuffle the lowest elements and then
16023   // broadcast the result.
16024   if (Subtarget.hasAVX2()) {
16025     for (unsigned BroadcastSize : {16, 32, 64}) {
16026       if (BroadcastSize <= VT.getScalarSizeInBits())
16027         continue;
16028       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
16029 
16030       // Attempt to match a repeating pattern every NumBroadcastElts,
16031       // accounting for UNDEFs but only references the lowest 128-bit
16032       // lane of the inputs.
16033       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
16034         for (int i = 0; i != NumElts; i += NumBroadcastElts)
16035           for (int j = 0; j != NumBroadcastElts; ++j) {
16036             int M = Mask[i + j];
16037             if (M < 0)
16038               continue;
16039             int &R = RepeatMask[j];
16040             if (0 != ((M % NumElts) / NumLaneElts))
16041               return false;
16042             if (0 <= R && R != M)
16043               return false;
16044             R = M;
16045           }
16046         return true;
16047       };
16048 
16049       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
16050       if (!FindRepeatingBroadcastMask(RepeatMask))
16051         continue;
16052 
16053       // Shuffle the (lowest) repeated elements in place for broadcast.
16054       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
16055 
16056       // Shuffle the actual broadcast.
16057       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
16058       for (int i = 0; i != NumElts; i += NumBroadcastElts)
16059         for (int j = 0; j != NumBroadcastElts; ++j)
16060           BroadcastMask[i + j] = j;
16061       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
16062                                   BroadcastMask);
16063     }
16064   }
16065 
16066   // Bail if the shuffle mask doesn't cross 128-bit lanes.
16067   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
16068     return SDValue();
16069 
16070   // Bail if we already have a repeated lane shuffle mask.
16071   SmallVector<int, 8> RepeatedShuffleMask;
16072   if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
16073     return SDValue();
16074 
16075   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
16076   // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
16077   int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
16078   int NumSubLanes = NumLanes * SubLaneScale;
16079   int NumSubLaneElts = NumLaneElts / SubLaneScale;
16080 
16081   // Check that all the sources are coming from the same lane and see if we can
16082   // form a repeating shuffle mask (local to each sub-lane). At the same time,
16083   // determine the source sub-lane for each destination sub-lane.
16084   int TopSrcSubLane = -1;
16085   SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
16086   SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
16087       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
16088       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
16089 
16090   for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
16091     // Extract the sub-lane mask, check that it all comes from the same lane
16092     // and normalize the mask entries to come from the first lane.
16093     int SrcLane = -1;
16094     SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
16095     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16096       int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
16097       if (M < 0)
16098         continue;
16099       int Lane = (M % NumElts) / NumLaneElts;
16100       if ((0 <= SrcLane) && (SrcLane != Lane))
16101         return SDValue();
16102       SrcLane = Lane;
16103       int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
16104       SubLaneMask[Elt] = LocalM;
16105     }
16106 
16107     // Whole sub-lane is UNDEF.
16108     if (SrcLane < 0)
16109       continue;
16110 
16111     // Attempt to match against the candidate repeated sub-lane masks.
16112     for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
16113       auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
16114         for (int i = 0; i != NumSubLaneElts; ++i) {
16115           if (M1[i] < 0 || M2[i] < 0)
16116             continue;
16117           if (M1[i] != M2[i])
16118             return false;
16119         }
16120         return true;
16121       };
16122 
16123       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
16124       if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
16125         continue;
16126 
16127       // Merge the sub-lane mask into the matching repeated sub-lane mask.
16128       for (int i = 0; i != NumSubLaneElts; ++i) {
16129         int M = SubLaneMask[i];
16130         if (M < 0)
16131           continue;
16132         assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
16133                "Unexpected mask element");
16134         RepeatedSubLaneMask[i] = M;
16135       }
16136 
16137       // Track the top most source sub-lane - by setting the remaining to UNDEF
16138       // we can greatly simplify shuffle matching.
16139       int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
16140       TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
16141       Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
16142       break;
16143     }
16144 
16145     // Bail if we failed to find a matching repeated sub-lane mask.
16146     if (Dst2SrcSubLanes[DstSubLane] < 0)
16147       return SDValue();
16148   }
16149   assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
16150          "Unexpected source lane");
16151 
16152   // Create a repeating shuffle mask for the entire vector.
16153   SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
16154   for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
16155     int Lane = SubLane / SubLaneScale;
16156     auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
16157     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16158       int M = RepeatedSubLaneMask[Elt];
16159       if (M < 0)
16160         continue;
16161       int Idx = (SubLane * NumSubLaneElts) + Elt;
16162       RepeatedMask[Idx] = M + (Lane * NumLaneElts);
16163     }
16164   }
16165   SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
16166 
16167   // Shuffle each source sub-lane to its destination.
16168   SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
16169   for (int i = 0; i != NumElts; i += NumSubLaneElts) {
16170     int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
16171     if (SrcSubLane < 0)
16172       continue;
16173     for (int j = 0; j != NumSubLaneElts; ++j)
16174       SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
16175   }
16176 
16177   return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
16178                               SubLaneMask);
16179 }
16180 
matchShuffleWithSHUFPD(MVT VT,SDValue & V1,SDValue & V2,bool & ForceV1Zero,bool & ForceV2Zero,unsigned & ShuffleImm,ArrayRef<int> Mask,const APInt & Zeroable)16181 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
16182                                    bool &ForceV1Zero, bool &ForceV2Zero,
16183                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
16184                                    const APInt &Zeroable) {
16185   int NumElts = VT.getVectorNumElements();
16186   assert(VT.getScalarSizeInBits() == 64 &&
16187          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
16188          "Unexpected data type for VSHUFPD");
16189   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
16190          "Illegal shuffle mask");
16191 
16192   bool ZeroLane[2] = { true, true };
16193   for (int i = 0; i < NumElts; ++i)
16194     ZeroLane[i & 1] &= Zeroable[i];
16195 
16196   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
16197   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
16198   ShuffleImm = 0;
16199   bool ShufpdMask = true;
16200   bool CommutableMask = true;
16201   for (int i = 0; i < NumElts; ++i) {
16202     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
16203       continue;
16204     if (Mask[i] < 0)
16205       return false;
16206     int Val = (i & 6) + NumElts * (i & 1);
16207     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
16208     if (Mask[i] < Val || Mask[i] > Val + 1)
16209       ShufpdMask = false;
16210     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
16211       CommutableMask = false;
16212     ShuffleImm |= (Mask[i] % 2) << i;
16213   }
16214 
16215   if (!ShufpdMask && !CommutableMask)
16216     return false;
16217 
16218   if (!ShufpdMask && CommutableMask)
16219     std::swap(V1, V2);
16220 
16221   ForceV1Zero = ZeroLane[0];
16222   ForceV2Zero = ZeroLane[1];
16223   return true;
16224 }
16225 
lowerShuffleWithSHUFPD(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,const X86Subtarget & Subtarget,SelectionDAG & DAG)16226 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
16227                                       SDValue V2, ArrayRef<int> Mask,
16228                                       const APInt &Zeroable,
16229                                       const X86Subtarget &Subtarget,
16230                                       SelectionDAG &DAG) {
16231   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
16232          "Unexpected data type for VSHUFPD");
16233 
16234   unsigned Immediate = 0;
16235   bool ForceV1Zero = false, ForceV2Zero = false;
16236   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
16237                               Mask, Zeroable))
16238     return SDValue();
16239 
16240   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
16241   if (ForceV1Zero)
16242     V1 = getZeroVector(VT, Subtarget, DAG, DL);
16243   if (ForceV2Zero)
16244     V2 = getZeroVector(VT, Subtarget, DAG, DL);
16245 
16246   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
16247                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
16248 }
16249 
16250 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16251 // by zeroable elements in the remaining 24 elements. Turn this into two
16252 // vmovqb instructions shuffled together.
lowerShuffleAsVTRUNCAndUnpack(const SDLoc & DL,MVT VT,SDValue V1,SDValue V2,ArrayRef<int> Mask,const APInt & Zeroable,SelectionDAG & DAG)16253 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
16254                                              SDValue V1, SDValue V2,
16255                                              ArrayRef<int> Mask,
16256                                              const APInt &Zeroable,
16257                                              SelectionDAG &DAG) {
16258   assert(VT == MVT::v32i8 && "Unexpected type!");
16259 
16260   // The first 8 indices should be every 8th element.
16261   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
16262     return SDValue();
16263 
16264   // Remaining elements need to be zeroable.
16265   if (Zeroable.countLeadingOnes() < (Mask.size() - 8))
16266     return SDValue();
16267 
16268   V1 = DAG.getBitcast(MVT::v4i64, V1);
16269   V2 = DAG.getBitcast(MVT::v4i64, V2);
16270 
16271   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
16272   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
16273 
16274   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
16275   // the upper bits of the result using an unpckldq.
16276   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
16277                                         { 0, 1, 2, 3, 16, 17, 18, 19,
16278                                           4, 5, 6, 7, 20, 21, 22, 23 });
16279   // Insert the unpckldq into a zero vector to widen to v32i8.
16280   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
16281                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
16282                      DAG.getIntPtrConstant(0, DL));
16283 }
16284 
16285 
16286 /// Handle lowering of 4-lane 64-bit floating point shuffles.
16287 ///
16288 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16289 /// isn't available.
lowerV4F64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16290 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16291                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16292                                  const X86Subtarget &Subtarget,
16293                                  SelectionDAG &DAG) {
16294   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16295   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16296   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16297 
16298   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16299                                      Subtarget, DAG))
16300     return V;
16301 
16302   if (V2.isUndef()) {
16303     // Check for being able to broadcast a single element.
16304     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16305                                                     Mask, Subtarget, DAG))
16306       return Broadcast;
16307 
16308     // Use low duplicate instructions for masks that match their pattern.
16309     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
16310       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16311 
16312     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16313       // Non-half-crossing single input shuffles can be lowered with an
16314       // interleaved permutation.
16315       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16316                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16317       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16318                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16319     }
16320 
16321     // With AVX2 we have direct support for this permutation.
16322     if (Subtarget.hasAVX2())
16323       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16324                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16325 
16326     // Try to create an in-lane repeating shuffle mask and then shuffle the
16327     // results into the target lanes.
16328     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16329             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16330       return V;
16331 
16332     // Try to permute the lanes and then use a per-lane permute.
16333     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16334                                                         Mask, DAG, Subtarget))
16335       return V;
16336 
16337     // Otherwise, fall back.
16338     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16339                                                DAG, Subtarget);
16340   }
16341 
16342   // Use dedicated unpack instructions for masks that match their pattern.
16343   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
16344     return V;
16345 
16346   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16347                                           Zeroable, Subtarget, DAG))
16348     return Blend;
16349 
16350   // Check if the blend happens to exactly fit that of SHUFPD.
16351   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16352                                           Zeroable, Subtarget, DAG))
16353     return Op;
16354 
16355   // If we have lane crossing shuffles AND they don't all come from the lower
16356   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16357   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16358   // canonicalize to a blend of splat which isn't necessary for this combine.
16359   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16360       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16361       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16362       (V2.getOpcode() != ISD::BUILD_VECTOR))
16363     if (SDValue Op = lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2,
16364                                                        Mask, DAG))
16365       return Op;
16366 
16367   // If we have one input in place, then we can permute the other input and
16368   // blend the result.
16369   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
16370     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2, Mask,
16371                                                 Subtarget, DAG);
16372 
16373   // Try to create an in-lane repeating shuffle mask and then shuffle the
16374   // results into the target lanes.
16375   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16376           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16377     return V;
16378 
16379   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16380   // shuffle. However, if we have AVX2 and either inputs are already in place,
16381   // we will be able to shuffle even across lanes the other input in a single
16382   // instruction so skip this pattern.
16383   if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
16384                                 isShuffleMaskInputInPlace(1, Mask))))
16385     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
16386             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16387       return V;
16388 
16389   // If we have VLX support, we can use VEXPAND.
16390   if (Subtarget.hasVLX())
16391     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
16392                                          DAG, Subtarget))
16393       return V;
16394 
16395   // If we have AVX2 then we always want to lower with a blend because an v4 we
16396   // can fully permute the elements.
16397   if (Subtarget.hasAVX2())
16398     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2, Mask,
16399                                                 Subtarget, DAG);
16400 
16401   // Otherwise fall back on generic lowering.
16402   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
16403                                     Subtarget, DAG);
16404 }
16405 
16406 /// Handle lowering of 4-lane 64-bit integer shuffles.
16407 ///
16408 /// This routine is only called when we have AVX2 and thus a reasonable
16409 /// instruction set for v4i64 shuffling..
lowerV4I64Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16410 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16411                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16412                                  const X86Subtarget &Subtarget,
16413                                  SelectionDAG &DAG) {
16414   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16415   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16416   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16417   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
16418 
16419   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16420                                      Subtarget, DAG))
16421     return V;
16422 
16423   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16424                                           Zeroable, Subtarget, DAG))
16425     return Blend;
16426 
16427   // Check for being able to broadcast a single element.
16428   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16429                                                   Subtarget, DAG))
16430     return Broadcast;
16431 
16432   if (V2.isUndef()) {
16433     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16434     // can use lower latency instructions that will operate on both lanes.
16435     SmallVector<int, 2> RepeatedMask;
16436     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
16437       SmallVector<int, 4> PSHUFDMask;
16438       narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
16439       return DAG.getBitcast(
16440           MVT::v4i64,
16441           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
16442                       DAG.getBitcast(MVT::v8i32, V1),
16443                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16444     }
16445 
16446     // AVX2 provides a direct instruction for permuting a single input across
16447     // lanes.
16448     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
16449                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16450   }
16451 
16452   // Try to use shift instructions.
16453   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
16454                                           Zeroable, Subtarget, DAG))
16455     return Shift;
16456 
16457   // If we have VLX support, we can use VALIGN or VEXPAND.
16458   if (Subtarget.hasVLX()) {
16459     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
16460                                               Subtarget, DAG))
16461       return Rotate;
16462 
16463     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
16464                                          DAG, Subtarget))
16465       return V;
16466   }
16467 
16468   // Try to use PALIGNR.
16469   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
16470                                                 Subtarget, DAG))
16471     return Rotate;
16472 
16473   // Use dedicated unpack instructions for masks that match their pattern.
16474   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
16475     return V;
16476 
16477   // If we have one input in place, then we can permute the other input and
16478   // blend the result.
16479   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
16480     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2, Mask,
16481                                                 Subtarget, DAG);
16482 
16483   // Try to create an in-lane repeating shuffle mask and then shuffle the
16484   // results into the target lanes.
16485   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16486           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16487     return V;
16488 
16489   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16490   // shuffle. However, if we have AVX2 and either inputs are already in place,
16491   // we will be able to shuffle even across lanes the other input in a single
16492   // instruction so skip this pattern.
16493   if (!isShuffleMaskInputInPlace(0, Mask) &&
16494       !isShuffleMaskInputInPlace(1, Mask))
16495     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16496             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16497       return Result;
16498 
16499   // Otherwise fall back on generic blend lowering.
16500   return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2, Mask,
16501                                               Subtarget, DAG);
16502 }
16503 
16504 /// Handle lowering of 8-lane 32-bit floating point shuffles.
16505 ///
16506 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
16507 /// isn't available.
lowerV8F32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16508 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16509                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16510                                  const X86Subtarget &Subtarget,
16511                                  SelectionDAG &DAG) {
16512   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16513   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16514   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16515 
16516   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
16517                                           Zeroable, Subtarget, DAG))
16518     return Blend;
16519 
16520   // Check for being able to broadcast a single element.
16521   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
16522                                                   Subtarget, DAG))
16523     return Broadcast;
16524 
16525   // If the shuffle mask is repeated in each 128-bit lane, we have many more
16526   // options to efficiently lower the shuffle.
16527   SmallVector<int, 4> RepeatedMask;
16528   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
16529     assert(RepeatedMask.size() == 4 &&
16530            "Repeated masks must be half the mask width!");
16531 
16532     // Use even/odd duplicate instructions for masks that match their pattern.
16533     if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
16534       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
16535     if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
16536       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
16537 
16538     if (V2.isUndef())
16539       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
16540                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16541 
16542     // Use dedicated unpack instructions for masks that match their pattern.
16543     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
16544       return V;
16545 
16546     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
16547     // have already handled any direct blends.
16548     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
16549   }
16550 
16551   // Try to create an in-lane repeating shuffle mask and then shuffle the
16552   // results into the target lanes.
16553   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16554           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16555     return V;
16556 
16557   // If we have a single input shuffle with different shuffle patterns in the
16558   // two 128-bit lanes use the variable mask to VPERMILPS.
16559   if (V2.isUndef()) {
16560     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
16561       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16562       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
16563     }
16564     if (Subtarget.hasAVX2()) {
16565       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16566       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
16567     }
16568     // Otherwise, fall back.
16569     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
16570                                                DAG, Subtarget);
16571   }
16572 
16573   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16574   // shuffle.
16575   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16576           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16577     return Result;
16578 
16579   // If we have VLX support, we can use VEXPAND.
16580   if (Subtarget.hasVLX())
16581     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
16582                                          DAG, Subtarget))
16583       return V;
16584 
16585   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16586   // since after split we get a more efficient code using vpunpcklwd and
16587   // vpunpckhwd instrs than vblend.
16588   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
16589     if (SDValue V = lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
16590                                                Subtarget, DAG))
16591       return V;
16592 
16593   // If we have AVX2 then we always want to lower with a blend because at v8 we
16594   // can fully permute the elements.
16595   if (Subtarget.hasAVX2())
16596     return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2, Mask,
16597                                                 Subtarget, DAG);
16598 
16599   // Otherwise fall back on generic lowering.
16600   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
16601                                     Subtarget, DAG);
16602 }
16603 
16604 /// Handle lowering of 8-lane 32-bit integer shuffles.
16605 ///
16606 /// This routine is only called when we have AVX2 and thus a reasonable
16607 /// instruction set for v8i32 shuffling..
lowerV8I32Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16608 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16609                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16610                                  const X86Subtarget &Subtarget,
16611                                  SelectionDAG &DAG) {
16612   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16613   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
16614   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16615   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
16616 
16617   // Whenever we can lower this as a zext, that instruction is strictly faster
16618   // than any alternative. It also allows us to fold memory operands into the
16619   // shuffle in many cases.
16620   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
16621                                                    Zeroable, Subtarget, DAG))
16622     return ZExt;
16623 
16624   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
16625   // since after split we get a more efficient code than vblend by using
16626   // vpunpcklwd and vpunpckhwd instrs.
16627   if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
16628       !Subtarget.hasAVX512())
16629     if (SDValue V = lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask,
16630                                                Subtarget, DAG))
16631       return V;
16632 
16633   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
16634                                           Zeroable, Subtarget, DAG))
16635     return Blend;
16636 
16637   // Check for being able to broadcast a single element.
16638   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
16639                                                   Subtarget, DAG))
16640     return Broadcast;
16641 
16642   // If the shuffle mask is repeated in each 128-bit lane we can use more
16643   // efficient instructions that mirror the shuffles across the two 128-bit
16644   // lanes.
16645   SmallVector<int, 4> RepeatedMask;
16646   bool Is128BitLaneRepeatedShuffle =
16647       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
16648   if (Is128BitLaneRepeatedShuffle) {
16649     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
16650     if (V2.isUndef())
16651       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
16652                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16653 
16654     // Use dedicated unpack instructions for masks that match their pattern.
16655     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
16656       return V;
16657   }
16658 
16659   // Try to use shift instructions.
16660   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
16661                                           Zeroable, Subtarget, DAG))
16662     return Shift;
16663 
16664   // If we have VLX support, we can use VALIGN or EXPAND.
16665   if (Subtarget.hasVLX()) {
16666     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
16667                                               Subtarget, DAG))
16668       return Rotate;
16669 
16670     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
16671                                          DAG, Subtarget))
16672       return V;
16673   }
16674 
16675   // Try to use byte rotation instructions.
16676   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
16677                                                 Subtarget, DAG))
16678     return Rotate;
16679 
16680   // Try to create an in-lane repeating shuffle mask and then shuffle the
16681   // results into the target lanes.
16682   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16683           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16684     return V;
16685 
16686   if (V2.isUndef()) {
16687     // Try to produce a fixed cross-128-bit lane permute followed by unpack
16688     // because that should be faster than the variable permute alternatives.
16689     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
16690       return V;
16691 
16692     // If the shuffle patterns aren't repeated but it's a single input, directly
16693     // generate a cross-lane VPERMD instruction.
16694     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16695     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
16696   }
16697 
16698   // Assume that a single SHUFPS is faster than an alternative sequence of
16699   // multiple instructions (even if the CPU has a domain penalty).
16700   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16701   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16702     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
16703     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
16704     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
16705                                             CastV1, CastV2, DAG);
16706     return DAG.getBitcast(MVT::v8i32, ShufPS);
16707   }
16708 
16709   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16710   // shuffle.
16711   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16712           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
16713     return Result;
16714 
16715   // Otherwise fall back on generic blend lowering.
16716   return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2, Mask,
16717                                               Subtarget, DAG);
16718 }
16719 
16720 /// Handle lowering of 16-lane 16-bit integer shuffles.
16721 ///
16722 /// This routine is only called when we have AVX2 and thus a reasonable
16723 /// instruction set for v16i16 shuffling..
lowerV16I16Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16724 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16725                                   const APInt &Zeroable, SDValue V1, SDValue V2,
16726                                   const X86Subtarget &Subtarget,
16727                                   SelectionDAG &DAG) {
16728   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16729   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
16730   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
16731   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
16732 
16733   // Whenever we can lower this as a zext, that instruction is strictly faster
16734   // than any alternative. It also allows us to fold memory operands into the
16735   // shuffle in many cases.
16736   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16737           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16738     return ZExt;
16739 
16740   // Check for being able to broadcast a single element.
16741   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
16742                                                   Subtarget, DAG))
16743     return Broadcast;
16744 
16745   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
16746                                           Zeroable, Subtarget, DAG))
16747     return Blend;
16748 
16749   // Use dedicated unpack instructions for masks that match their pattern.
16750   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
16751     return V;
16752 
16753   // Use dedicated pack instructions for masks that match their pattern.
16754   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
16755                                        Subtarget))
16756     return V;
16757 
16758   // Try to use shift instructions.
16759   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
16760                                           Zeroable, Subtarget, DAG))
16761     return Shift;
16762 
16763   // Try to use byte rotation instructions.
16764   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
16765                                                 Subtarget, DAG))
16766     return Rotate;
16767 
16768   // Try to create an in-lane repeating shuffle mask and then shuffle the
16769   // results into the target lanes.
16770   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16771           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16772     return V;
16773 
16774   if (V2.isUndef()) {
16775     // Try to use bit rotation instructions.
16776     if (SDValue Rotate =
16777             lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
16778       return Rotate;
16779 
16780     // Try to produce a fixed cross-128-bit lane permute followed by unpack
16781     // because that should be faster than the variable permute alternatives.
16782     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
16783       return V;
16784 
16785     // There are no generalized cross-lane shuffle operations available on i16
16786     // element types.
16787     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
16788       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16789               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16790         return V;
16791 
16792       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
16793                                                  DAG, Subtarget);
16794     }
16795 
16796     SmallVector<int, 8> RepeatedMask;
16797     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
16798       // As this is a single-input shuffle, the repeated mask should be
16799       // a strictly valid v8i16 mask that we can pass through to the v8i16
16800       // lowering to handle even the v16 case.
16801       return lowerV8I16GeneralSingleInputShuffle(
16802           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
16803     }
16804   }
16805 
16806   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
16807                                               Zeroable, Subtarget, DAG))
16808     return PSHUFB;
16809 
16810   // AVX512BWVL can lower to VPERMW.
16811   if (Subtarget.hasBWI() && Subtarget.hasVLX())
16812     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, DAG);
16813 
16814   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16815   // shuffle.
16816   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16817           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
16818     return Result;
16819 
16820   // Try to permute the lanes and then use a per-lane permute.
16821   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16822           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
16823     return V;
16824 
16825   // Otherwise fall back on generic lowering.
16826   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
16827                                     Subtarget, DAG);
16828 }
16829 
16830 /// Handle lowering of 32-lane 8-bit integer shuffles.
16831 ///
16832 /// This routine is only called when we have AVX2 and thus a reasonable
16833 /// instruction set for v32i8 shuffling..
lowerV32I8Shuffle(const SDLoc & DL,ArrayRef<int> Mask,const APInt & Zeroable,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)16834 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16835                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16836                                  const X86Subtarget &Subtarget,
16837                                  SelectionDAG &DAG) {
16838   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16839   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
16840   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
16841   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
16842 
16843   // Whenever we can lower this as a zext, that instruction is strictly faster
16844   // than any alternative. It also allows us to fold memory operands into the
16845   // shuffle in many cases.
16846   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
16847                                                    Zeroable, Subtarget, DAG))
16848     return ZExt;
16849 
16850   // Check for being able to broadcast a single element.
16851   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
16852                                                   Subtarget, DAG))
16853     return Broadcast;
16854 
16855   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
16856                                           Zeroable, Subtarget, DAG))
16857     return Blend;
16858 
16859   // Use dedicated unpack instructions for masks that match their pattern.
16860   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
16861     return V;
16862 
16863   // Use dedicated pack instructions for masks that match their pattern.
16864   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
16865                                        Subtarget))
16866     return V;
16867 
16868   // Try to use shift instructions.
16869   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
16870                                           Zeroable, Subtarget, DAG))
16871     return Shift;
16872 
16873   // Try to use byte rotation instructions.
16874   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
16875                                                 Subtarget, DAG))
16876     return Rotate;
16877 
16878   // Try to use bit rotation instructions.
16879   if (V2.isUndef())
16880     if (SDValue Rotate =
16881             lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
16882       return Rotate;
16883 
16884   // Try to create an in-lane repeating shuffle mask and then shuffle the
16885   // results into the target lanes.
16886   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16887           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16888     return V;
16889 
16890   // There are no generalized cross-lane shuffle operations available on i8
16891   // element types.
16892   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
16893     // Try to produce a fixed cross-128-bit lane permute followed by unpack
16894     // because that should be faster than the variable permute alternatives.
16895     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
16896       return V;
16897 
16898     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16899             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16900       return V;
16901 
16902     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
16903                                                DAG, Subtarget);
16904   }
16905 
16906   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
16907                                               Zeroable, Subtarget, DAG))
16908     return PSHUFB;
16909 
16910   // AVX512VBMIVL can lower to VPERMB.
16911   if (Subtarget.hasVBMI() && Subtarget.hasVLX())
16912     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, DAG);
16913 
16914   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16915   // shuffle.
16916   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16917           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
16918     return Result;
16919 
16920   // Try to permute the lanes and then use a per-lane permute.
16921   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16922           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
16923     return V;
16924 
16925   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16926   // by zeroable elements in the remaining 24 elements. Turn this into two
16927   // vmovqb instructions shuffled together.
16928   if (Subtarget.hasVLX())
16929     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
16930                                                   Mask, Zeroable, DAG))
16931       return V;
16932 
16933   // Otherwise fall back on generic lowering.
16934   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
16935                                     Subtarget, DAG);
16936 }
16937 
16938 /// High-level routine to lower various 256-bit x86 vector shuffles.
16939 ///
16940 /// This routine either breaks down the specific type of a 256-bit x86 vector
16941 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
16942 /// 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)16943 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
16944                                   SDValue V1, SDValue V2, const APInt &Zeroable,
16945                                   const X86Subtarget &Subtarget,
16946                                   SelectionDAG &DAG) {
16947   // If we have a single input to the zero element, insert that into V1 if we
16948   // can do so cheaply.
16949   int NumElts = VT.getVectorNumElements();
16950   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
16951 
16952   if (NumV2Elements == 1 && Mask[0] >= NumElts)
16953     if (SDValue Insertion = lowerShuffleAsElementInsertion(
16954             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
16955       return Insertion;
16956 
16957   // Handle special cases where the lower or upper half is UNDEF.
16958   if (SDValue V =
16959           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
16960     return V;
16961 
16962   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
16963   // can check for those subtargets here and avoid much of the subtarget
16964   // querying in the per-vector-type lowering routines. With AVX1 we have
16965   // essentially *zero* ability to manipulate a 256-bit vector with integer
16966   // types. Since we'll use floating point types there eventually, just
16967   // immediately cast everything to a float and operate entirely in that domain.
16968   if (VT.isInteger() && !Subtarget.hasAVX2()) {
16969     int ElementBits = VT.getScalarSizeInBits();
16970     if (ElementBits < 32) {
16971       // No floating point type available, if we can't use the bit operations
16972       // for masking/blending then decompose into 128-bit vectors.
16973       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
16974                                             Subtarget, DAG))
16975         return V;
16976       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
16977         return V;
16978       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
16979     }
16980 
16981     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
16982                                 VT.getVectorNumElements());
16983     V1 = DAG.getBitcast(FpVT, V1);
16984     V2 = DAG.getBitcast(FpVT, V2);
16985     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
16986   }
16987 
16988   switch (VT.SimpleTy) {
16989   case MVT::v4f64:
16990     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16991   case MVT::v4i64:
16992     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16993   case MVT::v8f32:
16994     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16995   case MVT::v8i32:
16996     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16997   case MVT::v16i16:
16998     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16999   case MVT::v32i8:
17000     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17001 
17002   default:
17003     llvm_unreachable("Not a valid 256-bit x86 vector type!");
17004   }
17005 }
17006 
17007 /// 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)17008 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
17009                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17010                                   const X86Subtarget &Subtarget,
17011                                   SelectionDAG &DAG) {
17012   assert(VT.getScalarSizeInBits() == 64 &&
17013          "Unexpected element type size for 128bit shuffle.");
17014 
17015   // To handle 256 bit vector requires VLX and most probably
17016   // function lowerV2X128VectorShuffle() is better solution.
17017   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
17018 
17019   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
17020   SmallVector<int, 4> Widened128Mask;
17021   if (!canWidenShuffleElements(Mask, Widened128Mask))
17022     return SDValue();
17023   assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
17024 
17025   // Try to use an insert into a zero vector.
17026   if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
17027       (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
17028     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
17029     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
17030     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17031                               DAG.getIntPtrConstant(0, DL));
17032     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17033                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
17034                        DAG.getIntPtrConstant(0, DL));
17035   }
17036 
17037   // Check for patterns which can be matched with a single insert of a 256-bit
17038   // subvector.
17039   bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 2, 3, 0, 1, 2, 3});
17040   if (OnlyUsesV1 ||
17041       isShuffleEquivalent(V1, V2, Mask, {0, 1, 2, 3, 8, 9, 10, 11})) {
17042     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
17043     SDValue SubVec =
17044         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
17045                     DAG.getIntPtrConstant(0, DL));
17046     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17047                        DAG.getIntPtrConstant(4, DL));
17048   }
17049 
17050   // See if this is an insertion of the lower 128-bits of V2 into V1.
17051   bool IsInsert = true;
17052   int V2Index = -1;
17053   for (int i = 0; i < 4; ++i) {
17054     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17055     if (Widened128Mask[i] < 0)
17056       continue;
17057 
17058     // Make sure all V1 subvectors are in place.
17059     if (Widened128Mask[i] < 4) {
17060       if (Widened128Mask[i] != i) {
17061         IsInsert = false;
17062         break;
17063       }
17064     } else {
17065       // Make sure we only have a single V2 index and its the lowest 128-bits.
17066       if (V2Index >= 0 || Widened128Mask[i] != 4) {
17067         IsInsert = false;
17068         break;
17069       }
17070       V2Index = i;
17071     }
17072   }
17073   if (IsInsert && V2Index >= 0) {
17074     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17075     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
17076                                  DAG.getIntPtrConstant(0, DL));
17077     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
17078   }
17079 
17080   // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
17081   // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
17082   // possible we at least ensure the lanes stay sequential to help later
17083   // combines.
17084   SmallVector<int, 2> Widened256Mask;
17085   if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
17086     Widened128Mask.clear();
17087     narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
17088   }
17089 
17090   // Try to lower to vshuf64x2/vshuf32x4.
17091   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
17092   unsigned PermMask = 0;
17093   // Insure elements came from the same Op.
17094   for (int i = 0; i < 4; ++i) {
17095     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17096     if (Widened128Mask[i] < 0)
17097       continue;
17098 
17099     SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
17100     unsigned OpIndex = i / 2;
17101     if (Ops[OpIndex].isUndef())
17102       Ops[OpIndex] = Op;
17103     else if (Ops[OpIndex] != Op)
17104       return SDValue();
17105 
17106     // Convert the 128-bit shuffle mask selection values into 128-bit selection
17107     // bits defined by a vshuf64x2 instruction's immediate control byte.
17108     PermMask |= (Widened128Mask[i] % 4) << (i * 2);
17109   }
17110 
17111   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
17112                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
17113 }
17114 
17115 /// 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)17116 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17117                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17118                                  const X86Subtarget &Subtarget,
17119                                  SelectionDAG &DAG) {
17120   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17121   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17122   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17123 
17124   if (V2.isUndef()) {
17125     // Use low duplicate instructions for masks that match their pattern.
17126     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
17127       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
17128 
17129     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
17130       // Non-half-crossing single input shuffles can be lowered with an
17131       // interleaved permutation.
17132       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17133                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
17134                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
17135                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
17136       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
17137                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17138     }
17139 
17140     SmallVector<int, 4> RepeatedMask;
17141     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
17142       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
17143                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17144   }
17145 
17146   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
17147                                            V2, Subtarget, DAG))
17148     return Shuf128;
17149 
17150   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
17151     return Unpck;
17152 
17153   // Check if the blend happens to exactly fit that of SHUFPD.
17154   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
17155                                           Zeroable, Subtarget, DAG))
17156     return Op;
17157 
17158   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
17159                                        DAG, Subtarget))
17160     return V;
17161 
17162   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
17163                                           Zeroable, Subtarget, DAG))
17164     return Blend;
17165 
17166   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
17167 }
17168 
17169 /// 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)17170 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17171                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17172                                   const X86Subtarget &Subtarget,
17173                                   SelectionDAG &DAG) {
17174   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17175   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17176   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17177 
17178   // If the shuffle mask is repeated in each 128-bit lane, we have many more
17179   // options to efficiently lower the shuffle.
17180   SmallVector<int, 4> RepeatedMask;
17181   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17182     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17183 
17184     // Use even/odd duplicate instructions for masks that match their pattern.
17185     if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
17186       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17187     if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
17188       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17189 
17190     if (V2.isUndef())
17191       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17192                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17193 
17194     // Use dedicated unpack instructions for masks that match their pattern.
17195     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
17196       return V;
17197 
17198     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17199                                             Zeroable, Subtarget, DAG))
17200       return Blend;
17201 
17202     // Otherwise, fall back to a SHUFPS sequence.
17203     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17204   }
17205 
17206   // Try to create an in-lane repeating shuffle mask and then shuffle the
17207   // results into the target lanes.
17208   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17209           DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17210     return V;
17211 
17212   // If we have a single input shuffle with different shuffle patterns in the
17213   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17214   if (V2.isUndef() &&
17215       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17216     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17217     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17218   }
17219 
17220   // If we have AVX512F support, we can use VEXPAND.
17221   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
17222                                              V1, V2, DAG, Subtarget))
17223     return V;
17224 
17225   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
17226 }
17227 
17228 /// 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)17229 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17230                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17231                                  const X86Subtarget &Subtarget,
17232                                  SelectionDAG &DAG) {
17233   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17234   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17235   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17236 
17237   if (V2.isUndef()) {
17238     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17239     // can use lower latency instructions that will operate on all four
17240     // 128-bit lanes.
17241     SmallVector<int, 2> Repeated128Mask;
17242     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17243       SmallVector<int, 4> PSHUFDMask;
17244       narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17245       return DAG.getBitcast(
17246           MVT::v8i64,
17247           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17248                       DAG.getBitcast(MVT::v16i32, V1),
17249                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17250     }
17251 
17252     SmallVector<int, 4> Repeated256Mask;
17253     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17254       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17255                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17256   }
17257 
17258   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17259                                            V2, Subtarget, DAG))
17260     return Shuf128;
17261 
17262   // Try to use shift instructions.
17263   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
17264                                           Zeroable, Subtarget, DAG))
17265     return Shift;
17266 
17267   // Try to use VALIGN.
17268   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17269                                             Subtarget, DAG))
17270     return Rotate;
17271 
17272   // Try to use PALIGNR.
17273   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17274                                                 Subtarget, DAG))
17275     return Rotate;
17276 
17277   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
17278     return Unpck;
17279   // If we have AVX512F support, we can use VEXPAND.
17280   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
17281                                        DAG, Subtarget))
17282     return V;
17283 
17284   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17285                                           Zeroable, Subtarget, DAG))
17286     return Blend;
17287 
17288   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
17289 }
17290 
17291 /// 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)17292 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17293                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17294                                   const X86Subtarget &Subtarget,
17295                                   SelectionDAG &DAG) {
17296   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17297   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17298   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17299 
17300   // Whenever we can lower this as a zext, that instruction is strictly faster
17301   // than any alternative. It also allows us to fold memory operands into the
17302   // shuffle in many cases.
17303   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17304           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17305     return ZExt;
17306 
17307   // If the shuffle mask is repeated in each 128-bit lane we can use more
17308   // efficient instructions that mirror the shuffles across the four 128-bit
17309   // lanes.
17310   SmallVector<int, 4> RepeatedMask;
17311   bool Is128BitLaneRepeatedShuffle =
17312       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17313   if (Is128BitLaneRepeatedShuffle) {
17314     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17315     if (V2.isUndef())
17316       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17317                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17318 
17319     // Use dedicated unpack instructions for masks that match their pattern.
17320     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
17321       return V;
17322   }
17323 
17324   // Try to use shift instructions.
17325   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
17326                                           Zeroable, Subtarget, DAG))
17327     return Shift;
17328 
17329   // Try to use VALIGN.
17330   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
17331                                             Subtarget, DAG))
17332     return Rotate;
17333 
17334   // Try to use byte rotation instructions.
17335   if (Subtarget.hasBWI())
17336     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
17337                                                   Subtarget, DAG))
17338       return Rotate;
17339 
17340   // Assume that a single SHUFPS is faster than using a permv shuffle.
17341   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17342   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17343     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
17344     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
17345     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
17346                                             CastV1, CastV2, DAG);
17347     return DAG.getBitcast(MVT::v16i32, ShufPS);
17348   }
17349 
17350   // Try to create an in-lane repeating shuffle mask and then shuffle the
17351   // results into the target lanes.
17352   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17353           DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
17354     return V;
17355 
17356   // If we have AVX512F support, we can use VEXPAND.
17357   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
17358                                        DAG, Subtarget))
17359     return V;
17360 
17361   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
17362                                           Zeroable, Subtarget, DAG))
17363     return Blend;
17364 
17365   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
17366 }
17367 
17368 /// 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)17369 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17370                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17371                                   const X86Subtarget &Subtarget,
17372                                   SelectionDAG &DAG) {
17373   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
17374   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
17375   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17376   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
17377 
17378   // Whenever we can lower this as a zext, that instruction is strictly faster
17379   // than any alternative. It also allows us to fold memory operands into the
17380   // shuffle in many cases.
17381   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17382           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17383     return ZExt;
17384 
17385   // Use dedicated unpack instructions for masks that match their pattern.
17386   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
17387     return V;
17388 
17389   // Use dedicated pack instructions for masks that match their pattern.
17390   if (SDValue V =
17391           lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
17392     return V;
17393 
17394   // Try to use shift instructions.
17395   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
17396                                           Zeroable, Subtarget, DAG))
17397     return Shift;
17398 
17399   // Try to use byte rotation instructions.
17400   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
17401                                                 Subtarget, DAG))
17402     return Rotate;
17403 
17404   if (V2.isUndef()) {
17405     // Try to use bit rotation instructions.
17406     if (SDValue Rotate =
17407             lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
17408       return Rotate;
17409 
17410     SmallVector<int, 8> RepeatedMask;
17411     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
17412       // As this is a single-input shuffle, the repeated mask should be
17413       // a strictly valid v8i16 mask that we can pass through to the v8i16
17414       // lowering to handle even the v32 case.
17415       return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
17416                                                  RepeatedMask, Subtarget, DAG);
17417     }
17418   }
17419 
17420   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
17421                                           Zeroable, Subtarget, DAG))
17422     return Blend;
17423 
17424   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
17425                                               Zeroable, Subtarget, DAG))
17426     return PSHUFB;
17427 
17428   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
17429 }
17430 
17431 /// 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)17432 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17433                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17434                                  const X86Subtarget &Subtarget,
17435                                  SelectionDAG &DAG) {
17436   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
17437   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
17438   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
17439   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
17440 
17441   // Whenever we can lower this as a zext, that instruction is strictly faster
17442   // than any alternative. It also allows us to fold memory operands into the
17443   // shuffle in many cases.
17444   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17445           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
17446     return ZExt;
17447 
17448   // Use dedicated unpack instructions for masks that match their pattern.
17449   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
17450     return V;
17451 
17452   // Use dedicated pack instructions for masks that match their pattern.
17453   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
17454                                        Subtarget))
17455     return V;
17456 
17457   // Try to use shift instructions.
17458   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
17459                                           Zeroable, Subtarget, DAG))
17460     return Shift;
17461 
17462   // Try to use byte rotation instructions.
17463   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
17464                                                 Subtarget, DAG))
17465     return Rotate;
17466 
17467   // Try to use bit rotation instructions.
17468   if (V2.isUndef())
17469     if (SDValue Rotate =
17470             lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
17471       return Rotate;
17472 
17473   // Lower as AND if possible.
17474   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
17475                                              Zeroable, Subtarget, DAG))
17476     return Masked;
17477 
17478   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
17479                                               Zeroable, Subtarget, DAG))
17480     return PSHUFB;
17481 
17482   // VBMI can use VPERMV/VPERMV3 byte shuffles.
17483   if (Subtarget.hasVBMI())
17484     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, DAG);
17485 
17486   // Try to create an in-lane repeating shuffle mask and then shuffle the
17487   // results into the target lanes.
17488   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17489           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17490     return V;
17491 
17492   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
17493                                           Zeroable, Subtarget, DAG))
17494     return Blend;
17495 
17496   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17497   // shuffle.
17498   if (!V2.isUndef())
17499     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17500             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17501       return Result;
17502 
17503   // FIXME: Implement direct support for this type!
17504   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
17505 }
17506 
17507 /// High-level routine to lower various 512-bit x86 vector shuffles.
17508 ///
17509 /// This routine either breaks down the specific type of a 512-bit x86 vector
17510 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
17511 /// 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)17512 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17513                                   MVT VT, SDValue V1, SDValue V2,
17514                                   const APInt &Zeroable,
17515                                   const X86Subtarget &Subtarget,
17516                                   SelectionDAG &DAG) {
17517   assert(Subtarget.hasAVX512() &&
17518          "Cannot lower 512-bit vectors w/ basic ISA!");
17519 
17520   // If we have a single input to the zero element, insert that into V1 if we
17521   // can do so cheaply.
17522   int NumElts = Mask.size();
17523   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17524 
17525   if (NumV2Elements == 1 && Mask[0] >= NumElts)
17526     if (SDValue Insertion = lowerShuffleAsElementInsertion(
17527             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17528       return Insertion;
17529 
17530   // Handle special cases where the lower or upper half is UNDEF.
17531   if (SDValue V =
17532           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17533     return V;
17534 
17535   // Check for being able to broadcast a single element.
17536   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
17537                                                   Subtarget, DAG))
17538     return Broadcast;
17539 
17540   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
17541     // Try using bit ops for masking and blending before falling back to
17542     // splitting.
17543     if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
17544                                           Subtarget, DAG))
17545       return V;
17546     if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17547       return V;
17548 
17549     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
17550   }
17551 
17552   // Dispatch to each element type for lowering. If we don't have support for
17553   // specific element type shuffles at 512 bits, immediately split them and
17554   // lower them. Each lowering routine of a given type is allowed to assume that
17555   // the requisite ISA extensions for that element type are available.
17556   switch (VT.SimpleTy) {
17557   case MVT::v8f64:
17558     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17559   case MVT::v16f32:
17560     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17561   case MVT::v8i64:
17562     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17563   case MVT::v16i32:
17564     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17565   case MVT::v32i16:
17566     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17567   case MVT::v64i8:
17568     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17569 
17570   default:
17571     llvm_unreachable("Not a valid 512-bit x86 vector type!");
17572   }
17573 }
17574 
lower1BitShuffleAsKSHIFTR(const SDLoc & DL,ArrayRef<int> Mask,MVT VT,SDValue V1,SDValue V2,const X86Subtarget & Subtarget,SelectionDAG & DAG)17575 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
17576                                          MVT VT, SDValue V1, SDValue V2,
17577                                          const X86Subtarget &Subtarget,
17578                                          SelectionDAG &DAG) {
17579   // Shuffle should be unary.
17580   if (!V2.isUndef())
17581     return SDValue();
17582 
17583   int ShiftAmt = -1;
17584   int NumElts = Mask.size();
17585   for (int i = 0; i != NumElts; ++i) {
17586     int M = Mask[i];
17587     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
17588            "Unexpected mask index.");
17589     if (M < 0)
17590       continue;
17591 
17592     // The first non-undef element determines our shift amount.
17593     if (ShiftAmt < 0) {
17594       ShiftAmt = M - i;
17595       // Need to be shifting right.
17596       if (ShiftAmt <= 0)
17597         return SDValue();
17598     }
17599     // All non-undef elements must shift by the same amount.
17600     if (ShiftAmt != M - i)
17601       return SDValue();
17602   }
17603   assert(ShiftAmt >= 0 && "All undef?");
17604 
17605   // Great we found a shift right.
17606   MVT WideVT = VT;
17607   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
17608     WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
17609   SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
17610                             DAG.getUNDEF(WideVT), V1,
17611                             DAG.getIntPtrConstant(0, DL));
17612   Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
17613                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17614   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17615                      DAG.getIntPtrConstant(0, DL));
17616 }
17617 
17618 // Determine if this shuffle can be implemented with a KSHIFT instruction.
17619 // Returns the shift amount if possible or -1 if not. This is a simplified
17620 // version of matchShuffleAsShift.
match1BitShuffleAsKSHIFT(unsigned & Opcode,ArrayRef<int> Mask,int MaskOffset,const APInt & Zeroable)17621 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
17622                                     int MaskOffset, const APInt &Zeroable) {
17623   int Size = Mask.size();
17624 
17625   auto CheckZeros = [&](int Shift, bool Left) {
17626     for (int j = 0; j < Shift; ++j)
17627       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
17628         return false;
17629 
17630     return true;
17631   };
17632 
17633   auto MatchShift = [&](int Shift, bool Left) {
17634     unsigned Pos = Left ? Shift : 0;
17635     unsigned Low = Left ? 0 : Shift;
17636     unsigned Len = Size - Shift;
17637     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
17638   };
17639 
17640   for (int Shift = 1; Shift != Size; ++Shift)
17641     for (bool Left : {true, false})
17642       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
17643         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
17644         return Shift;
17645       }
17646 
17647   return -1;
17648 }
17649 
17650 
17651 // Lower vXi1 vector shuffles.
17652 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
17653 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
17654 // 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)17655 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17656                                 MVT VT, SDValue V1, SDValue V2,
17657                                 const APInt &Zeroable,
17658                                 const X86Subtarget &Subtarget,
17659                                 SelectionDAG &DAG) {
17660   assert(Subtarget.hasAVX512() &&
17661          "Cannot lower 512-bit vectors w/o basic ISA!");
17662 
17663   int NumElts = Mask.size();
17664 
17665   // Try to recognize shuffles that are just padding a subvector with zeros.
17666   int SubvecElts = 0;
17667   int Src = -1;
17668   for (int i = 0; i != NumElts; ++i) {
17669     if (Mask[i] >= 0) {
17670       // Grab the source from the first valid mask. All subsequent elements need
17671       // to use this same source.
17672       if (Src < 0)
17673         Src = Mask[i] / NumElts;
17674       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
17675         break;
17676     }
17677 
17678     ++SubvecElts;
17679   }
17680   assert(SubvecElts != NumElts && "Identity shuffle?");
17681 
17682   // Clip to a power 2.
17683   SubvecElts = PowerOf2Floor(SubvecElts);
17684 
17685   // Make sure the number of zeroable bits in the top at least covers the bits
17686   // not covered by the subvector.
17687   if ((int)Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
17688     assert(Src >= 0 && "Expected a source!");
17689     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
17690     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
17691                                   Src == 0 ? V1 : V2,
17692                                   DAG.getIntPtrConstant(0, DL));
17693     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17694                        DAG.getConstant(0, DL, VT),
17695                        Extract, DAG.getIntPtrConstant(0, DL));
17696   }
17697 
17698   // Try a simple shift right with undef elements. Later we'll try with zeros.
17699   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
17700                                                 DAG))
17701     return Shift;
17702 
17703   // Try to match KSHIFTs.
17704   unsigned Offset = 0;
17705   for (SDValue V : { V1, V2 }) {
17706     unsigned Opcode;
17707     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
17708     if (ShiftAmt >= 0) {
17709       MVT WideVT = VT;
17710       if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
17711         WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
17712       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
17713                                 DAG.getUNDEF(WideVT), V,
17714                                 DAG.getIntPtrConstant(0, DL));
17715       // Widened right shifts need two shifts to ensure we shift in zeroes.
17716       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
17717         int WideElts = WideVT.getVectorNumElements();
17718         // Shift left to put the original vector in the MSBs of the new size.
17719         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
17720                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
17721         // Increase the shift amount to account for the left shift.
17722         ShiftAmt += WideElts - NumElts;
17723       }
17724 
17725       Res = DAG.getNode(Opcode, DL, WideVT, Res,
17726                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
17727       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
17728                          DAG.getIntPtrConstant(0, DL));
17729     }
17730     Offset += NumElts; // Increment for next iteration.
17731   }
17732 
17733 
17734 
17735   MVT ExtVT;
17736   switch (VT.SimpleTy) {
17737   default:
17738     llvm_unreachable("Expected a vector of i1 elements");
17739   case MVT::v2i1:
17740     ExtVT = MVT::v2i64;
17741     break;
17742   case MVT::v4i1:
17743     ExtVT = MVT::v4i32;
17744     break;
17745   case MVT::v8i1:
17746     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
17747     // shuffle.
17748     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
17749     break;
17750   case MVT::v16i1:
17751     // Take 512-bit type, unless we are avoiding 512-bit types and have the
17752     // 256-bit operation available.
17753     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
17754     break;
17755   case MVT::v32i1:
17756     // Take 512-bit type, unless we are avoiding 512-bit types and have the
17757     // 256-bit operation available.
17758     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
17759     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
17760     break;
17761   case MVT::v64i1:
17762     // Fall back to scalarization. FIXME: We can do better if the shuffle
17763     // can be partitioned cleanly.
17764     if (!Subtarget.useBWIRegs())
17765       return SDValue();
17766     ExtVT = MVT::v64i8;
17767     break;
17768   }
17769 
17770   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
17771   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
17772 
17773   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
17774   // i1 was sign extended we can use X86ISD::CVT2MASK.
17775   int NumElems = VT.getVectorNumElements();
17776   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
17777       (Subtarget.hasDQI() && (NumElems < 32)))
17778     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
17779                        Shuffle, ISD::SETGT);
17780 
17781   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
17782 }
17783 
17784 /// Helper function that returns true if the shuffle mask should be
17785 /// commuted to improve canonicalization.
canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask)17786 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
17787   int NumElements = Mask.size();
17788 
17789   int NumV1Elements = 0, NumV2Elements = 0;
17790   for (int M : Mask)
17791     if (M < 0)
17792       continue;
17793     else if (M < NumElements)
17794       ++NumV1Elements;
17795     else
17796       ++NumV2Elements;
17797 
17798   // Commute the shuffle as needed such that more elements come from V1 than
17799   // V2. This allows us to match the shuffle pattern strictly on how many
17800   // elements come from V1 without handling the symmetric cases.
17801   if (NumV2Elements > NumV1Elements)
17802     return true;
17803 
17804   assert(NumV1Elements > 0 && "No V1 indices");
17805 
17806   if (NumV2Elements == 0)
17807     return false;
17808 
17809   // When the number of V1 and V2 elements are the same, try to minimize the
17810   // number of uses of V2 in the low half of the vector. When that is tied,
17811   // ensure that the sum of indices for V1 is equal to or lower than the sum
17812   // indices for V2. When those are equal, try to ensure that the number of odd
17813   // indices for V1 is lower than the number of odd indices for V2.
17814   if (NumV1Elements == NumV2Elements) {
17815     int LowV1Elements = 0, LowV2Elements = 0;
17816     for (int M : Mask.slice(0, NumElements / 2))
17817       if (M >= NumElements)
17818         ++LowV2Elements;
17819       else if (M >= 0)
17820         ++LowV1Elements;
17821     if (LowV2Elements > LowV1Elements)
17822       return true;
17823     if (LowV2Elements == LowV1Elements) {
17824       int SumV1Indices = 0, SumV2Indices = 0;
17825       for (int i = 0, Size = Mask.size(); i < Size; ++i)
17826         if (Mask[i] >= NumElements)
17827           SumV2Indices += i;
17828         else if (Mask[i] >= 0)
17829           SumV1Indices += i;
17830       if (SumV2Indices < SumV1Indices)
17831         return true;
17832       if (SumV2Indices == SumV1Indices) {
17833         int NumV1OddIndices = 0, NumV2OddIndices = 0;
17834         for (int i = 0, Size = Mask.size(); i < Size; ++i)
17835           if (Mask[i] >= NumElements)
17836             NumV2OddIndices += i % 2;
17837           else if (Mask[i] >= 0)
17838             NumV1OddIndices += i % 2;
17839         if (NumV2OddIndices < NumV1OddIndices)
17840           return true;
17841       }
17842     }
17843   }
17844 
17845   return false;
17846 }
17847 
17848 /// Top-level lowering for x86 vector shuffles.
17849 ///
17850 /// This handles decomposition, canonicalization, and lowering of all x86
17851 /// vector shuffles. Most of the specific lowering strategies are encapsulated
17852 /// above in helper routines. The canonicalization attempts to widen shuffles
17853 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
17854 /// s.t. only one of the two inputs needs to be tested, etc.
lowerVECTOR_SHUFFLE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17855 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
17856                                    SelectionDAG &DAG) {
17857   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
17858   ArrayRef<int> OrigMask = SVOp->getMask();
17859   SDValue V1 = Op.getOperand(0);
17860   SDValue V2 = Op.getOperand(1);
17861   MVT VT = Op.getSimpleValueType();
17862   int NumElements = VT.getVectorNumElements();
17863   SDLoc DL(Op);
17864   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
17865 
17866   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
17867          "Can't lower MMX shuffles");
17868 
17869   bool V1IsUndef = V1.isUndef();
17870   bool V2IsUndef = V2.isUndef();
17871   if (V1IsUndef && V2IsUndef)
17872     return DAG.getUNDEF(VT);
17873 
17874   // When we create a shuffle node we put the UNDEF node to second operand,
17875   // but in some cases the first operand may be transformed to UNDEF.
17876   // In this case we should just commute the node.
17877   if (V1IsUndef)
17878     return DAG.getCommutedVectorShuffle(*SVOp);
17879 
17880   // Check for non-undef masks pointing at an undef vector and make the masks
17881   // undef as well. This makes it easier to match the shuffle based solely on
17882   // the mask.
17883   if (V2IsUndef &&
17884       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
17885     SmallVector<int, 8> NewMask(OrigMask.begin(), OrigMask.end());
17886     for (int &M : NewMask)
17887       if (M >= NumElements)
17888         M = -1;
17889     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
17890   }
17891 
17892   // Check for illegal shuffle mask element index values.
17893   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
17894   (void)MaskUpperLimit;
17895   assert(llvm::all_of(OrigMask,
17896                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
17897          "Out of bounds shuffle index");
17898 
17899   // We actually see shuffles that are entirely re-arrangements of a set of
17900   // zero inputs. This mostly happens while decomposing complex shuffles into
17901   // simple ones. Directly lower these as a buildvector of zeros.
17902   APInt KnownUndef, KnownZero;
17903   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
17904 
17905   APInt Zeroable = KnownUndef | KnownZero;
17906   if (Zeroable.isAllOnesValue())
17907     return getZeroVector(VT, Subtarget, DAG, DL);
17908 
17909   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
17910 
17911   // Try to collapse shuffles into using a vector type with fewer elements but
17912   // wider element types. We cap this to not form integers or floating point
17913   // elements wider than 64 bits, but it might be interesting to form i128
17914   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
17915   SmallVector<int, 16> WidenedMask;
17916   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
17917       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
17918     // Shuffle mask widening should not interfere with a broadcast opportunity
17919     // by obfuscating the operands with bitcasts.
17920     // TODO: Avoid lowering directly from this top-level function: make this
17921     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
17922     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
17923                                                     Subtarget, DAG))
17924       return Broadcast;
17925 
17926     MVT NewEltVT = VT.isFloatingPoint()
17927                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
17928                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
17929     int NewNumElts = NumElements / 2;
17930     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
17931     // Make sure that the new vector type is legal. For example, v2f64 isn't
17932     // legal on SSE1.
17933     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
17934       if (V2IsZero) {
17935         // Modify the new Mask to take all zeros from the all-zero vector.
17936         // Choose indices that are blend-friendly.
17937         bool UsedZeroVector = false;
17938         assert(find(WidenedMask, SM_SentinelZero) != WidenedMask.end() &&
17939                "V2's non-undef elements are used?!");
17940         for (int i = 0; i != NewNumElts; ++i)
17941           if (WidenedMask[i] == SM_SentinelZero) {
17942             WidenedMask[i] = i + NewNumElts;
17943             UsedZeroVector = true;
17944           }
17945         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
17946         // some elements to be undef.
17947         if (UsedZeroVector)
17948           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
17949       }
17950       V1 = DAG.getBitcast(NewVT, V1);
17951       V2 = DAG.getBitcast(NewVT, V2);
17952       return DAG.getBitcast(
17953           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
17954     }
17955   }
17956 
17957   // Commute the shuffle if it will improve canonicalization.
17958   SmallVector<int, 64> Mask(OrigMask.begin(), OrigMask.end());
17959   if (canonicalizeShuffleMaskWithCommute(Mask)) {
17960     ShuffleVectorSDNode::commuteMask(Mask);
17961     std::swap(V1, V2);
17962   }
17963 
17964   if (SDValue V = lowerShuffleWithVPMOV(DL, Mask, VT, V1, V2, DAG, Subtarget))
17965     return V;
17966 
17967   // For each vector width, delegate to a specialized lowering routine.
17968   if (VT.is128BitVector())
17969     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17970 
17971   if (VT.is256BitVector())
17972     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17973 
17974   if (VT.is512BitVector())
17975     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17976 
17977   if (Is1BitVector)
17978     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
17979 
17980   llvm_unreachable("Unimplemented!");
17981 }
17982 
17983 /// Try to lower a VSELECT instruction to a vector shuffle.
lowerVSELECTtoVectorShuffle(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)17984 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
17985                                            const X86Subtarget &Subtarget,
17986                                            SelectionDAG &DAG) {
17987   SDValue Cond = Op.getOperand(0);
17988   SDValue LHS = Op.getOperand(1);
17989   SDValue RHS = Op.getOperand(2);
17990   MVT VT = Op.getSimpleValueType();
17991 
17992   // Only non-legal VSELECTs reach this lowering, convert those into generic
17993   // shuffles and re-use the shuffle lowering path for blends.
17994   SmallVector<int, 32> Mask;
17995   if (createShuffleMaskFromVSELECT(Mask, Cond))
17996     return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
17997 
17998   return SDValue();
17999 }
18000 
LowerVSELECT(SDValue Op,SelectionDAG & DAG) const18001 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18002   SDValue Cond = Op.getOperand(0);
18003   SDValue LHS = Op.getOperand(1);
18004   SDValue RHS = Op.getOperand(2);
18005 
18006   // A vselect where all conditions and data are constants can be optimized into
18007   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18008   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
18009       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
18010       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
18011     return SDValue();
18012 
18013   // Try to lower this to a blend-style vector shuffle. This can handle all
18014   // constant condition cases.
18015   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18016     return BlendOp;
18017 
18018   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18019   // with patterns on the mask registers on AVX-512.
18020   MVT CondVT = Cond.getSimpleValueType();
18021   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18022   if (CondEltSize == 1)
18023     return Op;
18024 
18025   // Variable blends are only legal from SSE4.1 onward.
18026   if (!Subtarget.hasSSE41())
18027     return SDValue();
18028 
18029   SDLoc dl(Op);
18030   MVT VT = Op.getSimpleValueType();
18031   unsigned EltSize = VT.getScalarSizeInBits();
18032   unsigned NumElts = VT.getVectorNumElements();
18033 
18034   // Expand v32i16/v64i8 without BWI.
18035   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18036     return SDValue();
18037 
18038   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18039   // into an i1 condition so that we can use the mask-based 512-bit blend
18040   // instructions.
18041   if (VT.getSizeInBits() == 512) {
18042     // Build a mask by testing the condition against zero.
18043     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18044     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18045                                 DAG.getConstant(0, dl, CondVT),
18046                                 ISD::SETNE);
18047     // Now return a new VSELECT using the mask.
18048     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18049   }
18050 
18051   // SEXT/TRUNC cases where the mask doesn't match the destination size.
18052   if (CondEltSize != EltSize) {
18053     // If we don't have a sign splat, rely on the expansion.
18054     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18055       return SDValue();
18056 
18057     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18058     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18059     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18060     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18061   }
18062 
18063   // Only some types will be legal on some subtargets. If we can emit a legal
18064   // VSELECT-matching blend, return Op, and but if we need to expand, return
18065   // a null value.
18066   switch (VT.SimpleTy) {
18067   default:
18068     // Most of the vector types have blends past SSE4.1.
18069     return Op;
18070 
18071   case MVT::v32i8:
18072     // The byte blends for AVX vectors were introduced only in AVX2.
18073     if (Subtarget.hasAVX2())
18074       return Op;
18075 
18076     return SDValue();
18077 
18078   case MVT::v8i16:
18079   case MVT::v16i16: {
18080     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
18081     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
18082     Cond = DAG.getBitcast(CastVT, Cond);
18083     LHS = DAG.getBitcast(CastVT, LHS);
18084     RHS = DAG.getBitcast(CastVT, RHS);
18085     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
18086     return DAG.getBitcast(VT, Select);
18087   }
18088   }
18089 }
18090 
LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,SelectionDAG & DAG)18091 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
18092   MVT VT = Op.getSimpleValueType();
18093   SDValue Vec = Op.getOperand(0);
18094   SDValue Idx = Op.getOperand(1);
18095   assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
18096   SDLoc dl(Op);
18097 
18098   if (!Vec.getSimpleValueType().is128BitVector())
18099     return SDValue();
18100 
18101   if (VT.getSizeInBits() == 8) {
18102     // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
18103     // we're going to zero extend the register or fold the store.
18104     if (llvm::isNullConstant(Idx) && !MayFoldIntoZeroExtend(Op) &&
18105         !MayFoldIntoStore(Op))
18106       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
18107                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18108                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
18109 
18110     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec, Idx);
18111     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18112   }
18113 
18114   if (VT == MVT::f32) {
18115     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
18116     // the result back to FR32 register. It's only worth matching if the
18117     // result has a single use which is a store or a bitcast to i32.  And in
18118     // the case of a store, it's not worth it if the index is a constant 0,
18119     // because a MOVSSmr can be used instead, which is smaller and faster.
18120     if (!Op.hasOneUse())
18121       return SDValue();
18122     SDNode *User = *Op.getNode()->use_begin();
18123     if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
18124         (User->getOpcode() != ISD::BITCAST ||
18125          User->getValueType(0) != MVT::i32))
18126       return SDValue();
18127     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18128                                   DAG.getBitcast(MVT::v4i32, Vec), Idx);
18129     return DAG.getBitcast(MVT::f32, Extract);
18130   }
18131 
18132   if (VT == MVT::i32 || VT == MVT::i64)
18133       return Op;
18134 
18135   return SDValue();
18136 }
18137 
18138 /// Extract one bit from mask vector, like v16i1 or v8i1.
18139 /// AVX-512 feature.
ExtractBitFromMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18140 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
18141                                         const X86Subtarget &Subtarget) {
18142   SDValue Vec = Op.getOperand(0);
18143   SDLoc dl(Vec);
18144   MVT VecVT = Vec.getSimpleValueType();
18145   SDValue Idx = Op.getOperand(1);
18146   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18147   MVT EltVT = Op.getSimpleValueType();
18148 
18149   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
18150          "Unexpected vector type in ExtractBitFromMaskVector");
18151 
18152   // variable index can't be handled in mask registers,
18153   // extend vector to VR512/128
18154   if (!IdxC) {
18155     unsigned NumElts = VecVT.getVectorNumElements();
18156     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
18157     // than extending to 128/256bit.
18158     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18159     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18160     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
18161     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
18162     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
18163   }
18164 
18165   unsigned IdxVal = IdxC->getZExtValue();
18166   if (IdxVal == 0) // the operation is legal
18167     return Op;
18168 
18169   // Extend to natively supported kshift.
18170   unsigned NumElems = VecVT.getVectorNumElements();
18171   MVT WideVecVT = VecVT;
18172   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
18173     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18174     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
18175                       DAG.getUNDEF(WideVecVT), Vec,
18176                       DAG.getIntPtrConstant(0, dl));
18177   }
18178 
18179   // Use kshiftr instruction to move to the lower element.
18180   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
18181                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18182 
18183   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18184                      DAG.getIntPtrConstant(0, dl));
18185 }
18186 
18187 SDValue
LowerEXTRACT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const18188 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
18189                                            SelectionDAG &DAG) const {
18190   SDLoc dl(Op);
18191   SDValue Vec = Op.getOperand(0);
18192   MVT VecVT = Vec.getSimpleValueType();
18193   SDValue Idx = Op.getOperand(1);
18194   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18195 
18196   if (VecVT.getVectorElementType() == MVT::i1)
18197     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
18198 
18199   if (!IdxC) {
18200     // Its more profitable to go through memory (1 cycles throughput)
18201     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
18202     // IACA tool was used to get performance estimation
18203     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
18204     //
18205     // example : extractelement <16 x i8> %a, i32 %i
18206     //
18207     // Block Throughput: 3.00 Cycles
18208     // Throughput Bottleneck: Port5
18209     //
18210     // | Num Of |   Ports pressure in cycles  |    |
18211     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
18212     // ---------------------------------------------
18213     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
18214     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
18215     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
18216     // Total Num Of Uops: 4
18217     //
18218     //
18219     // Block Throughput: 1.00 Cycles
18220     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
18221     //
18222     // |    |  Ports pressure in cycles   |  |
18223     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
18224     // ---------------------------------------------------------
18225     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
18226     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
18227     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
18228     // Total Num Of Uops: 4
18229 
18230     return SDValue();
18231   }
18232 
18233   unsigned IdxVal = IdxC->getZExtValue();
18234 
18235   // If this is a 256-bit vector result, first extract the 128-bit vector and
18236   // then extract the element from the 128-bit vector.
18237   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
18238     // Get the 128-bit vector.
18239     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
18240     MVT EltVT = VecVT.getVectorElementType();
18241 
18242     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
18243     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
18244 
18245     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
18246     // this can be done with a mask.
18247     IdxVal &= ElemsPerChunk - 1;
18248     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18249                        DAG.getIntPtrConstant(IdxVal, dl));
18250   }
18251 
18252   assert(VecVT.is128BitVector() && "Unexpected vector length");
18253 
18254   MVT VT = Op.getSimpleValueType();
18255 
18256   if (VT.getSizeInBits() == 16) {
18257     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
18258     // we're going to zero extend the register or fold the store (SSE41 only).
18259     if (IdxVal == 0 && !MayFoldIntoZeroExtend(Op) &&
18260         !(Subtarget.hasSSE41() && MayFoldIntoStore(Op)))
18261       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
18262                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18263                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
18264 
18265     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec, Idx);
18266     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18267   }
18268 
18269   if (Subtarget.hasSSE41())
18270     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
18271       return Res;
18272 
18273   // TODO: We only extract a single element from v16i8, we can probably afford
18274   // to be more aggressive here before using the default approach of spilling to
18275   // stack.
18276   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
18277     // Extract either the lowest i32 or any i16, and extract the sub-byte.
18278     int DWordIdx = IdxVal / 4;
18279     if (DWordIdx == 0) {
18280       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18281                                 DAG.getBitcast(MVT::v4i32, Vec),
18282                                 DAG.getIntPtrConstant(DWordIdx, dl));
18283       int ShiftVal = (IdxVal % 4) * 8;
18284       if (ShiftVal != 0)
18285         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
18286                           DAG.getConstant(ShiftVal, dl, MVT::i8));
18287       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18288     }
18289 
18290     int WordIdx = IdxVal / 2;
18291     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
18292                               DAG.getBitcast(MVT::v8i16, Vec),
18293                               DAG.getIntPtrConstant(WordIdx, dl));
18294     int ShiftVal = (IdxVal % 2) * 8;
18295     if (ShiftVal != 0)
18296       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
18297                         DAG.getConstant(ShiftVal, dl, MVT::i8));
18298     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18299   }
18300 
18301   if (VT.getSizeInBits() == 32) {
18302     if (IdxVal == 0)
18303       return Op;
18304 
18305     // SHUFPS the element to the lowest double word, then movss.
18306     int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
18307     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18308     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18309                        DAG.getIntPtrConstant(0, dl));
18310   }
18311 
18312   if (VT.getSizeInBits() == 64) {
18313     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
18314     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
18315     //        to match extract_elt for f64.
18316     if (IdxVal == 0)
18317       return Op;
18318 
18319     // UNPCKHPD the element to the lowest double word, then movsd.
18320     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
18321     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
18322     int Mask[2] = { 1, -1 };
18323     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18324     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18325                        DAG.getIntPtrConstant(0, dl));
18326   }
18327 
18328   return SDValue();
18329 }
18330 
18331 /// Insert one bit to mask vector, like v16i1 or v8i1.
18332 /// AVX-512 feature.
InsertBitToMaskVector(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)18333 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
18334                                      const X86Subtarget &Subtarget) {
18335   SDLoc dl(Op);
18336   SDValue Vec = Op.getOperand(0);
18337   SDValue Elt = Op.getOperand(1);
18338   SDValue Idx = Op.getOperand(2);
18339   MVT VecVT = Vec.getSimpleValueType();
18340 
18341   if (!isa<ConstantSDNode>(Idx)) {
18342     // Non constant index. Extend source and destination,
18343     // insert element and then truncate the result.
18344     unsigned NumElts = VecVT.getVectorNumElements();
18345     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18346     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18347     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
18348       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
18349       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
18350     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
18351   }
18352 
18353   // Copy into a k-register, extract to v1i1 and insert_subvector.
18354   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
18355   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
18356 }
18357 
LowerINSERT_VECTOR_ELT(SDValue Op,SelectionDAG & DAG) const18358 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
18359                                                   SelectionDAG &DAG) const {
18360   MVT VT = Op.getSimpleValueType();
18361   MVT EltVT = VT.getVectorElementType();
18362   unsigned NumElts = VT.getVectorNumElements();
18363 
18364   if (EltVT == MVT::i1)
18365     return InsertBitToMaskVector(Op, DAG, Subtarget);
18366 
18367   SDLoc dl(Op);
18368   SDValue N0 = Op.getOperand(0);
18369   SDValue N1 = Op.getOperand(1);
18370   SDValue N2 = Op.getOperand(2);
18371 
18372   auto *N2C = dyn_cast<ConstantSDNode>(N2);
18373   if (!N2C || N2C->getAPIntValue().uge(NumElts))
18374     return SDValue();
18375   uint64_t IdxVal = N2C->getZExtValue();
18376 
18377   bool IsZeroElt = X86::isZeroNode(N1);
18378   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
18379 
18380   // If we are inserting a element, see if we can do this more efficiently with
18381   // a blend shuffle with a rematerializable vector than a costly integer
18382   // insertion.
18383   if ((IsZeroElt || IsAllOnesElt) && Subtarget.hasSSE41() &&
18384       16 <= EltVT.getSizeInBits()) {
18385     SmallVector<int, 8> BlendMask;
18386     for (unsigned i = 0; i != NumElts; ++i)
18387       BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18388     SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
18389                                   : getOnesVector(VT, DAG, dl);
18390     return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
18391   }
18392 
18393   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
18394   // into that, and then insert the subvector back into the result.
18395   if (VT.is256BitVector() || VT.is512BitVector()) {
18396     // With a 256-bit vector, we can insert into the zero element efficiently
18397     // using a blend if we have AVX or AVX2 and the right data type.
18398     if (VT.is256BitVector() && IdxVal == 0) {
18399       // TODO: It is worthwhile to cast integer to floating point and back
18400       // and incur a domain crossing penalty if that's what we'll end up
18401       // doing anyway after extracting to a 128-bit vector.
18402       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
18403           (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
18404         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18405         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
18406                            DAG.getTargetConstant(1, dl, MVT::i8));
18407       }
18408     }
18409 
18410     // Get the desired 128-bit vector chunk.
18411     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
18412 
18413     // Insert the element into the desired chunk.
18414     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
18415     assert(isPowerOf2_32(NumEltsIn128));
18416     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
18417     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
18418 
18419     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
18420                     DAG.getIntPtrConstant(IdxIn128, dl));
18421 
18422     // Insert the changed part back into the bigger vector
18423     return insert128BitVector(N0, V, IdxVal, DAG, dl);
18424   }
18425   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
18426 
18427   // This will be just movd/movq/movss/movsd.
18428   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
18429     if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
18430         EltVT == MVT::i64) {
18431       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18432       return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18433     }
18434 
18435     // We can't directly insert an i8 or i16 into a vector, so zero extend
18436     // it to i32 first.
18437     if (EltVT == MVT::i16 || EltVT == MVT::i8) {
18438       N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
18439       MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
18440       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
18441       N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18442       return DAG.getBitcast(VT, N1);
18443     }
18444   }
18445 
18446   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
18447   // argument. SSE41 required for pinsrb.
18448   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
18449     unsigned Opc;
18450     if (VT == MVT::v8i16) {
18451       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
18452       Opc = X86ISD::PINSRW;
18453     } else {
18454       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
18455       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
18456       Opc = X86ISD::PINSRB;
18457     }
18458 
18459     if (N1.getValueType() != MVT::i32)
18460       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
18461     if (N2.getValueType() != MVT::i32)
18462       N2 = DAG.getIntPtrConstant(IdxVal, dl);
18463     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
18464   }
18465 
18466   if (Subtarget.hasSSE41()) {
18467     if (EltVT == MVT::f32) {
18468       // Bits [7:6] of the constant are the source select. This will always be
18469       //   zero here. The DAG Combiner may combine an extract_elt index into
18470       //   these bits. For example (insert (extract, 3), 2) could be matched by
18471       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
18472       // Bits [5:4] of the constant are the destination select. This is the
18473       //   value of the incoming immediate.
18474       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
18475       //   combine either bitwise AND or insert of float 0.0 to set these bits.
18476 
18477       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
18478       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
18479         // If this is an insertion of 32-bits into the low 32-bits of
18480         // a vector, we prefer to generate a blend with immediate rather
18481         // than an insertps. Blends are simpler operations in hardware and so
18482         // will always have equal or better performance than insertps.
18483         // But if optimizing for size and there's a load folding opportunity,
18484         // generate insertps because blendps does not have a 32-bit memory
18485         // operand form.
18486         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18487         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
18488                            DAG.getTargetConstant(1, dl, MVT::i8));
18489       }
18490       // Create this as a scalar to vector..
18491       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18492       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
18493                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
18494     }
18495 
18496     // PINSR* works with constant index.
18497     if (EltVT == MVT::i32 || EltVT == MVT::i64)
18498       return Op;
18499   }
18500 
18501   return SDValue();
18502 }
18503 
LowerSCALAR_TO_VECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18504 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
18505                                      SelectionDAG &DAG) {
18506   SDLoc dl(Op);
18507   MVT OpVT = Op.getSimpleValueType();
18508 
18509   // It's always cheaper to replace a xor+movd with xorps and simplifies further
18510   // combines.
18511   if (X86::isZeroNode(Op.getOperand(0)))
18512     return getZeroVector(OpVT, Subtarget, DAG, dl);
18513 
18514   // If this is a 256-bit vector result, first insert into a 128-bit
18515   // vector and then insert into the 256-bit vector.
18516   if (!OpVT.is128BitVector()) {
18517     // Insert into a 128-bit vector.
18518     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
18519     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
18520                                  OpVT.getVectorNumElements() / SizeFactor);
18521 
18522     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
18523 
18524     // Insert the 128-bit vector.
18525     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
18526   }
18527   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
18528          "Expected an SSE type!");
18529 
18530   // Pass through a v4i32 SCALAR_TO_VECTOR as that's what we use in tblgen.
18531   if (OpVT == MVT::v4i32)
18532     return Op;
18533 
18534   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
18535   return DAG.getBitcast(
18536       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
18537 }
18538 
18539 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
18540 // simple superregister reference or explicit instructions to insert
18541 // the upper bits of a vector.
LowerINSERT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18542 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18543                                      SelectionDAG &DAG) {
18544   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
18545 
18546   return insert1BitVector(Op, DAG, Subtarget);
18547 }
18548 
LowerEXTRACT_SUBVECTOR(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)18549 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18550                                       SelectionDAG &DAG) {
18551   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
18552          "Only vXi1 extract_subvectors need custom lowering");
18553 
18554   SDLoc dl(Op);
18555   SDValue Vec = Op.getOperand(0);
18556   uint64_t IdxVal = Op.getConstantOperandVal(1);
18557 
18558   if (IdxVal == 0) // the operation is legal
18559     return Op;
18560 
18561   MVT VecVT = Vec.getSimpleValueType();
18562   unsigned NumElems = VecVT.getVectorNumElements();
18563 
18564   // Extend to natively supported kshift.
18565   MVT WideVecVT = VecVT;
18566   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
18567     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18568     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
18569                       DAG.getUNDEF(WideVecVT), Vec,
18570                       DAG.getIntPtrConstant(0, dl));
18571   }
18572 
18573   // Shift to the LSB.
18574   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
18575                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18576 
18577   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
18578                      DAG.getIntPtrConstant(0, dl));
18579 }
18580 
18581 // Returns the appropriate wrapper opcode for a global reference.
getGlobalWrapperKind(const GlobalValue * GV,const unsigned char OpFlags) const18582 unsigned X86TargetLowering::getGlobalWrapperKind(
18583     const GlobalValue *GV, const unsigned char OpFlags) const {
18584   // References to absolute symbols are never PC-relative.
18585   if (GV && GV->isAbsoluteSymbolRef())
18586     return X86ISD::Wrapper;
18587 
18588   CodeModel::Model M = getTargetMachine().getCodeModel();
18589   if (Subtarget.isPICStyleRIPRel() &&
18590       (M == CodeModel::Small || M == CodeModel::Kernel))
18591     return X86ISD::WrapperRIP;
18592 
18593   // GOTPCREL references must always use RIP.
18594   if (OpFlags == X86II::MO_GOTPCREL)
18595     return X86ISD::WrapperRIP;
18596 
18597   return X86ISD::Wrapper;
18598 }
18599 
18600 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
18601 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
18602 // one of the above mentioned nodes. It has to be wrapped because otherwise
18603 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
18604 // be used to form addressing mode. These wrapped nodes will be selected
18605 // into MOV32ri.
18606 SDValue
LowerConstantPool(SDValue Op,SelectionDAG & DAG) const18607 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
18608   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
18609 
18610   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18611   // global base reg.
18612   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18613 
18614   auto PtrVT = getPointerTy(DAG.getDataLayout());
18615   SDValue Result = DAG.getTargetConstantPool(
18616       CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
18617   SDLoc DL(CP);
18618   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
18619   // With PIC, the address is actually $g + Offset.
18620   if (OpFlag) {
18621     Result =
18622         DAG.getNode(ISD::ADD, DL, PtrVT,
18623                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18624   }
18625 
18626   return Result;
18627 }
18628 
LowerJumpTable(SDValue Op,SelectionDAG & DAG) const18629 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
18630   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
18631 
18632   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18633   // global base reg.
18634   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
18635 
18636   auto PtrVT = getPointerTy(DAG.getDataLayout());
18637   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
18638   SDLoc DL(JT);
18639   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
18640 
18641   // With PIC, the address is actually $g + Offset.
18642   if (OpFlag)
18643     Result =
18644         DAG.getNode(ISD::ADD, DL, PtrVT,
18645                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
18646 
18647   return Result;
18648 }
18649 
LowerExternalSymbol(SDValue Op,SelectionDAG & DAG) const18650 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
18651                                                SelectionDAG &DAG) const {
18652   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18653 }
18654 
18655 SDValue
LowerBlockAddress(SDValue Op,SelectionDAG & DAG) const18656 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
18657   // Create the TargetBlockAddressAddress node.
18658   unsigned char OpFlags =
18659     Subtarget.classifyBlockAddressReference();
18660   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
18661   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
18662   SDLoc dl(Op);
18663   auto PtrVT = getPointerTy(DAG.getDataLayout());
18664   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
18665   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
18666 
18667   // With PIC, the address is actually $g + Offset.
18668   if (isGlobalRelativeToPICBase(OpFlags)) {
18669     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18670                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18671   }
18672 
18673   return Result;
18674 }
18675 
18676 /// Creates target global address or external symbol nodes for calls or
18677 /// other uses.
LowerGlobalOrExternal(SDValue Op,SelectionDAG & DAG,bool ForCall) const18678 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
18679                                                  bool ForCall) const {
18680   // Unpack the global address or external symbol.
18681   const SDLoc &dl = SDLoc(Op);
18682   const GlobalValue *GV = nullptr;
18683   int64_t Offset = 0;
18684   const char *ExternalSym = nullptr;
18685   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
18686     GV = G->getGlobal();
18687     Offset = G->getOffset();
18688   } else {
18689     const auto *ES = cast<ExternalSymbolSDNode>(Op);
18690     ExternalSym = ES->getSymbol();
18691   }
18692 
18693   // Calculate some flags for address lowering.
18694   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
18695   unsigned char OpFlags;
18696   if (ForCall)
18697     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
18698   else
18699     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
18700   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
18701   bool NeedsLoad = isGlobalStubReference(OpFlags);
18702 
18703   CodeModel::Model M = DAG.getTarget().getCodeModel();
18704   auto PtrVT = getPointerTy(DAG.getDataLayout());
18705   SDValue Result;
18706 
18707   if (GV) {
18708     // Create a target global address if this is a global. If possible, fold the
18709     // offset into the global address reference. Otherwise, ADD it on later.
18710     int64_t GlobalOffset = 0;
18711     if (OpFlags == X86II::MO_NO_FLAG &&
18712         X86::isOffsetSuitableForCodeModel(Offset, M)) {
18713       std::swap(GlobalOffset, Offset);
18714     }
18715     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
18716   } else {
18717     // If this is not a global address, this must be an external symbol.
18718     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
18719   }
18720 
18721   // If this is a direct call, avoid the wrapper if we don't need to do any
18722   // loads or adds. This allows SDAG ISel to match direct calls.
18723   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
18724     return Result;
18725 
18726   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
18727 
18728   // With PIC, the address is actually $g + Offset.
18729   if (HasPICReg) {
18730     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
18731                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
18732   }
18733 
18734   // For globals that require a load from a stub to get the address, emit the
18735   // load.
18736   if (NeedsLoad)
18737     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
18738                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18739 
18740   // If there was a non-zero offset that we didn't fold, create an explicit
18741   // addition for it.
18742   if (Offset != 0)
18743     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
18744                          DAG.getConstant(Offset, dl, PtrVT));
18745 
18746   return Result;
18747 }
18748 
18749 SDValue
LowerGlobalAddress(SDValue Op,SelectionDAG & DAG) const18750 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
18751   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
18752 }
18753 
18754 static SDValue
GetTLSADDR(SelectionDAG & DAG,SDValue Chain,GlobalAddressSDNode * GA,SDValue * InFlag,const EVT PtrVT,unsigned ReturnReg,unsigned char OperandFlags,bool LocalDynamic=false)18755 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
18756            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
18757            unsigned char OperandFlags, bool LocalDynamic = false) {
18758   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18759   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18760   SDLoc dl(GA);
18761   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18762                                            GA->getValueType(0),
18763                                            GA->getOffset(),
18764                                            OperandFlags);
18765 
18766   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
18767                                            : X86ISD::TLSADDR;
18768 
18769   if (InFlag) {
18770     SDValue Ops[] = { Chain,  TGA, *InFlag };
18771     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
18772   } else {
18773     SDValue Ops[]  = { Chain, TGA };
18774     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
18775   }
18776 
18777   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
18778   MFI.setAdjustsStack(true);
18779   MFI.setHasCalls(true);
18780 
18781   SDValue Flag = Chain.getValue(1);
18782   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
18783 }
18784 
18785 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
18786 static SDValue
LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18787 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18788                                 const EVT PtrVT) {
18789   SDValue InFlag;
18790   SDLoc dl(GA);  // ? function entry point might be better
18791   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
18792                                    DAG.getNode(X86ISD::GlobalBaseReg,
18793                                                SDLoc(), PtrVT), InFlag);
18794   InFlag = Chain.getValue(1);
18795 
18796   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
18797 }
18798 
18799 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
18800 static SDValue
LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT)18801 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18802                                 const EVT PtrVT) {
18803   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
18804                     X86::RAX, X86II::MO_TLSGD);
18805 }
18806 
LowerToTLSLocalDynamicModel(GlobalAddressSDNode * GA,SelectionDAG & DAG,const EVT PtrVT,bool is64Bit)18807 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
18808                                            SelectionDAG &DAG,
18809                                            const EVT PtrVT,
18810                                            bool is64Bit) {
18811   SDLoc dl(GA);
18812 
18813   // Get the start address of the TLS block for this module.
18814   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
18815       .getInfo<X86MachineFunctionInfo>();
18816   MFI->incNumLocalDynamicTLSAccesses();
18817 
18818   SDValue Base;
18819   if (is64Bit) {
18820     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
18821                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
18822   } else {
18823     SDValue InFlag;
18824     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
18825         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
18826     InFlag = Chain.getValue(1);
18827     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
18828                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
18829   }
18830 
18831   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
18832   // of Base.
18833 
18834   // Build x@dtpoff.
18835   unsigned char OperandFlags = X86II::MO_DTPOFF;
18836   unsigned WrapperKind = X86ISD::Wrapper;
18837   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
18838                                            GA->getValueType(0),
18839                                            GA->getOffset(), OperandFlags);
18840   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
18841 
18842   // Add x@dtpoff with the base.
18843   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
18844 }
18845 
18846 // 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)18847 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
18848                                    const EVT PtrVT, TLSModel::Model model,
18849                                    bool is64Bit, bool isPIC) {
18850   SDLoc dl(GA);
18851 
18852   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
18853   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
18854                                                          is64Bit ? 257 : 256));
18855 
18856   SDValue ThreadPointer =
18857       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
18858                   MachinePointerInfo(Ptr));
18859 
18860   unsigned char OperandFlags = 0;
18861   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
18862   // initialexec.
18863   unsigned WrapperKind = X86ISD::Wrapper;
18864   if (model == TLSModel::LocalExec) {
18865     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
18866   } else if (model == TLSModel::InitialExec) {
18867     if (is64Bit) {
18868       OperandFlags = X86II::MO_GOTTPOFF;
18869       WrapperKind = X86ISD::WrapperRIP;
18870     } else {
18871       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
18872     }
18873   } else {
18874     llvm_unreachable("Unexpected model");
18875   }
18876 
18877   // emit "addl x@ntpoff,%eax" (local exec)
18878   // or "addl x@indntpoff,%eax" (initial exec)
18879   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
18880   SDValue TGA =
18881       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
18882                                  GA->getOffset(), OperandFlags);
18883   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
18884 
18885   if (model == TLSModel::InitialExec) {
18886     if (isPIC && !is64Bit) {
18887       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
18888                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
18889                            Offset);
18890     }
18891 
18892     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
18893                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
18894   }
18895 
18896   // The address of the thread local variable is the add of the thread
18897   // pointer with the offset of the variable.
18898   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
18899 }
18900 
18901 SDValue
LowerGlobalTLSAddress(SDValue Op,SelectionDAG & DAG) const18902 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
18903 
18904   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
18905 
18906   if (DAG.getTarget().useEmulatedTLS())
18907     return LowerToTLSEmulatedModel(GA, DAG);
18908 
18909   const GlobalValue *GV = GA->getGlobal();
18910   auto PtrVT = getPointerTy(DAG.getDataLayout());
18911   bool PositionIndependent = isPositionIndependent();
18912 
18913   if (Subtarget.isTargetELF()) {
18914     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
18915     switch (model) {
18916       case TLSModel::GeneralDynamic:
18917         if (Subtarget.is64Bit())
18918           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
18919         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
18920       case TLSModel::LocalDynamic:
18921         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
18922                                            Subtarget.is64Bit());
18923       case TLSModel::InitialExec:
18924       case TLSModel::LocalExec:
18925         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
18926                                    PositionIndependent);
18927     }
18928     llvm_unreachable("Unknown TLS model.");
18929   }
18930 
18931   if (Subtarget.isTargetDarwin()) {
18932     // Darwin only has one model of TLS.  Lower to that.
18933     unsigned char OpFlag = 0;
18934     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
18935                            X86ISD::WrapperRIP : X86ISD::Wrapper;
18936 
18937     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
18938     // global base reg.
18939     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
18940     if (PIC32)
18941       OpFlag = X86II::MO_TLVP_PIC_BASE;
18942     else
18943       OpFlag = X86II::MO_TLVP;
18944     SDLoc DL(Op);
18945     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
18946                                                 GA->getValueType(0),
18947                                                 GA->getOffset(), OpFlag);
18948     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
18949 
18950     // With PIC32, the address is actually $g + Offset.
18951     if (PIC32)
18952       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
18953                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
18954                            Offset);
18955 
18956     // Lowering the machine isd will make sure everything is in the right
18957     // location.
18958     SDValue Chain = DAG.getEntryNode();
18959     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
18960     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
18961     SDValue Args[] = { Chain, Offset };
18962     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
18963     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
18964                                DAG.getIntPtrConstant(0, DL, true),
18965                                Chain.getValue(1), DL);
18966 
18967     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
18968     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
18969     MFI.setAdjustsStack(true);
18970 
18971     // And our return value (tls address) is in the standard call return value
18972     // location.
18973     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
18974     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
18975   }
18976 
18977   if (Subtarget.isOSWindows()) {
18978     // Just use the implicit TLS architecture
18979     // Need to generate something similar to:
18980     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
18981     //                                  ; from TEB
18982     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
18983     //   mov     rcx, qword [rdx+rcx*8]
18984     //   mov     eax, .tls$:tlsvar
18985     //   [rax+rcx] contains the address
18986     // Windows 64bit: gs:0x58
18987     // Windows 32bit: fs:__tls_array
18988 
18989     SDLoc dl(GA);
18990     SDValue Chain = DAG.getEntryNode();
18991 
18992     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
18993     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
18994     // use its literal value of 0x2C.
18995     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
18996                                         ? Type::getInt8PtrTy(*DAG.getContext(),
18997                                                              256)
18998                                         : Type::getInt32PtrTy(*DAG.getContext(),
18999                                                               257));
19000 
19001     SDValue TlsArray = Subtarget.is64Bit()
19002                            ? DAG.getIntPtrConstant(0x58, dl)
19003                            : (Subtarget.isTargetWindowsGNU()
19004                                   ? DAG.getIntPtrConstant(0x2C, dl)
19005                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
19006 
19007     SDValue ThreadPointer =
19008         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
19009 
19010     SDValue res;
19011     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
19012       res = ThreadPointer;
19013     } else {
19014       // Load the _tls_index variable
19015       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
19016       if (Subtarget.is64Bit())
19017         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
19018                              MachinePointerInfo(), MVT::i32);
19019       else
19020         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
19021 
19022       auto &DL = DAG.getDataLayout();
19023       SDValue Scale =
19024           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
19025       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
19026 
19027       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
19028     }
19029 
19030     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
19031 
19032     // Get the offset of start of .tls section
19033     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19034                                              GA->getValueType(0),
19035                                              GA->getOffset(), X86II::MO_SECREL);
19036     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
19037 
19038     // The address of the thread local variable is the add of the thread
19039     // pointer with the offset of the variable.
19040     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
19041   }
19042 
19043   llvm_unreachable("TLS not implemented for this target.");
19044 }
19045 
19046 /// Lower SRA_PARTS and friends, which return two i32 values
19047 /// and take a 2 x i32 value to shift plus a shift amount.
19048 /// TODO: Can this be moved to general expansion code?
LowerShiftParts(SDValue Op,SelectionDAG & DAG)19049 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
19050   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
19051   MVT VT = Op.getSimpleValueType();
19052   unsigned VTBits = VT.getSizeInBits();
19053   SDLoc dl(Op);
19054   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
19055   SDValue ShOpLo = Op.getOperand(0);
19056   SDValue ShOpHi = Op.getOperand(1);
19057   SDValue ShAmt  = Op.getOperand(2);
19058   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
19059   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's optimized away
19060   // during isel.
19061   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
19062                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
19063   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
19064                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
19065                        : DAG.getConstant(0, dl, VT);
19066 
19067   SDValue Tmp2, Tmp3;
19068   if (Op.getOpcode() == ISD::SHL_PARTS) {
19069     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
19070     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
19071   } else {
19072     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
19073     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
19074   }
19075 
19076   // If the shift amount is larger or equal than the width of a part we can't
19077   // rely on the results of shld/shrd. Insert a test and select the appropriate
19078   // values for large shift amounts.
19079   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
19080                                 DAG.getConstant(VTBits, dl, MVT::i8));
19081   SDValue Cond = DAG.getSetCC(dl, MVT::i8, AndNode,
19082                              DAG.getConstant(0, dl, MVT::i8), ISD::SETNE);
19083 
19084   SDValue Hi, Lo;
19085   if (Op.getOpcode() == ISD::SHL_PARTS) {
19086     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
19087     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
19088   } else {
19089     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
19090     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
19091   }
19092 
19093   return DAG.getMergeValues({ Lo, Hi }, dl);
19094 }
19095 
LowerFunnelShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)19096 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
19097                                 SelectionDAG &DAG) {
19098   MVT VT = Op.getSimpleValueType();
19099   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
19100          "Unexpected funnel shift opcode!");
19101 
19102   SDLoc DL(Op);
19103   SDValue Op0 = Op.getOperand(0);
19104   SDValue Op1 = Op.getOperand(1);
19105   SDValue Amt = Op.getOperand(2);
19106 
19107   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
19108 
19109   if (VT.isVector()) {
19110     assert(Subtarget.hasVBMI2() && "Expected VBMI2");
19111 
19112     if (IsFSHR)
19113       std::swap(Op0, Op1);
19114 
19115     APInt APIntShiftAmt;
19116     if (X86::isConstantSplat(Amt, APIntShiftAmt)) {
19117       uint64_t ShiftAmt = APIntShiftAmt.urem(VT.getScalarSizeInBits());
19118       return DAG.getNode(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT, Op0,
19119                          Op1, DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
19120     }
19121 
19122     return DAG.getNode(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
19123                        Op0, Op1, Amt);
19124   }
19125   assert(
19126       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
19127       "Unexpected funnel shift type!");
19128 
19129   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
19130   bool OptForSize = DAG.shouldOptForSize();
19131   bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
19132 
19133   // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
19134   // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
19135   if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
19136       !isa<ConstantSDNode>(Amt)) {
19137     unsigned EltSizeInBits = VT.getScalarSizeInBits();
19138     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
19139     SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
19140     Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
19141     Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
19142     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
19143     SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
19144     Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
19145     if (IsFSHR) {
19146       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
19147     } else {
19148       Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
19149       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
19150     }
19151     return DAG.getZExtOrTrunc(Res, DL, VT);
19152   }
19153 
19154   if (VT == MVT::i8 || ExpandFunnel)
19155     return SDValue();
19156 
19157   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
19158   if (VT == MVT::i16) {
19159     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
19160                       DAG.getConstant(15, DL, Amt.getValueType()));
19161     unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
19162     return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
19163   }
19164 
19165   return Op;
19166 }
19167 
19168 // Try to use a packed vector operation to handle i64 on 32-bit targets when
19169 // AVX512DQ is enabled.
LowerI64IntToFP_AVX512DQ(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19170 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
19171                                         const X86Subtarget &Subtarget) {
19172   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
19173           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
19174           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
19175           Op.getOpcode() == ISD::UINT_TO_FP) &&
19176          "Unexpected opcode!");
19177   bool IsStrict = Op->isStrictFPOpcode();
19178   unsigned OpNo = IsStrict ? 1 : 0;
19179   SDValue Src = Op.getOperand(OpNo);
19180   MVT SrcVT = Src.getSimpleValueType();
19181   MVT VT = Op.getSimpleValueType();
19182 
19183    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
19184        (VT != MVT::f32 && VT != MVT::f64))
19185     return SDValue();
19186 
19187   // Pack the i64 into a vector, do the operation and extract.
19188 
19189   // Using 256-bit to ensure result is 128-bits for f32 case.
19190   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
19191   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
19192   MVT VecVT = MVT::getVectorVT(VT, NumElts);
19193 
19194   SDLoc dl(Op);
19195   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
19196   if (IsStrict) {
19197     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
19198                                  {Op.getOperand(0), InVec});
19199     SDValue Chain = CvtVec.getValue(1);
19200     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19201                                 DAG.getIntPtrConstant(0, dl));
19202     return DAG.getMergeValues({Value, Chain}, dl);
19203   }
19204 
19205   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
19206 
19207   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19208                      DAG.getIntPtrConstant(0, dl));
19209 }
19210 
useVectorCast(unsigned Opcode,MVT FromVT,MVT ToVT,const X86Subtarget & Subtarget)19211 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
19212                           const X86Subtarget &Subtarget) {
19213   switch (Opcode) {
19214     case ISD::SINT_TO_FP:
19215       // TODO: Handle wider types with AVX/AVX512.
19216       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
19217         return false;
19218       // CVTDQ2PS or (V)CVTDQ2PD
19219       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
19220 
19221     case ISD::UINT_TO_FP:
19222       // TODO: Handle wider types and i64 elements.
19223       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
19224         return false;
19225       // VCVTUDQ2PS or VCVTUDQ2PD
19226       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
19227 
19228     default:
19229       return false;
19230   }
19231 }
19232 
19233 /// Given a scalar cast operation that is extracted from a vector, try to
19234 /// vectorize the cast op followed by extraction. This will avoid an expensive
19235 /// round-trip between XMM and GPR.
vectorizeExtractedCast(SDValue Cast,SelectionDAG & DAG,const X86Subtarget & Subtarget)19236 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
19237                                       const X86Subtarget &Subtarget) {
19238   // TODO: This could be enhanced to handle smaller integer types by peeking
19239   // through an extend.
19240   SDValue Extract = Cast.getOperand(0);
19241   MVT DestVT = Cast.getSimpleValueType();
19242   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19243       !isa<ConstantSDNode>(Extract.getOperand(1)))
19244     return SDValue();
19245 
19246   // See if we have a 128-bit vector cast op for this type of cast.
19247   SDValue VecOp = Extract.getOperand(0);
19248   MVT FromVT = VecOp.getSimpleValueType();
19249   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
19250   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
19251   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
19252   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
19253     return SDValue();
19254 
19255   // If we are extracting from a non-zero element, first shuffle the source
19256   // vector to allow extracting from element zero.
19257   SDLoc DL(Cast);
19258   if (!isNullConstant(Extract.getOperand(1))) {
19259     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
19260     Mask[0] = Extract.getConstantOperandVal(1);
19261     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
19262   }
19263   // If the source vector is wider than 128-bits, extract the low part. Do not
19264   // create an unnecessarily wide vector cast op.
19265   if (FromVT != Vec128VT)
19266     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
19267 
19268   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
19269   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
19270   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
19271   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
19272                      DAG.getIntPtrConstant(0, DL));
19273 }
19274 
19275 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
19276 /// try to vectorize the cast ops. This will avoid an expensive round-trip
19277 /// between XMM and GPR.
lowerFPToIntToFP(SDValue CastToFP,SelectionDAG & DAG,const X86Subtarget & Subtarget)19278 static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
19279                                 const X86Subtarget &Subtarget) {
19280   // TODO: Allow FP_TO_UINT.
19281   SDValue CastToInt = CastToFP.getOperand(0);
19282   MVT VT = CastToFP.getSimpleValueType();
19283   if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
19284     return SDValue();
19285 
19286   MVT IntVT = CastToInt.getSimpleValueType();
19287   SDValue X = CastToInt.getOperand(0);
19288   MVT SrcVT = X.getSimpleValueType();
19289   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
19290     return SDValue();
19291 
19292   // See if we have 128-bit vector cast instructions for this type of cast.
19293   // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
19294   if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
19295       IntVT != MVT::i32)
19296     return SDValue();
19297 
19298   unsigned SrcSize = SrcVT.getSizeInBits();
19299   unsigned IntSize = IntVT.getSizeInBits();
19300   unsigned VTSize = VT.getSizeInBits();
19301   MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
19302   MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
19303   MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
19304 
19305   // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
19306   unsigned ToIntOpcode =
19307       SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
19308   unsigned ToFPOpcode =
19309       IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
19310 
19311   // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
19312   //
19313   // We are not defining the high elements (for example, zero them) because
19314   // that could nullify any performance advantage that we hoped to gain from
19315   // this vector op hack. We do not expect any adverse effects (like denorm
19316   // penalties) with cast ops.
19317   SDLoc DL(CastToFP);
19318   SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
19319   SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
19320   SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
19321   SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
19322   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
19323 }
19324 
lowerINT_TO_FP_vXi64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19325 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
19326                                     const X86Subtarget &Subtarget) {
19327   SDLoc DL(Op);
19328   bool IsStrict = Op->isStrictFPOpcode();
19329   MVT VT = Op->getSimpleValueType(0);
19330   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
19331 
19332   if (Subtarget.hasDQI()) {
19333     assert(!Subtarget.hasVLX() && "Unexpected features");
19334 
19335     assert((Src.getSimpleValueType() == MVT::v2i64 ||
19336             Src.getSimpleValueType() == MVT::v4i64) &&
19337            "Unsupported custom type");
19338 
19339     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
19340     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
19341            "Unexpected VT!");
19342     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
19343 
19344     // Need to concat with zero vector for strict fp to avoid spurious
19345     // exceptions.
19346     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
19347                            : DAG.getUNDEF(MVT::v8i64);
19348     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
19349                       DAG.getIntPtrConstant(0, DL));
19350     SDValue Res, Chain;
19351     if (IsStrict) {
19352       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
19353                         {Op->getOperand(0), Src});
19354       Chain = Res.getValue(1);
19355     } else {
19356       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
19357     }
19358 
19359     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19360                       DAG.getIntPtrConstant(0, DL));
19361 
19362     if (IsStrict)
19363       return DAG.getMergeValues({Res, Chain}, DL);
19364     return Res;
19365   }
19366 
19367   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
19368                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
19369   if (VT != MVT::v4f32 || IsSigned)
19370     return SDValue();
19371 
19372   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
19373   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
19374   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
19375                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
19376                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
19377   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
19378   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
19379   SmallVector<SDValue, 4> SignCvts(4);
19380   SmallVector<SDValue, 4> Chains(4);
19381   for (int i = 0; i != 4; ++i) {
19382     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
19383                               DAG.getIntPtrConstant(i, DL));
19384     if (IsStrict) {
19385       SignCvts[i] =
19386           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
19387                       {Op.getOperand(0), Elt});
19388       Chains[i] = SignCvts[i].getValue(1);
19389     } else {
19390       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
19391     }
19392   }
19393   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
19394 
19395   SDValue Slow, Chain;
19396   if (IsStrict) {
19397     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19398     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
19399                        {Chain, SignCvt, SignCvt});
19400     Chain = Slow.getValue(1);
19401   } else {
19402     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
19403   }
19404 
19405   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
19406   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
19407 
19408   if (IsStrict)
19409     return DAG.getMergeValues({Cvt, Chain}, DL);
19410 
19411   return Cvt;
19412 }
19413 
LowerSINT_TO_FP(SDValue Op,SelectionDAG & DAG) const19414 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
19415                                            SelectionDAG &DAG) const {
19416   bool IsStrict = Op->isStrictFPOpcode();
19417   unsigned OpNo = IsStrict ? 1 : 0;
19418   SDValue Src = Op.getOperand(OpNo);
19419   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
19420   MVT SrcVT = Src.getSimpleValueType();
19421   MVT VT = Op.getSimpleValueType();
19422   SDLoc dl(Op);
19423 
19424   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
19425     return Extract;
19426 
19427   if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
19428     return R;
19429 
19430   if (SrcVT.isVector()) {
19431     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
19432       // Note: Since v2f64 is a legal type. We don't need to zero extend the
19433       // source for strict FP.
19434       if (IsStrict)
19435         return DAG.getNode(
19436             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
19437             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19438                                 DAG.getUNDEF(SrcVT))});
19439       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
19440                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19441                                      DAG.getUNDEF(SrcVT)));
19442     }
19443     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
19444       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
19445 
19446     return SDValue();
19447   }
19448 
19449   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
19450          "Unknown SINT_TO_FP to lower!");
19451 
19452   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
19453 
19454   // These are really Legal; return the operand so the caller accepts it as
19455   // Legal.
19456   if (SrcVT == MVT::i32 && UseSSEReg)
19457     return Op;
19458   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
19459     return Op;
19460 
19461   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
19462     return V;
19463 
19464   // SSE doesn't have an i16 conversion so we need to promote.
19465   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
19466     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
19467     if (IsStrict)
19468       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
19469                          {Chain, Ext});
19470 
19471     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
19472   }
19473 
19474   if (VT == MVT::f128)
19475     return LowerF128Call(Op, DAG, RTLIB::getSINTTOFP(SrcVT, VT));
19476 
19477   SDValue ValueToStore = Src;
19478   if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
19479     // Bitcasting to f64 here allows us to do a single 64-bit store from
19480     // an SSE register, avoiding the store forwarding penalty that would come
19481     // with two 32-bit stores.
19482     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19483 
19484   unsigned Size = SrcVT.getStoreSize();
19485   Align Alignment(Size);
19486   MachineFunction &MF = DAG.getMachineFunction();
19487   auto PtrVT = getPointerTy(MF.getDataLayout());
19488   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
19489   MachinePointerInfo MPI =
19490       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
19491   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19492   Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
19493   std::pair<SDValue, SDValue> Tmp =
19494       BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
19495 
19496   if (IsStrict)
19497     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19498 
19499   return Tmp.first;
19500 }
19501 
BuildFILD(EVT DstVT,EVT SrcVT,const SDLoc & DL,SDValue Chain,SDValue Pointer,MachinePointerInfo PtrInfo,Align Alignment,SelectionDAG & DAG) const19502 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
19503     EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
19504     MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
19505   // Build the FILD
19506   SDVTList Tys;
19507   bool useSSE = isScalarFPTypeInSSEReg(DstVT);
19508   if (useSSE)
19509     Tys = DAG.getVTList(MVT::f80, MVT::Other);
19510   else
19511     Tys = DAG.getVTList(DstVT, MVT::Other);
19512 
19513   SDValue FILDOps[] = {Chain, Pointer};
19514   SDValue Result =
19515       DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
19516                               Alignment, MachineMemOperand::MOLoad);
19517   Chain = Result.getValue(1);
19518 
19519   if (useSSE) {
19520     MachineFunction &MF = DAG.getMachineFunction();
19521     unsigned SSFISize = DstVT.getStoreSize();
19522     int SSFI =
19523         MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
19524     auto PtrVT = getPointerTy(MF.getDataLayout());
19525     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19526     Tys = DAG.getVTList(MVT::Other);
19527     SDValue FSTOps[] = {Chain, Result, StackSlot};
19528     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
19529         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
19530         MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
19531 
19532     Chain =
19533         DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
19534     Result = DAG.getLoad(
19535         DstVT, DL, Chain, StackSlot,
19536         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
19537     Chain = Result.getValue(1);
19538   }
19539 
19540   return { Result, Chain };
19541 }
19542 
19543 /// Horizontal vector math instructions may be slower than normal math with
19544 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
19545 /// implementation, and likely shuffle complexity of the alternate sequence.
shouldUseHorizontalOp(bool IsSingleSource,SelectionDAG & DAG,const X86Subtarget & Subtarget)19546 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
19547                                   const X86Subtarget &Subtarget) {
19548   bool IsOptimizingSize = DAG.shouldOptForSize();
19549   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
19550   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
19551 }
19552 
19553 /// 64-bit unsigned integer to double expansion.
LowerUINT_TO_FP_i64(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19554 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
19555                                    const X86Subtarget &Subtarget) {
19556   // This algorithm is not obvious. Here it is what we're trying to output:
19557   /*
19558      movq       %rax,  %xmm0
19559      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
19560      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
19561      #ifdef __SSE3__
19562        haddpd   %xmm0, %xmm0
19563      #else
19564        pshufd   $0x4e, %xmm0, %xmm1
19565        addpd    %xmm1, %xmm0
19566      #endif
19567   */
19568 
19569   bool IsStrict = Op->isStrictFPOpcode();
19570   unsigned OpNo = IsStrict ? 1 : 0;
19571   SDLoc dl(Op);
19572   LLVMContext *Context = DAG.getContext();
19573 
19574   // Build some magic constants.
19575   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
19576   Constant *C0 = ConstantDataVector::get(*Context, CV0);
19577   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19578   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
19579 
19580   SmallVector<Constant*,2> CV1;
19581   CV1.push_back(
19582     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
19583                                       APInt(64, 0x4330000000000000ULL))));
19584   CV1.push_back(
19585     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
19586                                       APInt(64, 0x4530000000000000ULL))));
19587   Constant *C1 = ConstantVector::get(CV1);
19588   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
19589 
19590   // Load the 64-bit value into an XMM register.
19591   SDValue XR1 =
19592       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(OpNo));
19593   SDValue CLod0 =
19594       DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
19595                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
19596                   /* Alignment = */ 16);
19597   SDValue Unpck1 =
19598       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
19599 
19600   SDValue CLod1 =
19601       DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
19602                   MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
19603                   /* Alignment = */ 16);
19604   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
19605   SDValue Sub;
19606   SDValue Chain;
19607   // TODO: Are there any fast-math-flags to propagate here?
19608   if (IsStrict) {
19609     Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
19610                       {Op.getOperand(0), XR2F, CLod1});
19611     Chain = Sub.getValue(1);
19612   } else
19613     Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
19614   SDValue Result;
19615 
19616   if (!IsStrict && Subtarget.hasSSE3() &&
19617       shouldUseHorizontalOp(true, DAG, Subtarget)) {
19618     // FIXME: Do we need a STRICT version of FHADD?
19619     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
19620   } else {
19621     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
19622     if (IsStrict) {
19623       Result = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v2f64, MVT::Other},
19624                            {Chain, Shuffle, Sub});
19625       Chain = Result.getValue(1);
19626     } else
19627       Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
19628   }
19629   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
19630                        DAG.getIntPtrConstant(0, dl));
19631   if (IsStrict)
19632     return DAG.getMergeValues({Result, Chain}, dl);
19633 
19634   return Result;
19635 }
19636 
19637 /// 32-bit unsigned integer to float expansion.
LowerUINT_TO_FP_i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19638 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
19639                                    const X86Subtarget &Subtarget) {
19640   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19641   SDLoc dl(Op);
19642   // FP constant to bias correct the final result.
19643   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
19644                                    MVT::f64);
19645 
19646   // Load the 32-bit value into an XMM register.
19647   SDValue Load =
19648       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
19649 
19650   // Zero out the upper parts of the register.
19651   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
19652 
19653   // Or the load with the bias.
19654   SDValue Or = DAG.getNode(
19655       ISD::OR, dl, MVT::v2i64,
19656       DAG.getBitcast(MVT::v2i64, Load),
19657       DAG.getBitcast(MVT::v2i64,
19658                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
19659   Or =
19660       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
19661                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
19662 
19663   if (Op.getNode()->isStrictFPOpcode()) {
19664     // Subtract the bias.
19665     // TODO: Are there any fast-math-flags to propagate here?
19666     SDValue Chain = Op.getOperand(0);
19667     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
19668                               {Chain, Or, Bias});
19669 
19670     if (Op.getValueType() == Sub.getValueType())
19671       return Sub;
19672 
19673     // Handle final rounding.
19674     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
19675         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
19676 
19677     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
19678   }
19679 
19680   // Subtract the bias.
19681   // TODO: Are there any fast-math-flags to propagate here?
19682   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
19683 
19684   // Handle final rounding.
19685   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
19686 }
19687 
lowerUINT_TO_FP_v2i32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)19688 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
19689                                      const X86Subtarget &Subtarget,
19690                                      const SDLoc &DL) {
19691   if (Op.getSimpleValueType() != MVT::v2f64)
19692     return SDValue();
19693 
19694   bool IsStrict = Op->isStrictFPOpcode();
19695 
19696   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
19697   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
19698 
19699   if (Subtarget.hasAVX512()) {
19700     if (!Subtarget.hasVLX()) {
19701       // Let generic type legalization widen this.
19702       if (!IsStrict)
19703         return SDValue();
19704       // Otherwise pad the integer input with 0s and widen the operation.
19705       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19706                        DAG.getConstant(0, DL, MVT::v2i32));
19707       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
19708                                 {Op.getOperand(0), N0});
19709       SDValue Chain = Res.getValue(1);
19710       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
19711                         DAG.getIntPtrConstant(0, DL));
19712       return DAG.getMergeValues({Res, Chain}, DL);
19713     }
19714 
19715     // Legalize to v4i32 type.
19716     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
19717                      DAG.getUNDEF(MVT::v2i32));
19718     if (IsStrict)
19719       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
19720                          {Op.getOperand(0), N0});
19721     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
19722   }
19723 
19724   // Zero extend to 2i64, OR with the floating point representation of 2^52.
19725   // This gives us the floating point equivalent of 2^52 + the i32 integer
19726   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
19727   // point leaving just our i32 integers in double format.
19728   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
19729   SDValue VBias =
19730       DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), DL, MVT::v2f64);
19731   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
19732                            DAG.getBitcast(MVT::v2i64, VBias));
19733   Or = DAG.getBitcast(MVT::v2f64, Or);
19734 
19735   if (IsStrict)
19736     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
19737                        {Op.getOperand(0), Or, VBias});
19738   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
19739 }
19740 
lowerUINT_TO_FP_vXi32(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19741 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
19742                                      const X86Subtarget &Subtarget) {
19743   SDLoc DL(Op);
19744   bool IsStrict = Op->isStrictFPOpcode();
19745   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
19746   MVT VecIntVT = V.getSimpleValueType();
19747   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
19748          "Unsupported custom type");
19749 
19750   if (Subtarget.hasAVX512()) {
19751     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
19752     assert(!Subtarget.hasVLX() && "Unexpected features");
19753     MVT VT = Op->getSimpleValueType(0);
19754 
19755     // v8i32->v8f64 is legal with AVX512 so just return it.
19756     if (VT == MVT::v8f64)
19757       return Op;
19758 
19759     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
19760            "Unexpected VT!");
19761     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
19762     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
19763     // Need to concat with zero vector for strict fp to avoid spurious
19764     // exceptions.
19765     SDValue Tmp =
19766         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
19767     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
19768                     DAG.getIntPtrConstant(0, DL));
19769     SDValue Res, Chain;
19770     if (IsStrict) {
19771       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
19772                         {Op->getOperand(0), V});
19773       Chain = Res.getValue(1);
19774     } else {
19775       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
19776     }
19777 
19778     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19779                       DAG.getIntPtrConstant(0, DL));
19780 
19781     if (IsStrict)
19782       return DAG.getMergeValues({Res, Chain}, DL);
19783     return Res;
19784   }
19785 
19786   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
19787       Op->getSimpleValueType(0) == MVT::v4f64) {
19788     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
19789     Constant *Bias = ConstantFP::get(
19790         *DAG.getContext(),
19791         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
19792     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
19793     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
19794     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
19795     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
19796     SDValue VBias = DAG.getMemIntrinsicNode(
19797         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
19798         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
19799         MachineMemOperand::MOLoad);
19800 
19801     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
19802                              DAG.getBitcast(MVT::v4i64, VBias));
19803     Or = DAG.getBitcast(MVT::v4f64, Or);
19804 
19805     if (IsStrict)
19806       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
19807                          {Op.getOperand(0), Or, VBias});
19808     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
19809   }
19810 
19811   // The algorithm is the following:
19812   // #ifdef __SSE4_1__
19813   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
19814   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
19815   //                                 (uint4) 0x53000000, 0xaa);
19816   // #else
19817   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
19818   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
19819   // #endif
19820   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
19821   //     return (float4) lo + fhi;
19822 
19823   bool Is128 = VecIntVT == MVT::v4i32;
19824   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
19825   // If we convert to something else than the supported type, e.g., to v4f64,
19826   // abort early.
19827   if (VecFloatVT != Op->getSimpleValueType(0))
19828     return SDValue();
19829 
19830   // In the #idef/#else code, we have in common:
19831   // - The vector of constants:
19832   // -- 0x4b000000
19833   // -- 0x53000000
19834   // - A shift:
19835   // -- v >> 16
19836 
19837   // Create the splat vector for 0x4b000000.
19838   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
19839   // Create the splat vector for 0x53000000.
19840   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
19841 
19842   // Create the right shift.
19843   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
19844   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
19845 
19846   SDValue Low, High;
19847   if (Subtarget.hasSSE41()) {
19848     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
19849     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
19850     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
19851     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
19852     // Low will be bitcasted right away, so do not bother bitcasting back to its
19853     // original type.
19854     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
19855                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
19856     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
19857     //                                 (uint4) 0x53000000, 0xaa);
19858     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
19859     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
19860     // High will be bitcasted right away, so do not bother bitcasting back to
19861     // its original type.
19862     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
19863                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
19864   } else {
19865     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
19866     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
19867     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
19868     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
19869 
19870     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
19871     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
19872   }
19873 
19874   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
19875   SDValue VecCstFSub = DAG.getConstantFP(
19876       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
19877 
19878   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
19879   // NOTE: By using fsub of a positive constant instead of fadd of a negative
19880   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
19881   // enabled. See PR24512.
19882   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
19883   // TODO: Are there any fast-math-flags to propagate here?
19884   //     (float4) lo;
19885   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
19886   //     return (float4) lo + fhi;
19887   if (IsStrict) {
19888     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
19889                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
19890     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
19891                        {FHigh.getValue(1), LowBitcast, FHigh});
19892   }
19893 
19894   SDValue FHigh =
19895       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
19896   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
19897 }
19898 
lowerUINT_TO_FP_vec(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)19899 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
19900                                    const X86Subtarget &Subtarget) {
19901   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
19902   SDValue N0 = Op.getOperand(OpNo);
19903   MVT SrcVT = N0.getSimpleValueType();
19904   SDLoc dl(Op);
19905 
19906   switch (SrcVT.SimpleTy) {
19907   default:
19908     llvm_unreachable("Custom UINT_TO_FP is not supported!");
19909   case MVT::v2i32:
19910     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
19911   case MVT::v4i32:
19912   case MVT::v8i32:
19913     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
19914   case MVT::v2i64:
19915   case MVT::v4i64:
19916     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
19917   }
19918 }
19919 
LowerUINT_TO_FP(SDValue Op,SelectionDAG & DAG) const19920 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
19921                                            SelectionDAG &DAG) const {
19922   bool IsStrict = Op->isStrictFPOpcode();
19923   unsigned OpNo = IsStrict ? 1 : 0;
19924   SDValue Src = Op.getOperand(OpNo);
19925   SDLoc dl(Op);
19926   auto PtrVT = getPointerTy(DAG.getDataLayout());
19927   MVT SrcVT = Src.getSimpleValueType();
19928   MVT DstVT = Op->getSimpleValueType(0);
19929   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
19930 
19931   if (DstVT == MVT::f128)
19932     return LowerF128Call(Op, DAG, RTLIB::getUINTTOFP(SrcVT, DstVT));
19933 
19934   if (DstVT.isVector())
19935     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
19936 
19937   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
19938     return Extract;
19939 
19940   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
19941       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
19942     // Conversions from unsigned i32 to f32/f64 are legal,
19943     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
19944     return Op;
19945   }
19946 
19947   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
19948   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
19949     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
19950     if (IsStrict)
19951       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
19952                          {Chain, Src});
19953     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
19954   }
19955 
19956   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
19957     return V;
19958 
19959   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
19960     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
19961   if (SrcVT == MVT::i32 && X86ScalarSSEf64 && DstVT != MVT::f80)
19962     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
19963   if (Subtarget.is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
19964     return SDValue();
19965 
19966   // Make a 64-bit buffer, and use it to build an FILD.
19967   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
19968   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
19969   MachinePointerInfo MPI =
19970     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
19971   if (SrcVT == MVT::i32) {
19972     SDValue OffsetSlot = DAG.getMemBasePlusOffset(StackSlot, 4, dl);
19973     SDValue Store1 =
19974         DAG.getStore(Chain, dl, Src, StackSlot, MPI, 8 /*Align*/);
19975     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
19976                                   OffsetSlot, MPI.getWithOffset(4), 4);
19977     std::pair<SDValue, SDValue> Tmp =
19978         BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, Align(8), DAG);
19979     if (IsStrict)
19980       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19981 
19982     return Tmp.first;
19983   }
19984 
19985   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
19986   SDValue ValueToStore = Src;
19987   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
19988     // Bitcasting to f64 here allows us to do a single 64-bit store from
19989     // an SSE register, avoiding the store forwarding penalty that would come
19990     // with two 32-bit stores.
19991     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19992   }
19993   SDValue Store =
19994       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Align(8));
19995   // For i64 source, we need to add the appropriate power of 2 if the input
19996   // was negative.  This is the same as the optimization in
19997   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
19998   // we must be careful to do the computation in x87 extended precision, not
19999   // in SSE. (The generic code can't know it's OK to do this, or how to.)
20000   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20001   SDValue Ops[] = { Store, StackSlot };
20002   SDValue Fild =
20003       DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
20004                               Align(8), MachineMemOperand::MOLoad);
20005   Chain = Fild.getValue(1);
20006 
20007 
20008   // Check whether the sign bit is set.
20009   SDValue SignSet = DAG.getSetCC(
20010       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
20011       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
20012 
20013   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
20014   APInt FF(64, 0x5F80000000000000ULL);
20015   SDValue FudgePtr = DAG.getConstantPool(
20016       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
20017   Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
20018 
20019   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
20020   SDValue Zero = DAG.getIntPtrConstant(0, dl);
20021   SDValue Four = DAG.getIntPtrConstant(4, dl);
20022   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
20023   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
20024 
20025   // Load the value out, extending it from f32 to f80.
20026   SDValue Fudge = DAG.getExtLoad(
20027       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
20028       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
20029       CPAlignment);
20030   Chain = Fudge.getValue(1);
20031   // Extend everything to 80 bits to force it to be done on x87.
20032   // TODO: Are there any fast-math-flags to propagate here?
20033   if (IsStrict) {
20034     SDValue Add = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::f80, MVT::Other},
20035                               {Chain, Fild, Fudge});
20036     // STRICT_FP_ROUND can't handle equal types.
20037     if (DstVT == MVT::f80)
20038       return Add;
20039     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
20040                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
20041   }
20042   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
20043   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
20044                      DAG.getIntPtrConstant(0, dl));
20045 }
20046 
20047 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
20048 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
20049 // just return an SDValue().
20050 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
20051 // to i16, i32 or i64, and we lower it to a legal sequence and return the
20052 // result.
20053 SDValue
FP_TO_INTHelper(SDValue Op,SelectionDAG & DAG,bool IsSigned,SDValue & Chain) const20054 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
20055                                    bool IsSigned, SDValue &Chain) const {
20056   bool IsStrict = Op->isStrictFPOpcode();
20057   SDLoc DL(Op);
20058 
20059   EVT DstTy = Op.getValueType();
20060   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
20061   EVT TheVT = Value.getValueType();
20062   auto PtrVT = getPointerTy(DAG.getDataLayout());
20063 
20064   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
20065     // f16 must be promoted before using the lowering in this routine.
20066     // fp128 does not use this lowering.
20067     return SDValue();
20068   }
20069 
20070   // If using FIST to compute an unsigned i64, we'll need some fixup
20071   // to handle values above the maximum signed i64.  A FIST is always
20072   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
20073   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
20074 
20075   // FIXME: This does not generate an invalid exception if the input does not
20076   // fit in i32. PR44019
20077   if (!IsSigned && DstTy != MVT::i64) {
20078     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
20079     // The low 32 bits of the fist result will have the correct uint32 result.
20080     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
20081     DstTy = MVT::i64;
20082   }
20083 
20084   assert(DstTy.getSimpleVT() <= MVT::i64 &&
20085          DstTy.getSimpleVT() >= MVT::i16 &&
20086          "Unknown FP_TO_INT to lower!");
20087 
20088   // We lower FP->int64 into FISTP64 followed by a load from a temporary
20089   // stack slot.
20090   MachineFunction &MF = DAG.getMachineFunction();
20091   unsigned MemSize = DstTy.getStoreSize();
20092   int SSFI =
20093       MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
20094   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20095 
20096   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20097 
20098   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
20099 
20100   if (UnsignedFixup) {
20101     //
20102     // Conversion to unsigned i64 is implemented with a select,
20103     // depending on whether the source value fits in the range
20104     // of a signed i64.  Let Thresh be the FP equivalent of
20105     // 0x8000000000000000ULL.
20106     //
20107     //  Adjust = (Value < Thresh) ? 0 : 0x80000000;
20108     //  FltOfs = (Value < Thresh) ? 0 : 0x80000000;
20109     //  FistSrc = (Value - FltOfs);
20110     //  Fist-to-mem64 FistSrc
20111     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
20112     //  to XOR'ing the high 32 bits with Adjust.
20113     //
20114     // Being a power of 2, Thresh is exactly representable in all FP formats.
20115     // For X87 we'd like to use the smallest FP type for this constant, but
20116     // for DAG type consistency we have to match the FP operand type.
20117 
20118     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
20119     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
20120     bool LosesInfo = false;
20121     if (TheVT == MVT::f64)
20122       // The rounding mode is irrelevant as the conversion should be exact.
20123       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
20124                               &LosesInfo);
20125     else if (TheVT == MVT::f80)
20126       Status = Thresh.convert(APFloat::x87DoubleExtended(),
20127                               APFloat::rmNearestTiesToEven, &LosesInfo);
20128 
20129     assert(Status == APFloat::opOK && !LosesInfo &&
20130            "FP conversion should have been exact");
20131 
20132     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
20133 
20134     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
20135                                    *DAG.getContext(), TheVT);
20136     SDValue Cmp;
20137     if (IsStrict) {
20138       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETLT,
20139                          Chain, /*IsSignaling*/ true);
20140       Chain = Cmp.getValue(1);
20141     } else {
20142       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETLT);
20143     }
20144 
20145     Adjust = DAG.getSelect(DL, MVT::i64, Cmp,
20146                            DAG.getConstant(0, DL, MVT::i64),
20147                            DAG.getConstant(APInt::getSignMask(64),
20148                                            DL, MVT::i64));
20149     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp,
20150                                    DAG.getConstantFP(0.0, DL, TheVT),
20151                                    ThreshVal);
20152 
20153     if (IsStrict) {
20154       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
20155                           { Chain, Value, FltOfs });
20156       Chain = Value.getValue(1);
20157     } else
20158       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
20159   }
20160 
20161   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
20162 
20163   // FIXME This causes a redundant load/store if the SSE-class value is already
20164   // in memory, such as if it is on the callstack.
20165   if (isScalarFPTypeInSSEReg(TheVT)) {
20166     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
20167     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
20168     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20169     SDValue Ops[] = { Chain, StackSlot };
20170 
20171     unsigned FLDSize = TheVT.getStoreSize();
20172     assert(FLDSize <= MemSize && "Stack slot not big enough");
20173     MachineMemOperand *MMO = MF.getMachineMemOperand(
20174         MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
20175     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
20176     Chain = Value.getValue(1);
20177   }
20178 
20179   // Build the FP_TO_INT*_IN_MEM
20180   MachineMemOperand *MMO = MF.getMachineMemOperand(
20181       MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
20182   SDValue Ops[] = { Chain, Value, StackSlot };
20183   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
20184                                          DAG.getVTList(MVT::Other),
20185                                          Ops, DstTy, MMO);
20186 
20187   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
20188   Chain = Res.getValue(1);
20189 
20190   // If we need an unsigned fixup, XOR the result with adjust.
20191   if (UnsignedFixup)
20192     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
20193 
20194   return Res;
20195 }
20196 
LowerAVXExtend(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)20197 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
20198                               const X86Subtarget &Subtarget) {
20199   MVT VT = Op.getSimpleValueType();
20200   SDValue In = Op.getOperand(0);
20201   MVT InVT = In.getSimpleValueType();
20202   SDLoc dl(Op);
20203   unsigned Opc = Op.getOpcode();
20204 
20205   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
20206   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
20207          "Unexpected extension opcode");
20208   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
20209          "Expected same number of elements");
20210   assert((VT.getVectorElementType() == MVT::i16 ||
20211           VT.getVectorElementType() == MVT::i32 ||
20212           VT.getVectorElementType() == MVT::i64) &&
20213          "Unexpected element type");
20214   assert((InVT.getVectorElementType() == MVT::i8 ||
20215           InVT.getVectorElementType() == MVT::i16 ||
20216           InVT.getVectorElementType() == MVT::i32) &&
20217          "Unexpected element type");
20218 
20219   unsigned ExtendInVecOpc = getOpcode_EXTEND_VECTOR_INREG(Opc);
20220 
20221   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
20222     assert(InVT == MVT::v32i8 && "Unexpected VT!");
20223     return splitVectorIntUnary(Op, DAG);
20224   }
20225 
20226   if (Subtarget.hasInt256())
20227     return Op;
20228 
20229   // Optimize vectors in AVX mode:
20230   //
20231   //   v8i16 -> v8i32
20232   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
20233   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
20234   //   Concat upper and lower parts.
20235   //
20236   //   v4i32 -> v4i64
20237   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
20238   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
20239   //   Concat upper and lower parts.
20240   //
20241   MVT HalfVT = VT.getHalfNumVectorElementsVT();
20242   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
20243 
20244   // Short-circuit if we can determine that each 128-bit half is the same value.
20245   // Otherwise, this is difficult to match and optimize.
20246   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
20247     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
20248       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
20249 
20250   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
20251   SDValue Undef = DAG.getUNDEF(InVT);
20252   bool NeedZero = Opc == ISD::ZERO_EXTEND;
20253   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
20254   OpHi = DAG.getBitcast(HalfVT, OpHi);
20255 
20256   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
20257 }
20258 
20259 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
SplitAndExtendv16i1(unsigned ExtOpc,MVT VT,SDValue In,const SDLoc & dl,SelectionDAG & DAG)20260 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
20261                                    const SDLoc &dl, SelectionDAG &DAG) {
20262   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
20263   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20264                            DAG.getIntPtrConstant(0, dl));
20265   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20266                            DAG.getIntPtrConstant(8, dl));
20267   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
20268   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
20269   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
20270   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20271 }
20272 
LowerZERO_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20273 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
20274                                       const X86Subtarget &Subtarget,
20275                                       SelectionDAG &DAG) {
20276   MVT VT = Op->getSimpleValueType(0);
20277   SDValue In = Op->getOperand(0);
20278   MVT InVT = In.getSimpleValueType();
20279   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
20280   SDLoc DL(Op);
20281   unsigned NumElts = VT.getVectorNumElements();
20282 
20283   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
20284   // avoids a constant pool load.
20285   if (VT.getVectorElementType() != MVT::i8) {
20286     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
20287     return DAG.getNode(ISD::SRL, DL, VT, Extend,
20288                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
20289   }
20290 
20291   // Extend VT if BWI is not supported.
20292   MVT ExtVT = VT;
20293   if (!Subtarget.hasBWI()) {
20294     // If v16i32 is to be avoided, we'll need to split and concatenate.
20295     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20296       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
20297 
20298     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20299   }
20300 
20301   // Widen to 512-bits if VLX is not supported.
20302   MVT WideVT = ExtVT;
20303   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20304     NumElts *= 512 / ExtVT.getSizeInBits();
20305     InVT = MVT::getVectorVT(MVT::i1, NumElts);
20306     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
20307                      In, DAG.getIntPtrConstant(0, DL));
20308     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
20309                               NumElts);
20310   }
20311 
20312   SDValue One = DAG.getConstant(1, DL, WideVT);
20313   SDValue Zero = DAG.getConstant(0, DL, WideVT);
20314 
20315   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
20316 
20317   // Truncate if we had to extend above.
20318   if (VT != ExtVT) {
20319     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
20320     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
20321   }
20322 
20323   // Extract back to 128/256-bit if we widened.
20324   if (WideVT != VT)
20325     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
20326                               DAG.getIntPtrConstant(0, DL));
20327 
20328   return SelectedVal;
20329 }
20330 
LowerZERO_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)20331 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20332                                 SelectionDAG &DAG) {
20333   SDValue In = Op.getOperand(0);
20334   MVT SVT = In.getSimpleValueType();
20335 
20336   if (SVT.getVectorElementType() == MVT::i1)
20337     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
20338 
20339   assert(Subtarget.hasAVX() && "Expected AVX support");
20340   return LowerAVXExtend(Op, DAG, Subtarget);
20341 }
20342 
20343 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
20344 /// It makes use of the fact that vectors with enough leading sign/zero bits
20345 /// prevent the PACKSS/PACKUS from saturating the results.
20346 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
20347 /// within each 128-bit lane.
truncateVectorWithPACK(unsigned Opcode,EVT DstVT,SDValue In,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)20348 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
20349                                       const SDLoc &DL, SelectionDAG &DAG,
20350                                       const X86Subtarget &Subtarget) {
20351   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
20352          "Unexpected PACK opcode");
20353   assert(DstVT.isVector() && "VT not a vector?");
20354 
20355   // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
20356   if (!Subtarget.hasSSE2())
20357     return SDValue();
20358 
20359   EVT SrcVT = In.getValueType();
20360 
20361   // No truncation required, we might get here due to recursive calls.
20362   if (SrcVT == DstVT)
20363     return In;
20364 
20365   // We only support vector truncation to 64bits or greater from a
20366   // 128bits or greater source.
20367   unsigned DstSizeInBits = DstVT.getSizeInBits();
20368   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
20369   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
20370     return SDValue();
20371 
20372   unsigned NumElems = SrcVT.getVectorNumElements();
20373   if (!isPowerOf2_32(NumElems))
20374     return SDValue();
20375 
20376   LLVMContext &Ctx = *DAG.getContext();
20377   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
20378   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
20379 
20380   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
20381 
20382   // Pack to the largest type possible:
20383   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
20384   EVT InVT = MVT::i16, OutVT = MVT::i8;
20385   if (SrcVT.getScalarSizeInBits() > 16 &&
20386       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
20387     InVT = MVT::i32;
20388     OutVT = MVT::i16;
20389   }
20390 
20391   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
20392   if (SrcVT.is128BitVector()) {
20393     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
20394     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
20395     In = DAG.getBitcast(InVT, In);
20396     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, DAG.getUNDEF(InVT));
20397     Res = extractSubVector(Res, 0, DAG, DL, 64);
20398     return DAG.getBitcast(DstVT, Res);
20399   }
20400 
20401   // Split lower/upper subvectors.
20402   SDValue Lo, Hi;
20403   std::tie(Lo, Hi) = splitVector(In, DAG, DL);
20404 
20405   unsigned SubSizeInBits = SrcSizeInBits / 2;
20406   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
20407   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
20408 
20409   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
20410   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
20411     Lo = DAG.getBitcast(InVT, Lo);
20412     Hi = DAG.getBitcast(InVT, Hi);
20413     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20414     return DAG.getBitcast(DstVT, Res);
20415   }
20416 
20417   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
20418   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
20419   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
20420     Lo = DAG.getBitcast(InVT, Lo);
20421     Hi = DAG.getBitcast(InVT, Hi);
20422     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20423 
20424     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
20425     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
20426     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
20427     SmallVector<int, 64> Mask;
20428     int Scale = 64 / OutVT.getScalarSizeInBits();
20429     narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
20430     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
20431 
20432     if (DstVT.is256BitVector())
20433       return DAG.getBitcast(DstVT, Res);
20434 
20435     // If 512bit -> 128bit truncate another stage.
20436     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
20437     Res = DAG.getBitcast(PackedVT, Res);
20438     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20439   }
20440 
20441   // Recursively pack lower/upper subvectors, concat result and pack again.
20442   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
20443   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
20444   Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
20445   Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
20446 
20447   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
20448   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
20449   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20450 }
20451 
LowerTruncateVecI1(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)20452 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
20453                                   const X86Subtarget &Subtarget) {
20454 
20455   SDLoc DL(Op);
20456   MVT VT = Op.getSimpleValueType();
20457   SDValue In = Op.getOperand(0);
20458   MVT InVT = In.getSimpleValueType();
20459 
20460   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
20461 
20462   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
20463   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
20464   if (InVT.getScalarSizeInBits() <= 16) {
20465     if (Subtarget.hasBWI()) {
20466       // legal, will go to VPMOVB2M, VPMOVW2M
20467       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20468         // We need to shift to get the lsb into sign position.
20469         // Shift packed bytes not supported natively, bitcast to word
20470         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
20471         In = DAG.getNode(ISD::SHL, DL, ExtVT,
20472                          DAG.getBitcast(ExtVT, In),
20473                          DAG.getConstant(ShiftInx, DL, ExtVT));
20474         In = DAG.getBitcast(InVT, In);
20475       }
20476       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
20477                           In, ISD::SETGT);
20478     }
20479     // Use TESTD/Q, extended vector to packed dword/qword.
20480     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
20481            "Unexpected vector type.");
20482     unsigned NumElts = InVT.getVectorNumElements();
20483     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
20484     // We need to change to a wider element type that we have support for.
20485     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
20486     // For 16 element vectors we extend to v16i32 unless we are explicitly
20487     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
20488     // we need to split into two 8 element vectors which we can extend to v8i32,
20489     // truncate and concat the results. There's an additional complication if
20490     // the original type is v16i8. In that case we can't split the v16i8
20491     // directly, so we need to shuffle high elements to low and use
20492     // sign_extend_vector_inreg.
20493     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
20494       SDValue Lo, Hi;
20495       if (InVT == MVT::v16i8) {
20496         Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
20497         Hi = DAG.getVectorShuffle(
20498             InVT, DL, In, In,
20499             {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
20500         Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
20501       } else {
20502         assert(InVT == MVT::v16i16 && "Unexpected VT!");
20503         Lo = extract128BitVector(In, 0, DAG, DL);
20504         Hi = extract128BitVector(In, 8, DAG, DL);
20505       }
20506       // We're split now, just emit two truncates and a concat. The two
20507       // truncates will trigger legalization to come back to this function.
20508       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
20509       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
20510       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20511     }
20512     // We either have 8 elements or we're allowed to use 512-bit vectors.
20513     // If we have VLX, we want to use the narrowest vector that can get the
20514     // job done so we use vXi32.
20515     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
20516     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
20517     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
20518     InVT = ExtVT;
20519     ShiftInx = InVT.getScalarSizeInBits() - 1;
20520   }
20521 
20522   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20523     // We need to shift to get the lsb into sign position.
20524     In = DAG.getNode(ISD::SHL, DL, InVT, In,
20525                      DAG.getConstant(ShiftInx, DL, InVT));
20526   }
20527   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
20528   if (Subtarget.hasDQI())
20529     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
20530   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
20531 }
20532 
LowerTRUNCATE(SDValue Op,SelectionDAG & DAG) const20533 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
20534   SDLoc DL(Op);
20535   MVT VT = Op.getSimpleValueType();
20536   SDValue In = Op.getOperand(0);
20537   MVT InVT = In.getSimpleValueType();
20538   unsigned InNumEltBits = InVT.getScalarSizeInBits();
20539 
20540   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
20541          "Invalid TRUNCATE operation");
20542 
20543   // If we're called by the type legalizer, handle a few cases.
20544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20545   if (!TLI.isTypeLegal(InVT)) {
20546     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
20547         VT.is128BitVector()) {
20548       assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
20549              "Unexpected subtarget!");
20550       // The default behavior is to truncate one step, concatenate, and then
20551       // truncate the remainder. We'd rather produce two 64-bit results and
20552       // concatenate those.
20553       SDValue Lo, Hi;
20554       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
20555 
20556       EVT LoVT, HiVT;
20557       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
20558 
20559       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
20560       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
20561       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20562     }
20563 
20564     // Otherwise let default legalization handle it.
20565     return SDValue();
20566   }
20567 
20568   if (VT.getVectorElementType() == MVT::i1)
20569     return LowerTruncateVecI1(Op, DAG, Subtarget);
20570 
20571   // vpmovqb/w/d, vpmovdb/w, vpmovwb
20572   if (Subtarget.hasAVX512()) {
20573     if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
20574       assert(VT == MVT::v32i8 && "Unexpected VT!");
20575       return splitVectorIntUnary(Op, DAG);
20576     }
20577 
20578     // word to byte only under BWI. Otherwise we have to promoted to v16i32
20579     // and then truncate that. But we should only do that if we haven't been
20580     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
20581     // handled by isel patterns.
20582     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
20583         Subtarget.canExtendTo512DQ())
20584       return Op;
20585   }
20586 
20587   unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
20588   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
20589 
20590   // Truncate with PACKUS if we are truncating a vector with leading zero bits
20591   // that extend all the way to the packed/truncated value.
20592   // Pre-SSE41 we can only use PACKUSWB.
20593   KnownBits Known = DAG.computeKnownBits(In);
20594   if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
20595     if (SDValue V =
20596             truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
20597       return V;
20598 
20599   // Truncate with PACKSS if we are truncating a vector with sign-bits that
20600   // extend all the way to the packed/truncated value.
20601   if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
20602     if (SDValue V =
20603             truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
20604       return V;
20605 
20606   // Handle truncation of V256 to V128 using shuffles.
20607   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
20608 
20609   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
20610     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
20611     if (Subtarget.hasInt256()) {
20612       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
20613       In = DAG.getBitcast(MVT::v8i32, In);
20614       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
20615       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
20616                          DAG.getIntPtrConstant(0, DL));
20617     }
20618 
20619     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20620                                DAG.getIntPtrConstant(0, DL));
20621     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20622                                DAG.getIntPtrConstant(2, DL));
20623     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
20624     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
20625     static const int ShufMask[] = {0, 2, 4, 6};
20626     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
20627   }
20628 
20629   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
20630     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
20631     if (Subtarget.hasInt256()) {
20632       In = DAG.getBitcast(MVT::v32i8, In);
20633 
20634       // The PSHUFB mask:
20635       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
20636                                       -1, -1, -1, -1, -1, -1, -1, -1,
20637                                       16, 17, 20, 21, 24, 25, 28, 29,
20638                                       -1, -1, -1, -1, -1, -1, -1, -1 };
20639       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
20640       In = DAG.getBitcast(MVT::v4i64, In);
20641 
20642       static const int ShufMask2[] = {0,  2,  -1,  -1};
20643       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, In, ShufMask2);
20644       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
20645                        DAG.getIntPtrConstant(0, DL));
20646       return DAG.getBitcast(VT, In);
20647     }
20648 
20649     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
20650                                DAG.getIntPtrConstant(0, DL));
20651 
20652     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
20653                                DAG.getIntPtrConstant(4, DL));
20654 
20655     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
20656     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
20657 
20658     // The PSHUFB mask:
20659     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
20660                                    -1, -1, -1, -1, -1, -1, -1, -1};
20661 
20662     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
20663     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
20664 
20665     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
20666     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
20667 
20668     // The MOVLHPS Mask:
20669     static const int ShufMask2[] = {0, 1, 4, 5};
20670     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
20671     return DAG.getBitcast(MVT::v8i16, res);
20672   }
20673 
20674   if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
20675     // Use an AND to zero uppper bits for PACKUS.
20676     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
20677 
20678     SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
20679                                DAG.getIntPtrConstant(0, DL));
20680     SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
20681                                DAG.getIntPtrConstant(8, DL));
20682     return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
20683   }
20684 
20685   llvm_unreachable("All 256->128 cases should have been handled above!");
20686 }
20687 
LowerFP_TO_INT(SDValue Op,SelectionDAG & DAG) const20688 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
20689   bool IsStrict = Op->isStrictFPOpcode();
20690   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
20691                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
20692   MVT VT = Op->getSimpleValueType(0);
20693   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
20694   MVT SrcVT = Src.getSimpleValueType();
20695   SDLoc dl(Op);
20696 
20697   if (VT.isVector()) {
20698     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
20699       MVT ResVT = MVT::v4i32;
20700       MVT TruncVT = MVT::v4i1;
20701       unsigned Opc;
20702       if (IsStrict)
20703         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
20704       else
20705         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
20706 
20707       if (!IsSigned && !Subtarget.hasVLX()) {
20708         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
20709         // Widen to 512-bits.
20710         ResVT = MVT::v8i32;
20711         TruncVT = MVT::v8i1;
20712         Opc = Op.getOpcode();
20713         // Need to concat with zero vector for strict fp to avoid spurious
20714         // exceptions.
20715         // TODO: Should we just do this for non-strict as well?
20716         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
20717                                : DAG.getUNDEF(MVT::v8f64);
20718         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
20719                           DAG.getIntPtrConstant(0, dl));
20720       }
20721       SDValue Res, Chain;
20722       if (IsStrict) {
20723         Res =
20724             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Op->getOperand(0), Src});
20725         Chain = Res.getValue(1);
20726       } else {
20727         Res = DAG.getNode(Opc, dl, ResVT, Src);
20728       }
20729 
20730       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
20731       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
20732                         DAG.getIntPtrConstant(0, dl));
20733       if (IsStrict)
20734         return DAG.getMergeValues({Res, Chain}, dl);
20735       return Res;
20736     }
20737 
20738     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
20739     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
20740       assert(!IsSigned && "Expected unsigned conversion!");
20741       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
20742       return Op;
20743     }
20744 
20745     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
20746     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
20747         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32)) {
20748       assert(!IsSigned && "Expected unsigned conversion!");
20749       assert(Subtarget.useAVX512Regs() && !Subtarget.hasVLX() &&
20750              "Unexpected features!");
20751       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
20752       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
20753       // Need to concat with zero vector for strict fp to avoid spurious
20754       // exceptions.
20755       // TODO: Should we just do this for non-strict as well?
20756       SDValue Tmp =
20757           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
20758       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
20759                         DAG.getIntPtrConstant(0, dl));
20760 
20761       SDValue Res, Chain;
20762       if (IsStrict) {
20763         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
20764                           {Op->getOperand(0), Src});
20765         Chain = Res.getValue(1);
20766       } else {
20767         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
20768       }
20769 
20770       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20771                         DAG.getIntPtrConstant(0, dl));
20772 
20773       if (IsStrict)
20774         return DAG.getMergeValues({Res, Chain}, dl);
20775       return Res;
20776     }
20777 
20778     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
20779     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
20780         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32)) {
20781       assert(Subtarget.useAVX512Regs() && Subtarget.hasDQI() &&
20782              !Subtarget.hasVLX() && "Unexpected features!");
20783       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
20784       // Need to concat with zero vector for strict fp to avoid spurious
20785       // exceptions.
20786       // TODO: Should we just do this for non-strict as well?
20787       SDValue Tmp =
20788           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
20789       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
20790                         DAG.getIntPtrConstant(0, dl));
20791 
20792       SDValue Res, Chain;
20793       if (IsStrict) {
20794         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
20795                           {Op->getOperand(0), Src});
20796         Chain = Res.getValue(1);
20797       } else {
20798         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
20799       }
20800 
20801       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
20802                         DAG.getIntPtrConstant(0, dl));
20803 
20804       if (IsStrict)
20805         return DAG.getMergeValues({Res, Chain}, dl);
20806       return Res;
20807     }
20808 
20809     if (VT == MVT::v2i64 && SrcVT  == MVT::v2f32) {
20810       if (!Subtarget.hasVLX()) {
20811         // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
20812         // legalizer and then widened again by vector op legalization.
20813         if (!IsStrict)
20814           return SDValue();
20815 
20816         SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
20817         SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
20818                                   {Src, Zero, Zero, Zero});
20819         Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
20820                           {Op->getOperand(0), Tmp});
20821         SDValue Chain = Tmp.getValue(1);
20822         Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
20823                           DAG.getIntPtrConstant(0, dl));
20824         if (IsStrict)
20825           return DAG.getMergeValues({Tmp, Chain}, dl);
20826         return Tmp;
20827       }
20828 
20829       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
20830       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
20831                                 DAG.getUNDEF(MVT::v2f32));
20832       if (IsStrict) {
20833         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
20834                                 : X86ISD::STRICT_CVTTP2UI;
20835         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
20836       }
20837       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
20838       return DAG.getNode(Opc, dl, VT, Tmp);
20839     }
20840 
20841     return SDValue();
20842   }
20843 
20844   assert(!VT.isVector());
20845 
20846   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
20847 
20848   if (!IsSigned && UseSSEReg) {
20849     // Conversions from f32/f64 with AVX512 should be legal.
20850     if (Subtarget.hasAVX512())
20851       return Op;
20852 
20853     // Use default expansion for i64.
20854     if (VT == MVT::i64)
20855       return SDValue();
20856 
20857     assert(VT == MVT::i32 && "Unexpected VT!");
20858 
20859     // Promote i32 to i64 and use a signed operation on 64-bit targets.
20860     // FIXME: This does not generate an invalid exception if the input does not
20861     // fit in i32. PR44019
20862     if (Subtarget.is64Bit()) {
20863       SDValue Res, Chain;
20864       if (IsStrict) {
20865         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i64, MVT::Other},
20866                           { Op.getOperand(0), Src });
20867         Chain = Res.getValue(1);
20868       } else
20869         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
20870 
20871       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20872       if (IsStrict)
20873         return DAG.getMergeValues({ Res, Chain }, dl);
20874       return Res;
20875     }
20876 
20877     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
20878     // use fisttp which will be handled later.
20879     if (!Subtarget.hasSSE3())
20880       return SDValue();
20881   }
20882 
20883   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
20884   // FIXME: This does not generate an invalid exception if the input does not
20885   // fit in i16. PR44019
20886   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
20887     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
20888     SDValue Res, Chain;
20889     if (IsStrict) {
20890       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i32, MVT::Other},
20891                         { Op.getOperand(0), Src });
20892       Chain = Res.getValue(1);
20893     } else
20894       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
20895 
20896     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20897     if (IsStrict)
20898       return DAG.getMergeValues({ Res, Chain }, dl);
20899     return Res;
20900   }
20901 
20902   // If this is a FP_TO_SINT using SSEReg we're done.
20903   if (UseSSEReg && IsSigned)
20904     return Op;
20905 
20906   // fp128 needs to use a libcall.
20907   if (SrcVT == MVT::f128) {
20908     RTLIB::Libcall LC;
20909     if (IsSigned)
20910       LC = RTLIB::getFPTOSINT(SrcVT, VT);
20911     else
20912       LC = RTLIB::getFPTOUINT(SrcVT, VT);
20913 
20914     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
20915     MakeLibCallOptions CallOptions;
20916     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
20917                                                   SDLoc(Op), Chain);
20918 
20919     if (IsStrict)
20920       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
20921 
20922     return Tmp.first;
20923   }
20924 
20925   // Fall back to X87.
20926   SDValue Chain;
20927   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
20928     if (IsStrict)
20929       return DAG.getMergeValues({V, Chain}, dl);
20930     return V;
20931   }
20932 
20933   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
20934 }
20935 
LowerLRINT_LLRINT(SDValue Op,SelectionDAG & DAG) const20936 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
20937                                              SelectionDAG &DAG) const {
20938   SDValue Src = Op.getOperand(0);
20939   MVT SrcVT = Src.getSimpleValueType();
20940 
20941   // If the source is in an SSE register, the node is Legal.
20942   if (isScalarFPTypeInSSEReg(SrcVT))
20943     return Op;
20944 
20945   return LRINT_LLRINTHelper(Op.getNode(), DAG);
20946 }
20947 
LRINT_LLRINTHelper(SDNode * N,SelectionDAG & DAG) const20948 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
20949                                               SelectionDAG &DAG) const {
20950   EVT DstVT = N->getValueType(0);
20951   SDValue Src = N->getOperand(0);
20952   EVT SrcVT = Src.getValueType();
20953 
20954   if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
20955     // f16 must be promoted before using the lowering in this routine.
20956     // fp128 does not use this lowering.
20957     return SDValue();
20958   }
20959 
20960   SDLoc DL(N);
20961   SDValue Chain = DAG.getEntryNode();
20962 
20963   bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
20964 
20965   // If we're converting from SSE, the stack slot needs to hold both types.
20966   // Otherwise it only needs to hold the DstVT.
20967   EVT OtherVT = UseSSE ? SrcVT : DstVT;
20968   SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
20969   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
20970   MachinePointerInfo MPI =
20971       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
20972 
20973   if (UseSSE) {
20974     assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
20975     Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
20976     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20977     SDValue Ops[] = { Chain, StackPtr };
20978 
20979     Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
20980                                   /*Align*/ None, MachineMemOperand::MOLoad);
20981     Chain = Src.getValue(1);
20982   }
20983 
20984   SDValue StoreOps[] = { Chain, Src, StackPtr };
20985   Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
20986                                   StoreOps, DstVT, MPI, /*Align*/ None,
20987                                   MachineMemOperand::MOStore);
20988 
20989   return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
20990 }
20991 
LowerFP_EXTEND(SDValue Op,SelectionDAG & DAG) const20992 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
20993   bool IsStrict = Op->isStrictFPOpcode();
20994 
20995   SDLoc DL(Op);
20996   MVT VT = Op.getSimpleValueType();
20997   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
20998   MVT SVT = In.getSimpleValueType();
20999 
21000   if (VT == MVT::f128) {
21001     RTLIB::Libcall LC = RTLIB::getFPEXT(SVT, VT);
21002     return LowerF128Call(Op, DAG, LC);
21003   }
21004 
21005   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
21006 
21007   SDValue Res =
21008       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
21009   if (IsStrict)
21010     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21011                        {Op->getOperand(0), Res});
21012   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21013 }
21014 
LowerFP_ROUND(SDValue Op,SelectionDAG & DAG) const21015 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21016   bool IsStrict = Op->isStrictFPOpcode();
21017 
21018   MVT VT = Op.getSimpleValueType();
21019   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21020   MVT SVT = In.getSimpleValueType();
21021 
21022   // It's legal except when f128 is involved
21023   if (SVT != MVT::f128)
21024     return Op;
21025 
21026   RTLIB::Libcall LC = RTLIB::getFPROUND(SVT, VT);
21027 
21028   // FP_ROUND node has a second operand indicating whether it is known to be
21029   // precise. That doesn't take part in the LibCall so we can't directly use
21030   // LowerF128Call.
21031 
21032   SDLoc dl(Op);
21033   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21034   MakeLibCallOptions CallOptions;
21035   std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, In, CallOptions,
21036                                                 dl, Chain);
21037 
21038   if (IsStrict)
21039     return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
21040 
21041   return Tmp.first;
21042 }
21043 
LowerFP16_TO_FP(SDValue Op,SelectionDAG & DAG)21044 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
21045   bool IsStrict = Op->isStrictFPOpcode();
21046   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21047   assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
21048          "Unexpected VT!");
21049 
21050   SDLoc dl(Op);
21051   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
21052                             DAG.getConstant(0, dl, MVT::v8i16), Src,
21053                             DAG.getIntPtrConstant(0, dl));
21054 
21055   SDValue Chain;
21056   if (IsStrict) {
21057     Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
21058                       {Op.getOperand(0), Res});
21059     Chain = Res.getValue(1);
21060   } else {
21061     Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
21062   }
21063 
21064   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
21065                     DAG.getIntPtrConstant(0, dl));
21066 
21067   if (IsStrict)
21068     return DAG.getMergeValues({Res, Chain}, dl);
21069 
21070   return Res;
21071 }
21072 
LowerFP_TO_FP16(SDValue Op,SelectionDAG & DAG)21073 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
21074   bool IsStrict = Op->isStrictFPOpcode();
21075   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21076   assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
21077          "Unexpected VT!");
21078 
21079   SDLoc dl(Op);
21080   SDValue Res, Chain;
21081   if (IsStrict) {
21082     Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
21083                       DAG.getConstantFP(0, dl, MVT::v4f32), Src,
21084                       DAG.getIntPtrConstant(0, dl));
21085     Res = DAG.getNode(
21086         X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
21087         {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
21088     Chain = Res.getValue(1);
21089   } else {
21090     // FIXME: Should we use zeros for upper elements for non-strict?
21091     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
21092     Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
21093                       DAG.getTargetConstant(4, dl, MVT::i32));
21094   }
21095 
21096   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
21097                     DAG.getIntPtrConstant(0, dl));
21098 
21099   if (IsStrict)
21100     return DAG.getMergeValues({Res, Chain}, dl);
21101 
21102   return Res;
21103 }
21104 
21105 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21106 /// vector operation in place of the typical scalar operation.
lowerAddSubToHorizontalOp(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)21107 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
21108                                          const X86Subtarget &Subtarget) {
21109   // If both operands have other uses, this is probably not profitable.
21110   SDValue LHS = Op.getOperand(0);
21111   SDValue RHS = Op.getOperand(1);
21112   if (!LHS.hasOneUse() && !RHS.hasOneUse())
21113     return Op;
21114 
21115   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
21116   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
21117   if (IsFP && !Subtarget.hasSSE3())
21118     return Op;
21119   if (!IsFP && !Subtarget.hasSSSE3())
21120     return Op;
21121 
21122   // Extract from a common vector.
21123   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21124       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21125       LHS.getOperand(0) != RHS.getOperand(0) ||
21126       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
21127       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
21128       !shouldUseHorizontalOp(true, DAG, Subtarget))
21129     return Op;
21130 
21131   // Allow commuted 'hadd' ops.
21132   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
21133   unsigned HOpcode;
21134   switch (Op.getOpcode()) {
21135     case ISD::ADD: HOpcode = X86ISD::HADD; break;
21136     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
21137     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
21138     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
21139     default:
21140       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
21141   }
21142   unsigned LExtIndex = LHS.getConstantOperandVal(1);
21143   unsigned RExtIndex = RHS.getConstantOperandVal(1);
21144   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
21145       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
21146     std::swap(LExtIndex, RExtIndex);
21147 
21148   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
21149     return Op;
21150 
21151   SDValue X = LHS.getOperand(0);
21152   EVT VecVT = X.getValueType();
21153   unsigned BitWidth = VecVT.getSizeInBits();
21154   unsigned NumLanes = BitWidth / 128;
21155   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
21156   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
21157          "Not expecting illegal vector widths here");
21158 
21159   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
21160   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
21161   SDLoc DL(Op);
21162   if (BitWidth == 256 || BitWidth == 512) {
21163     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
21164     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
21165     LExtIndex %= NumEltsPerLane;
21166   }
21167 
21168   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
21169   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
21170   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
21171   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
21172   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
21173   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
21174                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
21175 }
21176 
21177 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21178 /// vector operation in place of the typical scalar operation.
lowerFaddFsub(SDValue Op,SelectionDAG & DAG) const21179 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
21180   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
21181          "Only expecting float/double");
21182   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
21183 }
21184 
21185 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
21186 /// This mode isn't supported in hardware on X86. But as long as we aren't
21187 /// compiling with trapping math, we can emulate this with
21188 /// floor(X + copysign(nextafter(0.5, 0.0), X)).
LowerFROUND(SDValue Op,SelectionDAG & DAG)21189 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
21190   SDValue N0 = Op.getOperand(0);
21191   SDLoc dl(Op);
21192   MVT VT = Op.getSimpleValueType();
21193 
21194   // N0 += copysign(nextafter(0.5, 0.0), N0)
21195   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21196   bool Ignored;
21197   APFloat Point5Pred = APFloat(0.5f);
21198   Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
21199   Point5Pred.next(/*nextDown*/true);
21200 
21201   SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
21202                               DAG.getConstantFP(Point5Pred, dl, VT), N0);
21203   N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
21204 
21205   // Truncate the result to remove fraction.
21206   return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
21207 }
21208 
21209 /// The only differences between FABS and FNEG are the mask and the logic op.
21210 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
LowerFABSorFNEG(SDValue Op,SelectionDAG & DAG)21211 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
21212   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
21213          "Wrong opcode for lowering FABS or FNEG.");
21214 
21215   bool IsFABS = (Op.getOpcode() == ISD::FABS);
21216 
21217   // If this is a FABS and it has an FNEG user, bail out to fold the combination
21218   // into an FNABS. We'll lower the FABS after that if it is still in use.
21219   if (IsFABS)
21220     for (SDNode *User : Op->uses())
21221       if (User->getOpcode() == ISD::FNEG)
21222         return Op;
21223 
21224   SDLoc dl(Op);
21225   MVT VT = Op.getSimpleValueType();
21226 
21227   bool IsF128 = (VT == MVT::f128);
21228   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
21229           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
21230           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
21231          "Unexpected type in LowerFABSorFNEG");
21232 
21233   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
21234   // decide if we should generate a 16-byte constant mask when we only need 4 or
21235   // 8 bytes for the scalar case.
21236 
21237   // There are no scalar bitwise logical SSE/AVX instructions, so we
21238   // generate a 16-byte vector constant and logic op even for the scalar case.
21239   // Using a 16-byte mask allows folding the load of the mask with
21240   // the logic op, so it can save (~4 bytes) on code size.
21241   bool IsFakeVector = !VT.isVector() && !IsF128;
21242   MVT LogicVT = VT;
21243   if (IsFakeVector)
21244     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
21245 
21246   unsigned EltBits = VT.getScalarSizeInBits();
21247   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
21248   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
21249                            APInt::getSignMask(EltBits);
21250   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21251   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
21252 
21253   SDValue Op0 = Op.getOperand(0);
21254   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
21255   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
21256                      IsFNABS ? X86ISD::FOR  :
21257                                X86ISD::FXOR;
21258   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
21259 
21260   if (VT.isVector() || IsF128)
21261     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
21262 
21263   // For the scalar case extend to a 128-bit vector, perform the logic op,
21264   // and extract the scalar result back out.
21265   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
21266   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
21267   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
21268                      DAG.getIntPtrConstant(0, dl));
21269 }
21270 
LowerFCOPYSIGN(SDValue Op,SelectionDAG & DAG)21271 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
21272   SDValue Mag = Op.getOperand(0);
21273   SDValue Sign = Op.getOperand(1);
21274   SDLoc dl(Op);
21275 
21276   // If the sign operand is smaller, extend it first.
21277   MVT VT = Op.getSimpleValueType();
21278   if (Sign.getSimpleValueType().bitsLT(VT))
21279     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
21280 
21281   // And if it is bigger, shrink it first.
21282   if (Sign.getSimpleValueType().bitsGT(VT))
21283     Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(1, dl));
21284 
21285   // At this point the operands and the result should have the same
21286   // type, and that won't be f80 since that is not custom lowered.
21287   bool IsF128 = (VT == MVT::f128);
21288   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
21289           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
21290           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
21291          "Unexpected type in LowerFCOPYSIGN");
21292 
21293   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21294 
21295   // Perform all scalar logic operations as 16-byte vectors because there are no
21296   // scalar FP logic instructions in SSE.
21297   // TODO: This isn't necessary. If we used scalar types, we might avoid some
21298   // unnecessary splats, but we might miss load folding opportunities. Should
21299   // this decision be based on OptimizeForSize?
21300   bool IsFakeVector = !VT.isVector() && !IsF128;
21301   MVT LogicVT = VT;
21302   if (IsFakeVector)
21303     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
21304 
21305   // The mask constants are automatically splatted for vector types.
21306   unsigned EltSizeInBits = VT.getScalarSizeInBits();
21307   SDValue SignMask = DAG.getConstantFP(
21308       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
21309   SDValue MagMask = DAG.getConstantFP(
21310       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
21311 
21312   // First, clear all bits but the sign bit from the second operand (sign).
21313   if (IsFakeVector)
21314     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
21315   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
21316 
21317   // Next, clear the sign bit from the first operand (magnitude).
21318   // TODO: If we had general constant folding for FP logic ops, this check
21319   // wouldn't be necessary.
21320   SDValue MagBits;
21321   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
21322     APFloat APF = Op0CN->getValueAPF();
21323     APF.clearSign();
21324     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
21325   } else {
21326     // If the magnitude operand wasn't a constant, we need to AND out the sign.
21327     if (IsFakeVector)
21328       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
21329     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
21330   }
21331 
21332   // OR the magnitude value with the sign bit.
21333   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
21334   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
21335                                           DAG.getIntPtrConstant(0, dl));
21336 }
21337 
LowerFGETSIGN(SDValue Op,SelectionDAG & DAG)21338 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
21339   SDValue N0 = Op.getOperand(0);
21340   SDLoc dl(Op);
21341   MVT VT = Op.getSimpleValueType();
21342 
21343   MVT OpVT = N0.getSimpleValueType();
21344   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
21345          "Unexpected type for FGETSIGN");
21346 
21347   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
21348   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
21349   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
21350   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
21351   Res = DAG.getZExtOrTrunc(Res, dl, VT);
21352   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
21353   return Res;
21354 }
21355 
21356 /// Helper for creating a X86ISD::SETCC node.
getSETCC(X86::CondCode Cond,SDValue EFLAGS,const SDLoc & dl,SelectionDAG & DAG)21357 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
21358                         SelectionDAG &DAG) {
21359   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
21360                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
21361 }
21362 
21363 /// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
21364 /// style scalarized (associative) reduction patterns. Partial reductions
21365 /// are supported when the pointer SrcMask is non-null.
21366 /// TODO - move this to SelectionDAG?
matchScalarReduction(SDValue Op,ISD::NodeType BinOp,SmallVectorImpl<SDValue> & SrcOps,SmallVectorImpl<APInt> * SrcMask=nullptr)21367 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
21368                                  SmallVectorImpl<SDValue> &SrcOps,
21369                                  SmallVectorImpl<APInt> *SrcMask = nullptr) {
21370   SmallVector<SDValue, 8> Opnds;
21371   DenseMap<SDValue, APInt> SrcOpMap;
21372   EVT VT = MVT::Other;
21373 
21374   // Recognize a special case where a vector is casted into wide integer to
21375   // test all 0s.
21376   assert(Op.getOpcode() == unsigned(BinOp) &&
21377          "Unexpected bit reduction opcode");
21378   Opnds.push_back(Op.getOperand(0));
21379   Opnds.push_back(Op.getOperand(1));
21380 
21381   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
21382     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
21383     // BFS traverse all BinOp operands.
21384     if (I->getOpcode() == unsigned(BinOp)) {
21385       Opnds.push_back(I->getOperand(0));
21386       Opnds.push_back(I->getOperand(1));
21387       // Re-evaluate the number of nodes to be traversed.
21388       e += 2; // 2 more nodes (LHS and RHS) are pushed.
21389       continue;
21390     }
21391 
21392     // Quit if a non-EXTRACT_VECTOR_ELT
21393     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21394       return false;
21395 
21396     // Quit if without a constant index.
21397     auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
21398     if (!Idx)
21399       return false;
21400 
21401     SDValue Src = I->getOperand(0);
21402     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
21403     if (M == SrcOpMap.end()) {
21404       VT = Src.getValueType();
21405       // Quit if not the same type.
21406       if (SrcOpMap.begin() != SrcOpMap.end() &&
21407           VT != SrcOpMap.begin()->first.getValueType())
21408         return false;
21409       unsigned NumElts = VT.getVectorNumElements();
21410       APInt EltCount = APInt::getNullValue(NumElts);
21411       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
21412       SrcOps.push_back(Src);
21413     }
21414 
21415     // Quit if element already used.
21416     unsigned CIdx = Idx->getZExtValue();
21417     if (M->second[CIdx])
21418       return false;
21419     M->second.setBit(CIdx);
21420   }
21421 
21422   if (SrcMask) {
21423     // Collect the source partial masks.
21424     for (SDValue &SrcOp : SrcOps)
21425       SrcMask->push_back(SrcOpMap[SrcOp]);
21426   } else {
21427     // Quit if not all elements are used.
21428     for (DenseMap<SDValue, APInt>::const_iterator I = SrcOpMap.begin(),
21429                                                   E = SrcOpMap.end();
21430          I != E; ++I) {
21431       if (!I->second.isAllOnesValue())
21432         return false;
21433     }
21434   }
21435 
21436   return true;
21437 }
21438 
21439 // Helper function for comparing all bits of a vector against zero.
LowerVectorAllZero(const SDLoc & DL,SDValue V,ISD::CondCode CC,const APInt & Mask,const X86Subtarget & Subtarget,SelectionDAG & DAG,X86::CondCode & X86CC)21440 static SDValue LowerVectorAllZero(const SDLoc &DL, SDValue V, ISD::CondCode CC,
21441                                   const APInt &Mask,
21442                                   const X86Subtarget &Subtarget,
21443                                   SelectionDAG &DAG, X86::CondCode &X86CC) {
21444   EVT VT = V.getValueType();
21445   assert(Mask.getBitWidth() == VT.getScalarSizeInBits() &&
21446          "Element Mask vs Vector bitwidth mismatch");
21447 
21448   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
21449   X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
21450 
21451   auto MaskBits = [&](SDValue Src) {
21452     if (Mask.isAllOnesValue())
21453       return Src;
21454     EVT SrcVT = Src.getValueType();
21455     SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
21456     return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
21457   };
21458 
21459   // For sub-128-bit vector, cast to (legal) integer and compare with zero.
21460   if (VT.getSizeInBits() < 128) {
21461     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
21462     if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT))
21463       return SDValue();
21464     return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
21465                        DAG.getBitcast(IntVT, MaskBits(V)),
21466                        DAG.getConstant(0, DL, IntVT));
21467   }
21468 
21469   // Quit if not splittable to 128/256-bit vector.
21470   if (!isPowerOf2_32(VT.getSizeInBits()))
21471     return SDValue();
21472 
21473   // Split down to 128/256-bit vector.
21474   unsigned TestSize = Subtarget.hasAVX() ? 256 : 128;
21475   while (VT.getSizeInBits() > TestSize) {
21476     auto Split = DAG.SplitVector(V, DL);
21477     VT = Split.first.getValueType();
21478     V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
21479   }
21480 
21481   bool UsePTEST = Subtarget.hasSSE41();
21482   if (UsePTEST) {
21483     MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
21484     V = DAG.getBitcast(TestVT, MaskBits(V));
21485     return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
21486   }
21487 
21488   // Without PTEST, a masked v2i64 or-reduction is not faster than
21489   // scalarization.
21490   if (!Mask.isAllOnesValue() && VT.getScalarSizeInBits() > 32)
21491       return SDValue();
21492 
21493   V = DAG.getBitcast(MVT::v16i8, MaskBits(V));
21494   V = DAG.getNode(X86ISD::PCMPEQ, DL, MVT::v16i8, V,
21495                   getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
21496   V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
21497   return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
21498                      DAG.getConstant(0xFFFF, DL, MVT::i32));
21499 }
21500 
21501 // Check whether an OR'd reduction tree is PTEST-able, or if we can fallback to
21502 // CMP(MOVMSK(PCMPEQB(X,0))).
MatchVectorAllZeroTest(SDValue Op,ISD::CondCode CC,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & X86CC)21503 static SDValue MatchVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
21504                                       const SDLoc &DL,
21505                                       const X86Subtarget &Subtarget,
21506                                       SelectionDAG &DAG, SDValue &X86CC) {
21507   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
21508 
21509   if (!Subtarget.hasSSE2() || !Op->hasOneUse())
21510     return SDValue();
21511 
21512   // Check whether we're masking/truncating an OR-reduction result, in which
21513   // case track the masked bits.
21514   APInt Mask = APInt::getAllOnesValue(Op.getScalarValueSizeInBits());
21515   switch (Op.getOpcode()) {
21516   case ISD::TRUNCATE: {
21517     SDValue Src = Op.getOperand(0);
21518     Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
21519                                 Op.getScalarValueSizeInBits());
21520     Op = Src;
21521     break;
21522   }
21523   case ISD::AND: {
21524     if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21525       Mask = Cst->getAPIntValue();
21526       Op = Op.getOperand(0);
21527     }
21528     break;
21529   }
21530   }
21531 
21532   SmallVector<SDValue, 8> VecIns;
21533   if (Op.getOpcode() == ISD::OR && matchScalarReduction(Op, ISD::OR, VecIns)) {
21534     EVT VT = VecIns[0].getValueType();
21535     assert(llvm::all_of(VecIns,
21536                         [VT](SDValue V) { return VT == V.getValueType(); }) &&
21537            "Reduction source vector mismatch");
21538 
21539     // Quit if less than 128-bits or not splittable to 128/256-bit vector.
21540     if (VT.getSizeInBits() < 128 || !isPowerOf2_32(VT.getSizeInBits()))
21541       return SDValue();
21542 
21543     // If more than one full vector is evaluated, OR them first before PTEST.
21544     for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
21545          Slot += 2, e += 1) {
21546       // Each iteration will OR 2 nodes and append the result until there is
21547       // only 1 node left, i.e. the final OR'd value of all vectors.
21548       SDValue LHS = VecIns[Slot];
21549       SDValue RHS = VecIns[Slot + 1];
21550       VecIns.push_back(DAG.getNode(ISD::OR, DL, VT, LHS, RHS));
21551     }
21552 
21553     X86::CondCode CCode;
21554     if (SDValue V = LowerVectorAllZero(DL, VecIns.back(), CC, Mask, Subtarget,
21555                                        DAG, CCode)) {
21556       X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
21557       return V;
21558     }
21559   }
21560 
21561   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
21562     ISD::NodeType BinOp;
21563     if (SDValue Match =
21564             DAG.matchBinOpReduction(Op.getNode(), BinOp, {ISD::OR})) {
21565       X86::CondCode CCode;
21566       if (SDValue V =
21567               LowerVectorAllZero(DL, Match, CC, Mask, Subtarget, DAG, CCode)) {
21568         X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
21569         return V;
21570       }
21571     }
21572   }
21573 
21574   return SDValue();
21575 }
21576 
21577 /// return true if \c Op has a use that doesn't just read flags.
hasNonFlagsUse(SDValue Op)21578 static bool hasNonFlagsUse(SDValue Op) {
21579   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
21580        ++UI) {
21581     SDNode *User = *UI;
21582     unsigned UOpNo = UI.getOperandNo();
21583     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
21584       // Look pass truncate.
21585       UOpNo = User->use_begin().getOperandNo();
21586       User = *User->use_begin();
21587     }
21588 
21589     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
21590         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
21591       return true;
21592   }
21593   return false;
21594 }
21595 
21596 // Transform to an x86-specific ALU node with flags if there is a chance of
21597 // using an RMW op or only the flags are used. Otherwise, leave
21598 // the node alone and emit a 'cmp' or 'test' instruction.
isProfitableToUseFlagOp(SDValue Op)21599 static bool isProfitableToUseFlagOp(SDValue Op) {
21600   for (SDNode *U : Op->uses())
21601     if (U->getOpcode() != ISD::CopyToReg &&
21602         U->getOpcode() != ISD::SETCC &&
21603         U->getOpcode() != ISD::STORE)
21604       return false;
21605 
21606   return true;
21607 }
21608 
21609 /// Emit nodes that will be selected as "test Op0,Op0", or something
21610 /// equivalent.
EmitTest(SDValue Op,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)21611 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
21612                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
21613   // CF and OF aren't always set the way we want. Determine which
21614   // of these we need.
21615   bool NeedCF = false;
21616   bool NeedOF = false;
21617   switch (X86CC) {
21618   default: break;
21619   case X86::COND_A: case X86::COND_AE:
21620   case X86::COND_B: case X86::COND_BE:
21621     NeedCF = true;
21622     break;
21623   case X86::COND_G: case X86::COND_GE:
21624   case X86::COND_L: case X86::COND_LE:
21625   case X86::COND_O: case X86::COND_NO: {
21626     // Check if we really need to set the
21627     // Overflow flag. If NoSignedWrap is present
21628     // that is not actually needed.
21629     switch (Op->getOpcode()) {
21630     case ISD::ADD:
21631     case ISD::SUB:
21632     case ISD::MUL:
21633     case ISD::SHL:
21634       if (Op.getNode()->getFlags().hasNoSignedWrap())
21635         break;
21636       LLVM_FALLTHROUGH;
21637     default:
21638       NeedOF = true;
21639       break;
21640     }
21641     break;
21642   }
21643   }
21644   // See if we can use the EFLAGS value from the operand instead of
21645   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
21646   // we prove that the arithmetic won't overflow, we can't use OF or CF.
21647   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
21648     // Emit a CMP with 0, which is the TEST pattern.
21649     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
21650                        DAG.getConstant(0, dl, Op.getValueType()));
21651   }
21652   unsigned Opcode = 0;
21653   unsigned NumOperands = 0;
21654 
21655   SDValue ArithOp = Op;
21656 
21657   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
21658   // which may be the result of a CAST.  We use the variable 'Op', which is the
21659   // non-casted variable when we check for possible users.
21660   switch (ArithOp.getOpcode()) {
21661   case ISD::AND:
21662     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
21663     // because a TEST instruction will be better.
21664     if (!hasNonFlagsUse(Op))
21665       break;
21666 
21667     LLVM_FALLTHROUGH;
21668   case ISD::ADD:
21669   case ISD::SUB:
21670   case ISD::OR:
21671   case ISD::XOR:
21672     if (!isProfitableToUseFlagOp(Op))
21673       break;
21674 
21675     // Otherwise use a regular EFLAGS-setting instruction.
21676     switch (ArithOp.getOpcode()) {
21677     default: llvm_unreachable("unexpected operator!");
21678     case ISD::ADD: Opcode = X86ISD::ADD; break;
21679     case ISD::SUB: Opcode = X86ISD::SUB; break;
21680     case ISD::XOR: Opcode = X86ISD::XOR; break;
21681     case ISD::AND: Opcode = X86ISD::AND; break;
21682     case ISD::OR:  Opcode = X86ISD::OR;  break;
21683     }
21684 
21685     NumOperands = 2;
21686     break;
21687   case X86ISD::ADD:
21688   case X86ISD::SUB:
21689   case X86ISD::OR:
21690   case X86ISD::XOR:
21691   case X86ISD::AND:
21692     return SDValue(Op.getNode(), 1);
21693   case ISD::SSUBO:
21694   case ISD::USUBO: {
21695     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
21696     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
21697     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
21698                        Op->getOperand(1)).getValue(1);
21699   }
21700   default:
21701     break;
21702   }
21703 
21704   if (Opcode == 0) {
21705     // Emit a CMP with 0, which is the TEST pattern.
21706     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
21707                        DAG.getConstant(0, dl, Op.getValueType()));
21708   }
21709   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
21710   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
21711 
21712   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
21713   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
21714   return SDValue(New.getNode(), 1);
21715 }
21716 
21717 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
21718 /// equivalent.
EmitCmp(SDValue Op0,SDValue Op1,unsigned X86CC,const SDLoc & dl,SelectionDAG & DAG,const X86Subtarget & Subtarget)21719 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
21720                        const SDLoc &dl, SelectionDAG &DAG,
21721                        const X86Subtarget &Subtarget) {
21722   if (isNullConstant(Op1))
21723     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
21724 
21725   EVT CmpVT = Op0.getValueType();
21726 
21727   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
21728           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
21729 
21730   // Only promote the compare up to I32 if it is a 16 bit operation
21731   // with an immediate.  16 bit immediates are to be avoided.
21732   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
21733       !DAG.getMachineFunction().getFunction().hasMinSize()) {
21734     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
21735     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
21736     // Don't do this if the immediate can fit in 8-bits.
21737     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
21738         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
21739       unsigned ExtendOp =
21740           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
21741       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
21742         // For equality comparisons try to use SIGN_EXTEND if the input was
21743         // truncate from something with enough sign bits.
21744         if (Op0.getOpcode() == ISD::TRUNCATE) {
21745           SDValue In = Op0.getOperand(0);
21746           unsigned EffBits =
21747               In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
21748           if (EffBits <= 16)
21749             ExtendOp = ISD::SIGN_EXTEND;
21750         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
21751           SDValue In = Op1.getOperand(0);
21752           unsigned EffBits =
21753               In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
21754           if (EffBits <= 16)
21755             ExtendOp = ISD::SIGN_EXTEND;
21756         }
21757       }
21758 
21759       CmpVT = MVT::i32;
21760       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
21761       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
21762     }
21763   }
21764 
21765   // Try to shrink i64 compares if the input has enough zero bits.
21766   // FIXME: Do this for non-constant compares for constant on LHS?
21767   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
21768       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
21769       cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
21770       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
21771     CmpVT = MVT::i32;
21772     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
21773     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
21774   }
21775 
21776   // 0-x == y --> x+y == 0
21777   // 0-x != y --> x+y != 0
21778   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
21779       Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
21780     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
21781     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
21782     return Add.getValue(1);
21783   }
21784 
21785   // x == 0-y --> x+y == 0
21786   // x != 0-y --> x+y != 0
21787   if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
21788       Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
21789     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
21790     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
21791     return Add.getValue(1);
21792   }
21793 
21794   // Use SUB instead of CMP to enable CSE between SUB and CMP.
21795   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
21796   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
21797   return Sub.getValue(1);
21798 }
21799 
21800 /// Check if replacement of SQRT with RSQRT should be disabled.
isFsqrtCheap(SDValue Op,SelectionDAG & DAG) const21801 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
21802   EVT VT = Op.getValueType();
21803 
21804   // We never want to use both SQRT and RSQRT instructions for the same input.
21805   if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
21806     return false;
21807 
21808   if (VT.isVector())
21809     return Subtarget.hasFastVectorFSQRT();
21810   return Subtarget.hasFastScalarFSQRT();
21811 }
21812 
21813 /// The minimum architected relative accuracy is 2^-12. We need one
21814 /// 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) const21815 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
21816                                            SelectionDAG &DAG, int Enabled,
21817                                            int &RefinementSteps,
21818                                            bool &UseOneConstNR,
21819                                            bool Reciprocal) const {
21820   EVT VT = Op.getValueType();
21821 
21822   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
21823   // It is likely not profitable to do this for f64 because a double-precision
21824   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
21825   // instructions: convert to single, rsqrtss, convert back to double, refine
21826   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
21827   // along with FMA, this could be a throughput win.
21828   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
21829   // after legalize types.
21830   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
21831       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
21832       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
21833       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
21834       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
21835     if (RefinementSteps == ReciprocalEstimate::Unspecified)
21836       RefinementSteps = 1;
21837 
21838     UseOneConstNR = false;
21839     // There is no FSQRT for 512-bits, but there is RSQRT14.
21840     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
21841     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
21842   }
21843   return SDValue();
21844 }
21845 
21846 /// The minimum architected relative accuracy is 2^-12. We need one
21847 /// Newton-Raphson step to have a good float result (24 bits of precision).
getRecipEstimate(SDValue Op,SelectionDAG & DAG,int Enabled,int & RefinementSteps) const21848 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
21849                                             int Enabled,
21850                                             int &RefinementSteps) const {
21851   EVT VT = Op.getValueType();
21852 
21853   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
21854   // It is likely not profitable to do this for f64 because a double-precision
21855   // reciprocal estimate with refinement on x86 prior to FMA requires
21856   // 15 instructions: convert to single, rcpss, convert back to double, refine
21857   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
21858   // along with FMA, this could be a throughput win.
21859 
21860   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
21861       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
21862       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
21863       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
21864     // Enable estimate codegen with 1 refinement step for vector division.
21865     // Scalar division estimates are disabled because they break too much
21866     // real-world code. These defaults are intended to match GCC behavior.
21867     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
21868       return SDValue();
21869 
21870     if (RefinementSteps == ReciprocalEstimate::Unspecified)
21871       RefinementSteps = 1;
21872 
21873     // There is no FSQRT for 512-bits, but there is RCP14.
21874     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
21875     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
21876   }
21877   return SDValue();
21878 }
21879 
21880 /// If we have at least two divisions that use the same divisor, convert to
21881 /// multiplication by a reciprocal. This may need to be adjusted for a given
21882 /// CPU if a division's cost is not at least twice the cost of a multiplication.
21883 /// This is because we still need one division to calculate the reciprocal and
21884 /// then we need two multiplies by that reciprocal as replacements for the
21885 /// original divisions.
combineRepeatedFPDivisors() const21886 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
21887   return 2;
21888 }
21889 
21890 SDValue
BuildSDIVPow2(SDNode * N,const APInt & Divisor,SelectionDAG & DAG,SmallVectorImpl<SDNode * > & Created) const21891 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
21892                                  SelectionDAG &DAG,
21893                                  SmallVectorImpl<SDNode *> &Created) const {
21894   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
21895   if (isIntDivCheap(N->getValueType(0), Attr))
21896     return SDValue(N,0); // Lower SDIV as SDIV
21897 
21898   assert((Divisor.isPowerOf2() || (-Divisor).isPowerOf2()) &&
21899          "Unexpected divisor!");
21900 
21901   // Only perform this transform if CMOV is supported otherwise the select
21902   // below will become a branch.
21903   if (!Subtarget.hasCMov())
21904     return SDValue();
21905 
21906   // fold (sdiv X, pow2)
21907   EVT VT = N->getValueType(0);
21908   // FIXME: Support i8.
21909   if (VT != MVT::i16 && VT != MVT::i32 &&
21910       !(Subtarget.is64Bit() && VT == MVT::i64))
21911     return SDValue();
21912 
21913   unsigned Lg2 = Divisor.countTrailingZeros();
21914 
21915   // If the divisor is 2 or -2, the default expansion is better.
21916   if (Lg2 == 1)
21917     return SDValue();
21918 
21919   SDLoc DL(N);
21920   SDValue N0 = N->getOperand(0);
21921   SDValue Zero = DAG.getConstant(0, DL, VT);
21922   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
21923   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
21924 
21925   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
21926   SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
21927   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
21928   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
21929 
21930   Created.push_back(Cmp.getNode());
21931   Created.push_back(Add.getNode());
21932   Created.push_back(CMov.getNode());
21933 
21934   // Divide by pow2.
21935   SDValue SRA =
21936       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
21937 
21938   // If we're dividing by a positive value, we're done.  Otherwise, we must
21939   // negate the result.
21940   if (Divisor.isNonNegative())
21941     return SRA;
21942 
21943   Created.push_back(SRA.getNode());
21944   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
21945 }
21946 
21947 /// Result of 'and' is compared against zero. Change to a BT node if possible.
21948 /// Returns the BT node and the condition code needed to use it.
LowerAndToBT(SDValue And,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC)21949 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
21950                             const SDLoc &dl, SelectionDAG &DAG,
21951                             SDValue &X86CC) {
21952   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
21953   SDValue Op0 = And.getOperand(0);
21954   SDValue Op1 = And.getOperand(1);
21955   if (Op0.getOpcode() == ISD::TRUNCATE)
21956     Op0 = Op0.getOperand(0);
21957   if (Op1.getOpcode() == ISD::TRUNCATE)
21958     Op1 = Op1.getOperand(0);
21959 
21960   SDValue Src, BitNo;
21961   if (Op1.getOpcode() == ISD::SHL)
21962     std::swap(Op0, Op1);
21963   if (Op0.getOpcode() == ISD::SHL) {
21964     if (isOneConstant(Op0.getOperand(0))) {
21965       // If we looked past a truncate, check that it's only truncating away
21966       // known zeros.
21967       unsigned BitWidth = Op0.getValueSizeInBits();
21968       unsigned AndBitWidth = And.getValueSizeInBits();
21969       if (BitWidth > AndBitWidth) {
21970         KnownBits Known = DAG.computeKnownBits(Op0);
21971         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
21972           return SDValue();
21973       }
21974       Src = Op1;
21975       BitNo = Op0.getOperand(1);
21976     }
21977   } else if (Op1.getOpcode() == ISD::Constant) {
21978     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
21979     uint64_t AndRHSVal = AndRHS->getZExtValue();
21980     SDValue AndLHS = Op0;
21981 
21982     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
21983       Src = AndLHS.getOperand(0);
21984       BitNo = AndLHS.getOperand(1);
21985     } else {
21986       // Use BT if the immediate can't be encoded in a TEST instruction or we
21987       // are optimizing for size and the immedaite won't fit in a byte.
21988       bool OptForSize = DAG.shouldOptForSize();
21989       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
21990           isPowerOf2_64(AndRHSVal)) {
21991         Src = AndLHS;
21992         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
21993                                 Src.getValueType());
21994       }
21995     }
21996   }
21997 
21998   // No patterns found, give up.
21999   if (!Src.getNode())
22000     return SDValue();
22001 
22002   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
22003   // instruction.  Since the shift amount is in-range-or-undefined, we know
22004   // that doing a bittest on the i32 value is ok.  We extend to i32 because
22005   // the encoding for the i16 version is larger than the i32 version.
22006   // Also promote i16 to i32 for performance / code size reason.
22007   if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
22008     Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
22009 
22010   // See if we can use the 32-bit instruction instead of the 64-bit one for a
22011   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
22012   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
22013   // known to be zero.
22014   if (Src.getValueType() == MVT::i64 &&
22015       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
22016     Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
22017 
22018   // If the operand types disagree, extend the shift amount to match.  Since
22019   // BT ignores high bits (like shifts) we can use anyextend.
22020   if (Src.getValueType() != BitNo.getValueType())
22021     BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
22022 
22023   X86CC = DAG.getTargetConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
22024                                 dl, MVT::i8);
22025   return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
22026 }
22027 
22028 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
22029 /// CMPs.
translateX86FSETCC(ISD::CondCode SetCCOpcode,SDValue & Op0,SDValue & Op1,bool & IsAlwaysSignaling)22030 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
22031                                    SDValue &Op1, bool &IsAlwaysSignaling) {
22032   unsigned SSECC;
22033   bool Swap = false;
22034 
22035   // SSE Condition code mapping:
22036   //  0 - EQ
22037   //  1 - LT
22038   //  2 - LE
22039   //  3 - UNORD
22040   //  4 - NEQ
22041   //  5 - NLT
22042   //  6 - NLE
22043   //  7 - ORD
22044   switch (SetCCOpcode) {
22045   default: llvm_unreachable("Unexpected SETCC condition");
22046   case ISD::SETOEQ:
22047   case ISD::SETEQ:  SSECC = 0; break;
22048   case ISD::SETOGT:
22049   case ISD::SETGT:  Swap = true; LLVM_FALLTHROUGH;
22050   case ISD::SETLT:
22051   case ISD::SETOLT: SSECC = 1; break;
22052   case ISD::SETOGE:
22053   case ISD::SETGE:  Swap = true; LLVM_FALLTHROUGH;
22054   case ISD::SETLE:
22055   case ISD::SETOLE: SSECC = 2; break;
22056   case ISD::SETUO:  SSECC = 3; break;
22057   case ISD::SETUNE:
22058   case ISD::SETNE:  SSECC = 4; break;
22059   case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
22060   case ISD::SETUGE: SSECC = 5; break;
22061   case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
22062   case ISD::SETUGT: SSECC = 6; break;
22063   case ISD::SETO:   SSECC = 7; break;
22064   case ISD::SETUEQ: SSECC = 8; break;
22065   case ISD::SETONE: SSECC = 12; break;
22066   }
22067   if (Swap)
22068     std::swap(Op0, Op1);
22069 
22070   switch (SetCCOpcode) {
22071   default:
22072     IsAlwaysSignaling = true;
22073     break;
22074   case ISD::SETEQ:
22075   case ISD::SETOEQ:
22076   case ISD::SETUEQ:
22077   case ISD::SETNE:
22078   case ISD::SETONE:
22079   case ISD::SETUNE:
22080   case ISD::SETO:
22081   case ISD::SETUO:
22082     IsAlwaysSignaling = false;
22083     break;
22084   }
22085 
22086   return SSECC;
22087 }
22088 
22089 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
22090 /// concatenate the result back.
splitIntVSETCC(SDValue Op,SelectionDAG & DAG)22091 static SDValue splitIntVSETCC(SDValue Op, SelectionDAG &DAG) {
22092   EVT VT = Op.getValueType();
22093 
22094   assert(Op.getOpcode() == ISD::SETCC && "Unsupported operation");
22095   assert(Op.getOperand(0).getValueType().isInteger() &&
22096          VT == Op.getOperand(0).getValueType() && "Unsupported VTs!");
22097 
22098   SDLoc dl(Op);
22099   SDValue CC = Op.getOperand(2);
22100 
22101   // Extract the LHS Lo/Hi vectors
22102   SDValue LHS1, LHS2;
22103   std::tie(LHS1, LHS2) = splitVector(Op.getOperand(0), DAG, dl);
22104 
22105   // Extract the RHS Lo/Hi vectors
22106   SDValue RHS1, RHS2;
22107   std::tie(RHS1, RHS2) = splitVector(Op.getOperand(1), DAG, dl);
22108 
22109   // Issue the operation on the smaller types and concatenate the result back
22110   EVT LoVT, HiVT;
22111   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
22112   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
22113                      DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
22114                      DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
22115 }
22116 
LowerIntVSETCC_AVX512(SDValue Op,SelectionDAG & DAG)22117 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
22118 
22119   SDValue Op0 = Op.getOperand(0);
22120   SDValue Op1 = Op.getOperand(1);
22121   SDValue CC = Op.getOperand(2);
22122   MVT VT = Op.getSimpleValueType();
22123   SDLoc dl(Op);
22124 
22125   assert(VT.getVectorElementType() == MVT::i1 &&
22126          "Cannot set masked compare for this operation");
22127 
22128   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
22129 
22130   // Prefer SETGT over SETLT.
22131   if (SetCCOpcode == ISD::SETLT) {
22132     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
22133     std::swap(Op0, Op1);
22134   }
22135 
22136   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
22137 }
22138 
22139 /// Given a buildvector constant, return a new vector constant with each element
22140 /// incremented or decremented. If incrementing or decrementing would result in
22141 /// unsigned overflow or underflow or this is not a simple vector constant,
22142 /// return an empty value.
incDecVectorConstant(SDValue V,SelectionDAG & DAG,bool IsInc)22143 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
22144   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
22145   if (!BV)
22146     return SDValue();
22147 
22148   MVT VT = V.getSimpleValueType();
22149   MVT EltVT = VT.getVectorElementType();
22150   unsigned NumElts = VT.getVectorNumElements();
22151   SmallVector<SDValue, 8> NewVecC;
22152   SDLoc DL(V);
22153   for (unsigned i = 0; i < NumElts; ++i) {
22154     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
22155     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
22156       return SDValue();
22157 
22158     // Avoid overflow/underflow.
22159     const APInt &EltC = Elt->getAPIntValue();
22160     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isNullValue()))
22161       return SDValue();
22162 
22163     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
22164   }
22165 
22166   return DAG.getBuildVector(VT, DL, NewVecC);
22167 }
22168 
22169 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
22170 /// Op0 u<= Op1:
22171 ///   t = psubus Op0, Op1
22172 ///   pcmpeq t, <0..0>
LowerVSETCCWithSUBUS(SDValue Op0,SDValue Op1,MVT VT,ISD::CondCode Cond,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)22173 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
22174                                     ISD::CondCode Cond, const SDLoc &dl,
22175                                     const X86Subtarget &Subtarget,
22176                                     SelectionDAG &DAG) {
22177   if (!Subtarget.hasSSE2())
22178     return SDValue();
22179 
22180   MVT VET = VT.getVectorElementType();
22181   if (VET != MVT::i8 && VET != MVT::i16)
22182     return SDValue();
22183 
22184   switch (Cond) {
22185   default:
22186     return SDValue();
22187   case ISD::SETULT: {
22188     // If the comparison is against a constant we can turn this into a
22189     // setule.  With psubus, setule does not require a swap.  This is
22190     // beneficial because the constant in the register is no longer
22191     // destructed as the destination so it can be hoisted out of a loop.
22192     // Only do this pre-AVX since vpcmp* is no longer destructive.
22193     if (Subtarget.hasAVX())
22194       return SDValue();
22195     SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false);
22196     if (!ULEOp1)
22197       return SDValue();
22198     Op1 = ULEOp1;
22199     break;
22200   }
22201   case ISD::SETUGT: {
22202     // If the comparison is against a constant, we can turn this into a setuge.
22203     // This is beneficial because materializing a constant 0 for the PCMPEQ is
22204     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
22205     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
22206     SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true);
22207     if (!UGEOp1)
22208       return SDValue();
22209     Op1 = Op0;
22210     Op0 = UGEOp1;
22211     break;
22212   }
22213   // Psubus is better than flip-sign because it requires no inversion.
22214   case ISD::SETUGE:
22215     std::swap(Op0, Op1);
22216     break;
22217   case ISD::SETULE:
22218     break;
22219   }
22220 
22221   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
22222   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
22223                      DAG.getConstant(0, dl, VT));
22224 }
22225 
LowerVSETCC(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)22226 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
22227                            SelectionDAG &DAG) {
22228   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
22229                   Op.getOpcode() == ISD::STRICT_FSETCCS;
22230   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
22231   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
22232   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
22233   MVT VT = Op->getSimpleValueType(0);
22234   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
22235   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
22236   SDLoc dl(Op);
22237 
22238   if (isFP) {
22239 #ifndef NDEBUG
22240     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
22241     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
22242 #endif
22243 
22244     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
22245     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
22246 
22247     // If we have a strict compare with a vXi1 result and the input is 128/256
22248     // bits we can't use a masked compare unless we have VLX. If we use a wider
22249     // compare like we do for non-strict, we might trigger spurious exceptions
22250     // from the upper elements. Instead emit a AVX compare and convert to mask.
22251     unsigned Opc;
22252     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
22253         (!IsStrict || Subtarget.hasVLX() ||
22254          Op0.getSimpleValueType().is512BitVector())) {
22255       assert(VT.getVectorNumElements() <= 16);
22256       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
22257     } else {
22258       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
22259       // The SSE/AVX packed FP comparison nodes are defined with a
22260       // floating-point vector result that matches the operand type. This allows
22261       // them to work with an SSE1 target (integer vector types are not legal).
22262       VT = Op0.getSimpleValueType();
22263     }
22264 
22265     SDValue Cmp;
22266     bool IsAlwaysSignaling;
22267     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
22268     if (!Subtarget.hasAVX()) {
22269       // TODO: We could use following steps to handle a quiet compare with
22270       // signaling encodings.
22271       // 1. Get ordered masks from a quiet ISD::SETO
22272       // 2. Use the masks to mask potential unordered elements in operand A, B
22273       // 3. Get the compare results of masked A, B
22274       // 4. Calculating final result using the mask and result from 3
22275       // But currently, we just fall back to scalar operations.
22276       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
22277         return SDValue();
22278 
22279       // Insert an extra signaling instruction to raise exception.
22280       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
22281         SDValue SignalCmp = DAG.getNode(
22282             Opc, dl, {VT, MVT::Other},
22283             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
22284         // FIXME: It seems we need to update the flags of all new strict nodes.
22285         // Otherwise, mayRaiseFPException in MI will return false due to
22286         // NoFPExcept = false by default. However, I didn't find it in other
22287         // patches.
22288         SignalCmp->setFlags(Op->getFlags());
22289         Chain = SignalCmp.getValue(1);
22290       }
22291 
22292       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
22293       // emit two comparisons and a logic op to tie them together.
22294       if (SSECC >= 8) {
22295         // LLVM predicate is SETUEQ or SETONE.
22296         unsigned CC0, CC1;
22297         unsigned CombineOpc;
22298         if (Cond == ISD::SETUEQ) {
22299           CC0 = 3; // UNORD
22300           CC1 = 0; // EQ
22301           CombineOpc = X86ISD::FOR;
22302         } else {
22303           assert(Cond == ISD::SETONE);
22304           CC0 = 7; // ORD
22305           CC1 = 4; // NEQ
22306           CombineOpc = X86ISD::FAND;
22307         }
22308 
22309         SDValue Cmp0, Cmp1;
22310         if (IsStrict) {
22311           Cmp0 = DAG.getNode(
22312               Opc, dl, {VT, MVT::Other},
22313               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
22314           Cmp1 = DAG.getNode(
22315               Opc, dl, {VT, MVT::Other},
22316               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
22317           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
22318                               Cmp1.getValue(1));
22319         } else {
22320           Cmp0 = DAG.getNode(
22321               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
22322           Cmp1 = DAG.getNode(
22323               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
22324         }
22325         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
22326       } else {
22327         if (IsStrict) {
22328           Cmp = DAG.getNode(
22329               Opc, dl, {VT, MVT::Other},
22330               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
22331           Chain = Cmp.getValue(1);
22332         } else
22333           Cmp = DAG.getNode(
22334               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
22335       }
22336     } else {
22337       // Handle all other FP comparisons here.
22338       if (IsStrict) {
22339         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
22340         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
22341         Cmp = DAG.getNode(
22342             Opc, dl, {VT, MVT::Other},
22343             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
22344         Chain = Cmp.getValue(1);
22345       } else
22346         Cmp = DAG.getNode(
22347             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
22348     }
22349 
22350     if (VT.getSizeInBits() > Op.getSimpleValueType().getSizeInBits()) {
22351       // We emitted a compare with an XMM/YMM result. Finish converting to a
22352       // mask register using a vptestm.
22353       EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
22354       Cmp = DAG.getBitcast(CastVT, Cmp);
22355       Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
22356                          DAG.getConstant(0, dl, CastVT), ISD::SETNE);
22357     } else {
22358       // If this is SSE/AVX CMPP, bitcast the result back to integer to match
22359       // the result type of SETCC. The bitcast is expected to be optimized
22360       // away during combining/isel.
22361       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
22362     }
22363 
22364     if (IsStrict)
22365       return DAG.getMergeValues({Cmp, Chain}, dl);
22366 
22367     return Cmp;
22368   }
22369 
22370   assert(!IsStrict && "Strict SETCC only handles FP operands.");
22371 
22372   MVT VTOp0 = Op0.getSimpleValueType();
22373   (void)VTOp0;
22374   assert(VTOp0 == Op1.getSimpleValueType() &&
22375          "Expected operands with same type!");
22376   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
22377          "Invalid number of packed elements for source and destination!");
22378 
22379   // The non-AVX512 code below works under the assumption that source and
22380   // destination types are the same.
22381   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
22382          "Value types for source and destination must be the same!");
22383 
22384   // The result is boolean, but operands are int/float
22385   if (VT.getVectorElementType() == MVT::i1) {
22386     // In AVX-512 architecture setcc returns mask with i1 elements,
22387     // But there is no compare instruction for i8 and i16 elements in KNL.
22388     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
22389            "Unexpected operand type");
22390     return LowerIntVSETCC_AVX512(Op, DAG);
22391   }
22392 
22393   // Lower using XOP integer comparisons.
22394   if (VT.is128BitVector() && Subtarget.hasXOP()) {
22395     // Translate compare code to XOP PCOM compare mode.
22396     unsigned CmpMode = 0;
22397     switch (Cond) {
22398     default: llvm_unreachable("Unexpected SETCC condition");
22399     case ISD::SETULT:
22400     case ISD::SETLT: CmpMode = 0x00; break;
22401     case ISD::SETULE:
22402     case ISD::SETLE: CmpMode = 0x01; break;
22403     case ISD::SETUGT:
22404     case ISD::SETGT: CmpMode = 0x02; break;
22405     case ISD::SETUGE:
22406     case ISD::SETGE: CmpMode = 0x03; break;
22407     case ISD::SETEQ: CmpMode = 0x04; break;
22408     case ISD::SETNE: CmpMode = 0x05; break;
22409     }
22410 
22411     // Are we comparing unsigned or signed integers?
22412     unsigned Opc =
22413         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
22414 
22415     return DAG.getNode(Opc, dl, VT, Op0, Op1,
22416                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
22417   }
22418 
22419   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
22420   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
22421   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
22422     SDValue BC0 = peekThroughBitcasts(Op0);
22423     if (BC0.getOpcode() == ISD::AND) {
22424       APInt UndefElts;
22425       SmallVector<APInt, 64> EltBits;
22426       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
22427                                         VT.getScalarSizeInBits(), UndefElts,
22428                                         EltBits, false, false)) {
22429         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
22430           Cond = ISD::SETEQ;
22431           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
22432         }
22433       }
22434     }
22435   }
22436 
22437   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
22438   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
22439       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
22440     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
22441     if (C1 && C1->getAPIntValue().isPowerOf2()) {
22442       unsigned BitWidth = VT.getScalarSizeInBits();
22443       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
22444 
22445       SDValue Result = Op0.getOperand(0);
22446       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
22447                            DAG.getConstant(ShiftAmt, dl, VT));
22448       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
22449                            DAG.getConstant(BitWidth - 1, dl, VT));
22450       return Result;
22451     }
22452   }
22453 
22454   // Break 256-bit integer vector compare into smaller ones.
22455   if (VT.is256BitVector() && !Subtarget.hasInt256())
22456     return splitIntVSETCC(Op, DAG);
22457 
22458   if (VT == MVT::v32i16 || VT == MVT::v64i8) {
22459     assert(!Subtarget.hasBWI() && "Unexpected VT with AVX512BW!");
22460     return splitIntVSETCC(Op, DAG);
22461   }
22462 
22463   // If this is a SETNE against the signed minimum value, change it to SETGT.
22464   // If this is a SETNE against the signed maximum value, change it to SETLT.
22465   // which will be swapped to SETGT.
22466   // Otherwise we use PCMPEQ+invert.
22467   APInt ConstValue;
22468   if (Cond == ISD::SETNE &&
22469       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
22470     if (ConstValue.isMinSignedValue())
22471       Cond = ISD::SETGT;
22472     else if (ConstValue.isMaxSignedValue())
22473       Cond = ISD::SETLT;
22474   }
22475 
22476   // If both operands are known non-negative, then an unsigned compare is the
22477   // same as a signed compare and there's no need to flip signbits.
22478   // TODO: We could check for more general simplifications here since we're
22479   // computing known bits.
22480   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
22481                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
22482 
22483   // Special case: Use min/max operations for unsigned compares.
22484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22485   if (ISD::isUnsignedIntSetCC(Cond) &&
22486       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
22487       TLI.isOperationLegal(ISD::UMIN, VT)) {
22488     // If we have a constant operand, increment/decrement it and change the
22489     // condition to avoid an invert.
22490     if (Cond == ISD::SETUGT) {
22491       // X > C --> X >= (C+1) --> X == umax(X, C+1)
22492       if (SDValue UGTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true)) {
22493         Op1 = UGTOp1;
22494         Cond = ISD::SETUGE;
22495       }
22496     }
22497     if (Cond == ISD::SETULT) {
22498       // X < C --> X <= (C-1) --> X == umin(X, C-1)
22499       if (SDValue ULTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false)) {
22500         Op1 = ULTOp1;
22501         Cond = ISD::SETULE;
22502       }
22503     }
22504     bool Invert = false;
22505     unsigned Opc;
22506     switch (Cond) {
22507     default: llvm_unreachable("Unexpected condition code");
22508     case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH;
22509     case ISD::SETULE: Opc = ISD::UMIN; break;
22510     case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH;
22511     case ISD::SETUGE: Opc = ISD::UMAX; break;
22512     }
22513 
22514     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
22515     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
22516 
22517     // If the logical-not of the result is required, perform that now.
22518     if (Invert)
22519       Result = DAG.getNOT(dl, Result, VT);
22520 
22521     return Result;
22522   }
22523 
22524   // Try to use SUBUS and PCMPEQ.
22525   if (SDValue V = LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
22526     return V;
22527 
22528   // We are handling one of the integer comparisons here. Since SSE only has
22529   // GT and EQ comparisons for integer, swapping operands and multiple
22530   // operations may be required for some comparisons.
22531   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
22532                                                             : X86ISD::PCMPGT;
22533   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
22534               Cond == ISD::SETGE || Cond == ISD::SETUGE;
22535   bool Invert = Cond == ISD::SETNE ||
22536                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
22537 
22538   if (Swap)
22539     std::swap(Op0, Op1);
22540 
22541   // Check that the operation in question is available (most are plain SSE2,
22542   // but PCMPGTQ and PCMPEQQ have different requirements).
22543   if (VT == MVT::v2i64) {
22544     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
22545       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
22546 
22547       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
22548       // the odd elements over the even elements.
22549       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
22550         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
22551         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
22552 
22553         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
22554         static const int MaskHi[] = { 1, 1, 3, 3 };
22555         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
22556 
22557         return DAG.getBitcast(VT, Result);
22558       }
22559 
22560       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
22561         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
22562         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
22563 
22564         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
22565         static const int MaskHi[] = { 1, 1, 3, 3 };
22566         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
22567 
22568         return DAG.getBitcast(VT, Result);
22569       }
22570 
22571       // Since SSE has no unsigned integer comparisons, we need to flip the sign
22572       // bits of the inputs before performing those operations. The lower
22573       // compare is always unsigned.
22574       SDValue SB;
22575       if (FlipSigns) {
22576         SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
22577       } else {
22578         SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
22579       }
22580       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
22581       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
22582 
22583       // Cast everything to the right type.
22584       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
22585       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
22586 
22587       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
22588       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
22589       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
22590 
22591       // Create masks for only the low parts/high parts of the 64 bit integers.
22592       static const int MaskHi[] = { 1, 1, 3, 3 };
22593       static const int MaskLo[] = { 0, 0, 2, 2 };
22594       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
22595       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
22596       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
22597 
22598       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
22599       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
22600 
22601       if (Invert)
22602         Result = DAG.getNOT(dl, Result, MVT::v4i32);
22603 
22604       return DAG.getBitcast(VT, Result);
22605     }
22606 
22607     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
22608       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
22609       // pcmpeqd + pshufd + pand.
22610       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
22611 
22612       // First cast everything to the right type.
22613       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
22614       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
22615 
22616       // Do the compare.
22617       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
22618 
22619       // Make sure the lower and upper halves are both all-ones.
22620       static const int Mask[] = { 1, 0, 3, 2 };
22621       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
22622       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
22623 
22624       if (Invert)
22625         Result = DAG.getNOT(dl, Result, MVT::v4i32);
22626 
22627       return DAG.getBitcast(VT, Result);
22628     }
22629   }
22630 
22631   // Since SSE has no unsigned integer comparisons, we need to flip the sign
22632   // bits of the inputs before performing those operations.
22633   if (FlipSigns) {
22634     MVT EltVT = VT.getVectorElementType();
22635     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
22636                                  VT);
22637     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
22638     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
22639   }
22640 
22641   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
22642 
22643   // If the logical-not of the result is required, perform that now.
22644   if (Invert)
22645     Result = DAG.getNOT(dl, Result, VT);
22646 
22647   return Result;
22648 }
22649 
22650 // 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)22651 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
22652                               const SDLoc &dl, SelectionDAG &DAG,
22653                               const X86Subtarget &Subtarget,
22654                               SDValue &X86CC) {
22655   // Only support equality comparisons.
22656   if (CC != ISD::SETEQ && CC != ISD::SETNE)
22657     return SDValue();
22658 
22659   // Must be a bitcast from vXi1.
22660   if (Op0.getOpcode() != ISD::BITCAST)
22661     return SDValue();
22662 
22663   Op0 = Op0.getOperand(0);
22664   MVT VT = Op0.getSimpleValueType();
22665   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
22666       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
22667       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
22668     return SDValue();
22669 
22670   X86::CondCode X86Cond;
22671   if (isNullConstant(Op1)) {
22672     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
22673   } else if (isAllOnesConstant(Op1)) {
22674     // C flag is set for all ones.
22675     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
22676   } else
22677     return SDValue();
22678 
22679   // If the input is an AND, we can combine it's operands into the KTEST.
22680   bool KTestable = false;
22681   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
22682     KTestable = true;
22683   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
22684     KTestable = true;
22685   if (!isNullConstant(Op1))
22686     KTestable = false;
22687   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
22688     SDValue LHS = Op0.getOperand(0);
22689     SDValue RHS = Op0.getOperand(1);
22690     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
22691     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
22692   }
22693 
22694   // If the input is an OR, we can combine it's operands into the KORTEST.
22695   SDValue LHS = Op0;
22696   SDValue RHS = Op0;
22697   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
22698     LHS = Op0.getOperand(0);
22699     RHS = Op0.getOperand(1);
22700   }
22701 
22702   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
22703   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
22704 }
22705 
22706 /// Emit flags for the given setcc condition and operands. Also returns the
22707 /// corresponding X86 condition code constant in X86CC.
emitFlagsForSetcc(SDValue Op0,SDValue Op1,ISD::CondCode CC,const SDLoc & dl,SelectionDAG & DAG,SDValue & X86CC) const22708 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
22709                                              ISD::CondCode CC, const SDLoc &dl,
22710                                              SelectionDAG &DAG,
22711                                              SDValue &X86CC) const {
22712   // Optimize to BT if possible.
22713   // Lower (X & (1 << N)) == 0 to BT(X, N).
22714   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
22715   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
22716   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
22717       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
22718     if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
22719       return BT;
22720   }
22721 
22722   // Try to use PTEST/PMOVMSKB for a tree ORs equality compared with 0.
22723   // TODO: We could do AND tree with all 1s as well by using the C flag.
22724   if (isNullConstant(Op1) && (CC == ISD::SETEQ || CC == ISD::SETNE))
22725     if (SDValue CmpZ =
22726             MatchVectorAllZeroTest(Op0, CC, dl, Subtarget, DAG, X86CC))
22727       return CmpZ;
22728 
22729   // Try to lower using KORTEST or KTEST.
22730   if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
22731     return Test;
22732 
22733   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
22734   // these.
22735   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
22736       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
22737     // If the input is a setcc, then reuse the input setcc or use a new one with
22738     // the inverted condition.
22739     if (Op0.getOpcode() == X86ISD::SETCC) {
22740       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
22741 
22742       X86CC = Op0.getOperand(0);
22743       if (Invert) {
22744         X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
22745         CCode = X86::GetOppositeBranchCondition(CCode);
22746         X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
22747       }
22748 
22749       return Op0.getOperand(1);
22750     }
22751   }
22752 
22753   // Try to use the carry flag from the add in place of an separate CMP for:
22754   // (seteq (add X, -1), -1). Similar for setne.
22755   if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
22756       Op0.getOperand(1) == Op1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
22757     if (isProfitableToUseFlagOp(Op0)) {
22758       SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
22759 
22760       SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
22761                                 Op0.getOperand(1));
22762       DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
22763       X86::CondCode CCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
22764       X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
22765       return SDValue(New.getNode(), 1);
22766     }
22767   }
22768 
22769   X86::CondCode CondCode =
22770       TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
22771   assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
22772 
22773   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
22774   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
22775   return EFLAGS;
22776 }
22777 
LowerSETCC(SDValue Op,SelectionDAG & DAG) const22778 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
22779 
22780   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
22781                   Op.getOpcode() == ISD::STRICT_FSETCCS;
22782   MVT VT = Op->getSimpleValueType(0);
22783 
22784   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
22785 
22786   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
22787   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
22788   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
22789   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
22790   SDLoc dl(Op);
22791   ISD::CondCode CC =
22792       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
22793 
22794   // Handle f128 first, since one possible outcome is a normal integer
22795   // comparison which gets handled by emitFlagsForSetcc.
22796   if (Op0.getValueType() == MVT::f128) {
22797     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
22798                         Op.getOpcode() == ISD::STRICT_FSETCCS);
22799 
22800     // If softenSetCCOperands returned a scalar, use it.
22801     if (!Op1.getNode()) {
22802       assert(Op0.getValueType() == Op.getValueType() &&
22803              "Unexpected setcc expansion!");
22804       if (IsStrict)
22805         return DAG.getMergeValues({Op0, Chain}, dl);
22806       return Op0;
22807     }
22808   }
22809 
22810   if (Op0.getSimpleValueType().isInteger()) {
22811     SDValue X86CC;
22812     SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
22813     SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
22814     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
22815   }
22816 
22817   // Handle floating point.
22818   X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
22819   if (CondCode == X86::COND_INVALID)
22820     return SDValue();
22821 
22822   SDValue EFLAGS;
22823   if (IsStrict) {
22824     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
22825     EFLAGS =
22826         DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
22827                     dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
22828     Chain = EFLAGS.getValue(1);
22829   } else {
22830     EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
22831   }
22832 
22833   SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
22834   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
22835   return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
22836 }
22837 
LowerSETCCCARRY(SDValue Op,SelectionDAG & DAG) const22838 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
22839   SDValue LHS = Op.getOperand(0);
22840   SDValue RHS = Op.getOperand(1);
22841   SDValue Carry = Op.getOperand(2);
22842   SDValue Cond = Op.getOperand(3);
22843   SDLoc DL(Op);
22844 
22845   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
22846   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
22847 
22848   // Recreate the carry if needed.
22849   EVT CarryVT = Carry.getValueType();
22850   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
22851                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
22852 
22853   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
22854   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
22855   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
22856 }
22857 
22858 // This function returns three things: the arithmetic computation itself
22859 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
22860 // flag and the condition code define the case in which the arithmetic
22861 // computation overflows.
22862 static std::pair<SDValue, SDValue>
getX86XALUOOp(X86::CondCode & Cond,SDValue Op,SelectionDAG & DAG)22863 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
22864   assert(Op.getResNo() == 0 && "Unexpected result number!");
22865   SDValue Value, Overflow;
22866   SDValue LHS = Op.getOperand(0);
22867   SDValue RHS = Op.getOperand(1);
22868   unsigned BaseOp = 0;
22869   SDLoc DL(Op);
22870   switch (Op.getOpcode()) {
22871   default: llvm_unreachable("Unknown ovf instruction!");
22872   case ISD::SADDO:
22873     BaseOp = X86ISD::ADD;
22874     Cond = X86::COND_O;
22875     break;
22876   case ISD::UADDO:
22877     BaseOp = X86ISD::ADD;
22878     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
22879     break;
22880   case ISD::SSUBO:
22881     BaseOp = X86ISD::SUB;
22882     Cond = X86::COND_O;
22883     break;
22884   case ISD::USUBO:
22885     BaseOp = X86ISD::SUB;
22886     Cond = X86::COND_B;
22887     break;
22888   case ISD::SMULO:
22889     BaseOp = X86ISD::SMUL;
22890     Cond = X86::COND_O;
22891     break;
22892   case ISD::UMULO:
22893     BaseOp = X86ISD::UMUL;
22894     Cond = X86::COND_O;
22895     break;
22896   }
22897 
22898   if (BaseOp) {
22899     // Also sets EFLAGS.
22900     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22901     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
22902     Overflow = Value.getValue(1);
22903   }
22904 
22905   return std::make_pair(Value, Overflow);
22906 }
22907 
LowerXALUO(SDValue Op,SelectionDAG & DAG)22908 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
22909   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
22910   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
22911   // looks for this combo and may remove the "setcc" instruction if the "setcc"
22912   // has only one use.
22913   SDLoc DL(Op);
22914   X86::CondCode Cond;
22915   SDValue Value, Overflow;
22916   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
22917 
22918   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
22919   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
22920   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
22921 }
22922 
22923 /// Return true if opcode is a X86 logical comparison.
isX86LogicalCmp(SDValue Op)22924 static bool isX86LogicalCmp(SDValue Op) {
22925   unsigned Opc = Op.getOpcode();
22926   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
22927       Opc == X86ISD::FCMP)
22928     return true;
22929   if (Op.getResNo() == 1 &&
22930       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
22931        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
22932        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
22933     return true;
22934 
22935   return false;
22936 }
22937 
isTruncWithZeroHighBitsInput(SDValue V,SelectionDAG & DAG)22938 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
22939   if (V.getOpcode() != ISD::TRUNCATE)
22940     return false;
22941 
22942   SDValue VOp0 = V.getOperand(0);
22943   unsigned InBits = VOp0.getValueSizeInBits();
22944   unsigned Bits = V.getValueSizeInBits();
22945   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
22946 }
22947 
LowerSELECT(SDValue Op,SelectionDAG & DAG) const22948 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
22949   bool AddTest = true;
22950   SDValue Cond  = Op.getOperand(0);
22951   SDValue Op1 = Op.getOperand(1);
22952   SDValue Op2 = Op.getOperand(2);
22953   SDLoc DL(Op);
22954   MVT VT = Op1.getSimpleValueType();
22955   SDValue CC;
22956 
22957   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
22958   // are available or VBLENDV if AVX is available.
22959   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
22960   if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
22961       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
22962     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
22963     bool IsAlwaysSignaling;
22964     unsigned SSECC =
22965         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
22966                            CondOp0, CondOp1, IsAlwaysSignaling);
22967 
22968     if (Subtarget.hasAVX512()) {
22969       SDValue Cmp =
22970           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
22971                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
22972       assert(!VT.isVector() && "Not a scalar type?");
22973       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
22974     }
22975 
22976     if (SSECC < 8 || Subtarget.hasAVX()) {
22977       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
22978                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
22979 
22980       // If we have AVX, we can use a variable vector select (VBLENDV) instead
22981       // of 3 logic instructions for size savings and potentially speed.
22982       // Unfortunately, there is no scalar form of VBLENDV.
22983 
22984       // If either operand is a +0.0 constant, don't try this. We can expect to
22985       // optimize away at least one of the logic instructions later in that
22986       // case, so that sequence would be faster than a variable blend.
22987 
22988       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
22989       // uses XMM0 as the selection register. That may need just as many
22990       // instructions as the AND/ANDN/OR sequence due to register moves, so
22991       // don't bother.
22992       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
22993           !isNullFPConstant(Op2)) {
22994         // Convert to vectors, do a VSELECT, and convert back to scalar.
22995         // All of the conversions should be optimized away.
22996         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
22997         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
22998         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
22999         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
23000 
23001         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
23002         VCmp = DAG.getBitcast(VCmpVT, VCmp);
23003 
23004         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
23005 
23006         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
23007                            VSel, DAG.getIntPtrConstant(0, DL));
23008       }
23009       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
23010       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
23011       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
23012     }
23013   }
23014 
23015   // AVX512 fallback is to lower selects of scalar floats to masked moves.
23016   if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
23017     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
23018     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23019   }
23020 
23021   if (Cond.getOpcode() == ISD::SETCC) {
23022     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
23023       Cond = NewCond;
23024       // If the condition was updated, it's possible that the operands of the
23025       // select were also updated (for example, EmitTest has a RAUW). Refresh
23026       // the local references to the select operands in case they got stale.
23027       Op1 = Op.getOperand(1);
23028       Op2 = Op.getOperand(2);
23029     }
23030   }
23031 
23032   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
23033   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
23034   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
23035   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
23036   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
23037   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
23038   if (Cond.getOpcode() == X86ISD::SETCC &&
23039       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
23040       isNullConstant(Cond.getOperand(1).getOperand(1))) {
23041     SDValue Cmp = Cond.getOperand(1);
23042     SDValue CmpOp0 = Cmp.getOperand(0);
23043     unsigned CondCode = Cond.getConstantOperandVal(0);
23044 
23045     // Special handling for __builtin_ffs(X) - 1 pattern which looks like
23046     // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
23047     // handle to keep the CMP with 0. This should be removed by
23048     // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
23049     // cttz_zero_undef.
23050     auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
23051       return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
23052               Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
23053     };
23054     if (Subtarget.hasCMov() && (VT == MVT::i32 || VT == MVT::i64) &&
23055         ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
23056          (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
23057       // Keep Cmp.
23058     } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
23059         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
23060       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
23061 
23062       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23063       SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
23064 
23065       // Apply further optimizations for special cases
23066       // (select (x != 0), -1, 0) -> neg & sbb
23067       // (select (x == 0), 0, -1) -> neg & sbb
23068       if (isNullConstant(Y) &&
23069           (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
23070         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
23071         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
23072         Zero = DAG.getConstant(0, DL, Op.getValueType());
23073         return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Neg.getValue(1));
23074       }
23075 
23076       Cmp = DAG.getNode(X86ISD::SUB, DL, CmpVTs,
23077                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
23078 
23079       SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
23080       SDValue Res =   // Res = 0 or -1.
23081         DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp.getValue(1));
23082 
23083       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
23084         Res = DAG.getNOT(DL, Res, Res.getValueType());
23085 
23086       return DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
23087     } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
23088                Cmp.getOperand(0).getOpcode() == ISD::AND &&
23089                isOneConstant(Cmp.getOperand(0).getOperand(1))) {
23090       SDValue Src1, Src2;
23091       // true if Op2 is XOR or OR operator and one of its operands
23092       // is equal to Op1
23093       // ( a , a op b) || ( b , a op b)
23094       auto isOrXorPattern = [&]() {
23095         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
23096             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
23097           Src1 =
23098               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
23099           Src2 = Op1;
23100           return true;
23101         }
23102         return false;
23103       };
23104 
23105       if (isOrXorPattern()) {
23106         SDValue Neg;
23107         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
23108         // we need mask of all zeros or ones with same size of the other
23109         // operands.
23110         if (CmpSz > VT.getSizeInBits())
23111           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
23112         else if (CmpSz < VT.getSizeInBits())
23113           Neg = DAG.getNode(ISD::AND, DL, VT,
23114               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
23115               DAG.getConstant(1, DL, VT));
23116         else
23117           Neg = CmpOp0;
23118         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
23119                                    Neg); // -(and (x, 0x1))
23120         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
23121         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
23122       }
23123     }
23124   }
23125 
23126   // Look past (and (setcc_carry (cmp ...)), 1).
23127   if (Cond.getOpcode() == ISD::AND &&
23128       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
23129       isOneConstant(Cond.getOperand(1)))
23130     Cond = Cond.getOperand(0);
23131 
23132   // If condition flag is set by a X86ISD::CMP, then use it as the condition
23133   // setting operand in place of the X86ISD::SETCC.
23134   unsigned CondOpcode = Cond.getOpcode();
23135   if (CondOpcode == X86ISD::SETCC ||
23136       CondOpcode == X86ISD::SETCC_CARRY) {
23137     CC = Cond.getOperand(0);
23138 
23139     SDValue Cmp = Cond.getOperand(1);
23140     bool IllegalFPCMov = false;
23141     if (VT.isFloatingPoint() && !VT.isVector() &&
23142         !isScalarFPTypeInSSEReg(VT) && Subtarget.hasCMov())  // FPStack?
23143       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
23144 
23145     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
23146         Cmp.getOpcode() == X86ISD::BT) { // FIXME
23147       Cond = Cmp;
23148       AddTest = false;
23149     }
23150   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
23151              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
23152              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
23153     SDValue Value;
23154     X86::CondCode X86Cond;
23155     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
23156 
23157     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
23158     AddTest = false;
23159   }
23160 
23161   if (AddTest) {
23162     // Look past the truncate if the high bits are known zero.
23163     if (isTruncWithZeroHighBitsInput(Cond, DAG))
23164       Cond = Cond.getOperand(0);
23165 
23166     // We know the result of AND is compared against zero. Try to match
23167     // it to BT.
23168     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
23169       SDValue BTCC;
23170       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
23171         CC = BTCC;
23172         Cond = BT;
23173         AddTest = false;
23174       }
23175     }
23176   }
23177 
23178   if (AddTest) {
23179     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
23180     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
23181   }
23182 
23183   // a <  b ? -1 :  0 -> RES = ~setcc_carry
23184   // a <  b ?  0 : -1 -> RES = setcc_carry
23185   // a >= b ? -1 :  0 -> RES = setcc_carry
23186   // a >= b ?  0 : -1 -> RES = ~setcc_carry
23187   if (Cond.getOpcode() == X86ISD::SUB) {
23188     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
23189 
23190     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
23191         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
23192         (isNullConstant(Op1) || isNullConstant(Op2))) {
23193       SDValue Res =
23194           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
23195                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
23196       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
23197         return DAG.getNOT(DL, Res, Res.getValueType());
23198       return Res;
23199     }
23200   }
23201 
23202   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
23203   // widen the cmov and push the truncate through. This avoids introducing a new
23204   // branch during isel and doesn't add any extensions.
23205   if (Op.getValueType() == MVT::i8 &&
23206       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
23207     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
23208     if (T1.getValueType() == T2.getValueType() &&
23209         // Exclude CopyFromReg to avoid partial register stalls.
23210         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
23211       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
23212                                  CC, Cond);
23213       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
23214     }
23215   }
23216 
23217   // Or finally, promote i8 cmovs if we have CMOV,
23218   //                 or i16 cmovs if it won't prevent folding a load.
23219   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
23220   //        legal, but EmitLoweredSelect() can not deal with these extensions
23221   //        being inserted between two CMOV's. (in i16 case too TBN)
23222   //        https://bugs.llvm.org/show_bug.cgi?id=40974
23223   if ((Op.getValueType() == MVT::i8 && Subtarget.hasCMov()) ||
23224       (Op.getValueType() == MVT::i16 && !MayFoldLoad(Op1) &&
23225        !MayFoldLoad(Op2))) {
23226     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
23227     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
23228     SDValue Ops[] = { Op2, Op1, CC, Cond };
23229     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
23230     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
23231   }
23232 
23233   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
23234   // condition is true.
23235   SDValue Ops[] = { Op2, Op1, CC, Cond };
23236   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
23237 }
23238 
LowerSIGN_EXTEND_Mask(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23239 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
23240                                      const X86Subtarget &Subtarget,
23241                                      SelectionDAG &DAG) {
23242   MVT VT = Op->getSimpleValueType(0);
23243   SDValue In = Op->getOperand(0);
23244   MVT InVT = In.getSimpleValueType();
23245   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
23246   MVT VTElt = VT.getVectorElementType();
23247   SDLoc dl(Op);
23248 
23249   unsigned NumElts = VT.getVectorNumElements();
23250 
23251   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
23252   MVT ExtVT = VT;
23253   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
23254     // If v16i32 is to be avoided, we'll need to split and concatenate.
23255     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
23256       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
23257 
23258     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
23259   }
23260 
23261   // Widen to 512-bits if VLX is not supported.
23262   MVT WideVT = ExtVT;
23263   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
23264     NumElts *= 512 / ExtVT.getSizeInBits();
23265     InVT = MVT::getVectorVT(MVT::i1, NumElts);
23266     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
23267                      In, DAG.getIntPtrConstant(0, dl));
23268     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
23269   }
23270 
23271   SDValue V;
23272   MVT WideEltVT = WideVT.getVectorElementType();
23273   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
23274       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
23275     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
23276   } else {
23277     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
23278     SDValue Zero = DAG.getConstant(0, dl, WideVT);
23279     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
23280   }
23281 
23282   // Truncate if we had to extend i16/i8 above.
23283   if (VT != ExtVT) {
23284     WideVT = MVT::getVectorVT(VTElt, NumElts);
23285     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
23286   }
23287 
23288   // Extract back to 128/256-bit if we widened.
23289   if (WideVT != VT)
23290     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
23291                     DAG.getIntPtrConstant(0, dl));
23292 
23293   return V;
23294 }
23295 
LowerANY_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23296 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
23297                                SelectionDAG &DAG) {
23298   SDValue In = Op->getOperand(0);
23299   MVT InVT = In.getSimpleValueType();
23300 
23301   if (InVT.getVectorElementType() == MVT::i1)
23302     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
23303 
23304   assert(Subtarget.hasAVX() && "Expected AVX support");
23305   return LowerAVXExtend(Op, DAG, Subtarget);
23306 }
23307 
23308 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
23309 // For sign extend this needs to handle all vector sizes and SSE4.1 and
23310 // non-SSE4.1 targets. For zero extend this should only handle inputs of
23311 // MVT::v64i8 when BWI is not supported, but AVX512 is.
LowerEXTEND_VECTOR_INREG(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23312 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
23313                                         const X86Subtarget &Subtarget,
23314                                         SelectionDAG &DAG) {
23315   SDValue In = Op->getOperand(0);
23316   MVT VT = Op->getSimpleValueType(0);
23317   MVT InVT = In.getSimpleValueType();
23318 
23319   MVT SVT = VT.getVectorElementType();
23320   MVT InSVT = InVT.getVectorElementType();
23321   assert(SVT.getSizeInBits() > InSVT.getSizeInBits());
23322 
23323   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
23324     return SDValue();
23325   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
23326     return SDValue();
23327   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
23328       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
23329       !(VT.is512BitVector() && Subtarget.hasAVX512()))
23330     return SDValue();
23331 
23332   SDLoc dl(Op);
23333   unsigned Opc = Op.getOpcode();
23334   unsigned NumElts = VT.getVectorNumElements();
23335 
23336   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
23337   // For 512-bit vectors, we need 128-bits or 256-bits.
23338   if (InVT.getSizeInBits() > 128) {
23339     // Input needs to be at least the same number of elements as output, and
23340     // at least 128-bits.
23341     int InSize = InSVT.getSizeInBits() * NumElts;
23342     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
23343     InVT = In.getSimpleValueType();
23344   }
23345 
23346   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
23347   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
23348   // need to be handled here for 256/512-bit results.
23349   if (Subtarget.hasInt256()) {
23350     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
23351 
23352     if (InVT.getVectorNumElements() != NumElts)
23353       return DAG.getNode(Op.getOpcode(), dl, VT, In);
23354 
23355     // FIXME: Apparently we create inreg operations that could be regular
23356     // extends.
23357     unsigned ExtOpc =
23358         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
23359                                              : ISD::ZERO_EXTEND;
23360     return DAG.getNode(ExtOpc, dl, VT, In);
23361   }
23362 
23363   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
23364   if (Subtarget.hasAVX()) {
23365     assert(VT.is256BitVector() && "256-bit vector expected");
23366     MVT HalfVT = VT.getHalfNumVectorElementsVT();
23367     int HalfNumElts = HalfVT.getVectorNumElements();
23368 
23369     unsigned NumSrcElts = InVT.getVectorNumElements();
23370     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
23371     for (int i = 0; i != HalfNumElts; ++i)
23372       HiMask[i] = HalfNumElts + i;
23373 
23374     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
23375     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
23376     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
23377     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
23378   }
23379 
23380   // We should only get here for sign extend.
23381   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
23382   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
23383 
23384   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
23385   SDValue Curr = In;
23386   SDValue SignExt = Curr;
23387 
23388   // As SRAI is only available on i16/i32 types, we expand only up to i32
23389   // and handle i64 separately.
23390   if (InVT != MVT::v4i32) {
23391     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
23392 
23393     unsigned DestWidth = DestVT.getScalarSizeInBits();
23394     unsigned Scale = DestWidth / InSVT.getSizeInBits();
23395 
23396     unsigned InNumElts = InVT.getVectorNumElements();
23397     unsigned DestElts = DestVT.getVectorNumElements();
23398 
23399     // Build a shuffle mask that takes each input element and places it in the
23400     // MSBs of the new element size.
23401     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
23402     for (unsigned i = 0; i != DestElts; ++i)
23403       Mask[i * Scale + (Scale - 1)] = i;
23404 
23405     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
23406     Curr = DAG.getBitcast(DestVT, Curr);
23407 
23408     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
23409     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
23410                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
23411   }
23412 
23413   if (VT == MVT::v2i64) {
23414     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
23415     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
23416     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
23417     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
23418     SignExt = DAG.getBitcast(VT, SignExt);
23419   }
23420 
23421   return SignExt;
23422 }
23423 
LowerSIGN_EXTEND(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23424 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
23425                                 SelectionDAG &DAG) {
23426   MVT VT = Op->getSimpleValueType(0);
23427   SDValue In = Op->getOperand(0);
23428   MVT InVT = In.getSimpleValueType();
23429   SDLoc dl(Op);
23430 
23431   if (InVT.getVectorElementType() == MVT::i1)
23432     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
23433 
23434   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
23435   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
23436          "Expected same number of elements");
23437   assert((VT.getVectorElementType() == MVT::i16 ||
23438           VT.getVectorElementType() == MVT::i32 ||
23439           VT.getVectorElementType() == MVT::i64) &&
23440          "Unexpected element type");
23441   assert((InVT.getVectorElementType() == MVT::i8 ||
23442           InVT.getVectorElementType() == MVT::i16 ||
23443           InVT.getVectorElementType() == MVT::i32) &&
23444          "Unexpected element type");
23445 
23446   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
23447     assert(InVT == MVT::v32i8 && "Unexpected VT!");
23448     return splitVectorIntUnary(Op, DAG);
23449   }
23450 
23451   if (Subtarget.hasInt256())
23452     return Op;
23453 
23454   // Optimize vectors in AVX mode
23455   // Sign extend  v8i16 to v8i32 and
23456   //              v4i32 to v4i64
23457   //
23458   // Divide input vector into two parts
23459   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
23460   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
23461   // concat the vectors to original VT
23462   MVT HalfVT = VT.getHalfNumVectorElementsVT();
23463   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
23464 
23465   unsigned NumElems = InVT.getVectorNumElements();
23466   SmallVector<int,8> ShufMask(NumElems, -1);
23467   for (unsigned i = 0; i != NumElems/2; ++i)
23468     ShufMask[i] = i + NumElems/2;
23469 
23470   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
23471   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
23472 
23473   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
23474 }
23475 
23476 /// Change a vector store into a pair of half-size vector stores.
splitVectorStore(StoreSDNode * Store,SelectionDAG & DAG)23477 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
23478   SDValue StoredVal = Store->getValue();
23479   assert((StoredVal.getValueType().is256BitVector() ||
23480           StoredVal.getValueType().is512BitVector()) &&
23481          "Expecting 256/512-bit op");
23482 
23483   // Splitting volatile memory ops is not allowed unless the operation was not
23484   // legal to begin with. Assume the input store is legal (this transform is
23485   // only used for targets with AVX). Note: It is possible that we have an
23486   // illegal type like v2i128, and so we could allow splitting a volatile store
23487   // in that case if that is important.
23488   if (!Store->isSimple())
23489     return SDValue();
23490 
23491   SDLoc DL(Store);
23492   SDValue Value0, Value1;
23493   std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
23494   unsigned HalfOffset = Value0.getValueType().getStoreSize();
23495   SDValue Ptr0 = Store->getBasePtr();
23496   SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, HalfOffset, DL);
23497   SDValue Ch0 =
23498       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
23499                    Store->getOriginalAlign(),
23500                    Store->getMemOperand()->getFlags());
23501   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
23502                              Store->getPointerInfo().getWithOffset(HalfOffset),
23503                              Store->getOriginalAlign(),
23504                              Store->getMemOperand()->getFlags());
23505   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
23506 }
23507 
23508 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
23509 /// type.
scalarizeVectorStore(StoreSDNode * Store,MVT StoreVT,SelectionDAG & DAG)23510 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
23511                                     SelectionDAG &DAG) {
23512   SDValue StoredVal = Store->getValue();
23513   assert(StoreVT.is128BitVector() &&
23514          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
23515   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
23516 
23517   // Splitting volatile memory ops is not allowed unless the operation was not
23518   // legal to begin with. We are assuming the input op is legal (this transform
23519   // is only used for targets with AVX).
23520   if (!Store->isSimple())
23521     return SDValue();
23522 
23523   MVT StoreSVT = StoreVT.getScalarType();
23524   unsigned NumElems = StoreVT.getVectorNumElements();
23525   unsigned ScalarSize = StoreSVT.getStoreSize();
23526 
23527   SDLoc DL(Store);
23528   SmallVector<SDValue, 4> Stores;
23529   for (unsigned i = 0; i != NumElems; ++i) {
23530     unsigned Offset = i * ScalarSize;
23531     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(), Offset, DL);
23532     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
23533                               DAG.getIntPtrConstant(i, DL));
23534     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
23535                               Store->getPointerInfo().getWithOffset(Offset),
23536                               Store->getOriginalAlign(),
23537                               Store->getMemOperand()->getFlags());
23538     Stores.push_back(Ch);
23539   }
23540   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
23541 }
23542 
LowerStore(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23543 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
23544                           SelectionDAG &DAG) {
23545   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
23546   SDLoc dl(St);
23547   SDValue StoredVal = St->getValue();
23548 
23549   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
23550   if (StoredVal.getValueType().isVector() &&
23551       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
23552     assert(StoredVal.getValueType().getVectorNumElements() <= 8 &&
23553            "Unexpected VT");
23554     assert(!St->isTruncatingStore() && "Expected non-truncating store");
23555     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
23556            "Expected AVX512F without AVX512DQI");
23557 
23558     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
23559                             DAG.getUNDEF(MVT::v16i1), StoredVal,
23560                             DAG.getIntPtrConstant(0, dl));
23561     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
23562     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
23563 
23564     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
23565                         St->getPointerInfo(), St->getOriginalAlign(),
23566                         St->getMemOperand()->getFlags());
23567   }
23568 
23569   if (St->isTruncatingStore())
23570     return SDValue();
23571 
23572   // If this is a 256-bit store of concatenated ops, we are better off splitting
23573   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
23574   // and each half can execute independently. Some cores would split the op into
23575   // halves anyway, so the concat (vinsertf128) is purely an extra op.
23576   MVT StoreVT = StoredVal.getSimpleValueType();
23577   if (StoreVT.is256BitVector() ||
23578       ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
23579        !Subtarget.hasBWI())) {
23580     SmallVector<SDValue, 4> CatOps;
23581     if (StoredVal.hasOneUse() && collectConcatOps(StoredVal.getNode(), CatOps))
23582       return splitVectorStore(St, DAG);
23583     return SDValue();
23584   }
23585 
23586   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23587   assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&
23588          "Unexpected VT");
23589   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
23590              TargetLowering::TypeWidenVector && "Unexpected type action!");
23591 
23592   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
23593   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
23594                           DAG.getUNDEF(StoreVT));
23595 
23596   if (Subtarget.hasSSE2()) {
23597     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
23598     // and store it.
23599     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
23600     MVT CastVT = MVT::getVectorVT(StVT, 2);
23601     StoredVal = DAG.getBitcast(CastVT, StoredVal);
23602     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
23603                             DAG.getIntPtrConstant(0, dl));
23604 
23605     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
23606                         St->getPointerInfo(), St->getOriginalAlign(),
23607                         St->getMemOperand()->getFlags());
23608   }
23609   assert(Subtarget.hasSSE1() && "Expected SSE");
23610   SDVTList Tys = DAG.getVTList(MVT::Other);
23611   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
23612   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
23613                                  St->getMemOperand());
23614 }
23615 
23616 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
23617 // may emit an illegal shuffle but the expansion is still better than scalar
23618 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
23619 // we'll emit a shuffle and a arithmetic shift.
23620 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
23621 // TODO: It is possible to support ZExt by zeroing the undef values during
23622 // the shuffle phase or after the shuffle.
LowerLoad(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23623 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
23624                                  SelectionDAG &DAG) {
23625   MVT RegVT = Op.getSimpleValueType();
23626   assert(RegVT.isVector() && "We only custom lower vector loads.");
23627   assert(RegVT.isInteger() &&
23628          "We only custom lower integer vector loads.");
23629 
23630   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
23631   SDLoc dl(Ld);
23632 
23633   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
23634   if (RegVT.getVectorElementType() == MVT::i1) {
23635     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
23636     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
23637     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
23638            "Expected AVX512F without AVX512DQI");
23639 
23640     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
23641                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
23642                                 Ld->getMemOperand()->getFlags());
23643 
23644     // Replace chain users with the new chain.
23645     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
23646 
23647     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
23648     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
23649                       DAG.getBitcast(MVT::v16i1, Val),
23650                       DAG.getIntPtrConstant(0, dl));
23651     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
23652   }
23653 
23654   return SDValue();
23655 }
23656 
23657 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
23658 /// each of which has no other use apart from the AND / OR.
isAndOrOfSetCCs(SDValue Op,unsigned & Opc)23659 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
23660   Opc = Op.getOpcode();
23661   if (Opc != ISD::OR && Opc != ISD::AND)
23662     return false;
23663   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
23664           Op.getOperand(0).hasOneUse() &&
23665           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
23666           Op.getOperand(1).hasOneUse());
23667 }
23668 
LowerBRCOND(SDValue Op,SelectionDAG & DAG) const23669 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
23670   SDValue Chain = Op.getOperand(0);
23671   SDValue Cond  = Op.getOperand(1);
23672   SDValue Dest  = Op.getOperand(2);
23673   SDLoc dl(Op);
23674 
23675   if (Cond.getOpcode() == ISD::SETCC &&
23676       Cond.getOperand(0).getValueType() != MVT::f128) {
23677     SDValue LHS = Cond.getOperand(0);
23678     SDValue RHS = Cond.getOperand(1);
23679     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23680 
23681     // Special case for
23682     // setcc([su]{add,sub,mul}o == 0)
23683     // setcc([su]{add,sub,mul}o != 1)
23684     if (ISD::isOverflowIntrOpRes(LHS) &&
23685         (CC == ISD::SETEQ || CC == ISD::SETNE) &&
23686         (isNullConstant(RHS) || isOneConstant(RHS))) {
23687       SDValue Value, Overflow;
23688       X86::CondCode X86Cond;
23689       std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
23690 
23691       if ((CC == ISD::SETEQ) == isNullConstant(RHS))
23692         X86Cond = X86::GetOppositeBranchCondition(X86Cond);
23693 
23694       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23695       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23696                          Overflow);
23697     }
23698 
23699     if (LHS.getSimpleValueType().isInteger()) {
23700       SDValue CCVal;
23701       SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
23702       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23703                          EFLAGS);
23704     }
23705 
23706     if (CC == ISD::SETOEQ) {
23707       // For FCMP_OEQ, we can emit
23708       // two branches instead of an explicit AND instruction with a
23709       // separate test. However, we only do this if this block doesn't
23710       // have a fall-through edge, because this requires an explicit
23711       // jmp when the condition is false.
23712       if (Op.getNode()->hasOneUse()) {
23713         SDNode *User = *Op.getNode()->use_begin();
23714         // Look for an unconditional branch following this conditional branch.
23715         // We need this because we need to reverse the successors in order
23716         // to implement FCMP_OEQ.
23717         if (User->getOpcode() == ISD::BR) {
23718           SDValue FalseBB = User->getOperand(1);
23719           SDNode *NewBR =
23720             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
23721           assert(NewBR == User);
23722           (void)NewBR;
23723           Dest = FalseBB;
23724 
23725           SDValue Cmp =
23726               DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
23727           SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
23728           Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
23729                               CCVal, Cmp);
23730           CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
23731           return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23732                              Cmp);
23733         }
23734       }
23735     } else if (CC == ISD::SETUNE) {
23736       // For FCMP_UNE, we can emit
23737       // two branches instead of an explicit OR instruction with a
23738       // separate test.
23739       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
23740       SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
23741       Chain =
23742           DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
23743       CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
23744       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23745                          Cmp);
23746     } else {
23747       X86::CondCode X86Cond =
23748           TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
23749       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
23750       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23751       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23752                          Cmp);
23753     }
23754   }
23755 
23756   if (ISD::isOverflowIntrOpRes(Cond)) {
23757     SDValue Value, Overflow;
23758     X86::CondCode X86Cond;
23759     std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
23760 
23761     SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23762     return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23763                        Overflow);
23764   }
23765 
23766   // Look past the truncate if the high bits are known zero.
23767   if (isTruncWithZeroHighBitsInput(Cond, DAG))
23768     Cond = Cond.getOperand(0);
23769 
23770   EVT CondVT = Cond.getValueType();
23771 
23772   // Add an AND with 1 if we don't already have one.
23773   if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
23774     Cond =
23775         DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
23776 
23777   SDValue LHS = Cond;
23778   SDValue RHS = DAG.getConstant(0, dl, CondVT);
23779 
23780   SDValue CCVal;
23781   SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
23782   return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
23783                      EFLAGS);
23784 }
23785 
23786 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
23787 // Calls to _alloca are needed to probe the stack when allocating more than 4k
23788 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
23789 // that the guard pages used by the OS virtual memory manager are allocated in
23790 // correct sequence.
23791 SDValue
LowerDYNAMIC_STACKALLOC(SDValue Op,SelectionDAG & DAG) const23792 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
23793                                            SelectionDAG &DAG) const {
23794   MachineFunction &MF = DAG.getMachineFunction();
23795   bool SplitStack = MF.shouldSplitStack();
23796   bool EmitStackProbeCall = hasStackProbeSymbol(MF);
23797   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
23798                SplitStack || EmitStackProbeCall;
23799   SDLoc dl(Op);
23800 
23801   // Get the inputs.
23802   SDNode *Node = Op.getNode();
23803   SDValue Chain = Op.getOperand(0);
23804   SDValue Size  = Op.getOperand(1);
23805   MaybeAlign Alignment(Op.getConstantOperandVal(2));
23806   EVT VT = Node->getValueType(0);
23807 
23808   // Chain the dynamic stack allocation so that it doesn't modify the stack
23809   // pointer when other instructions are using the stack.
23810   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
23811 
23812   bool Is64Bit = Subtarget.is64Bit();
23813   MVT SPTy = getPointerTy(DAG.getDataLayout());
23814 
23815   SDValue Result;
23816   if (!Lower) {
23817     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23818     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
23819     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
23820                     " not tell us which reg is the stack pointer!");
23821 
23822     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
23823     const Align StackAlign = TFI.getStackAlign();
23824     if (hasInlineStackProbe(MF)) {
23825       MachineRegisterInfo &MRI = MF.getRegInfo();
23826 
23827       const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
23828       Register Vreg = MRI.createVirtualRegister(AddrRegClass);
23829       Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
23830       Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
23831                            DAG.getRegister(Vreg, SPTy));
23832     } else {
23833       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
23834       Chain = SP.getValue(1);
23835       Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
23836     }
23837     if (Alignment && *Alignment > StackAlign)
23838       Result =
23839           DAG.getNode(ISD::AND, dl, VT, Result,
23840                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
23841     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
23842   } else if (SplitStack) {
23843     MachineRegisterInfo &MRI = MF.getRegInfo();
23844 
23845     if (Is64Bit) {
23846       // The 64 bit implementation of segmented stacks needs to clobber both r10
23847       // r11. This makes it impossible to use it along with nested parameters.
23848       const Function &F = MF.getFunction();
23849       for (const auto &A : F.args()) {
23850         if (A.hasNestAttr())
23851           report_fatal_error("Cannot use segmented stacks with functions that "
23852                              "have nested arguments.");
23853       }
23854     }
23855 
23856     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
23857     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
23858     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
23859     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
23860                                 DAG.getRegister(Vreg, SPTy));
23861   } else {
23862     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
23863     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
23864     MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
23865 
23866     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23867     Register SPReg = RegInfo->getStackRegister();
23868     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
23869     Chain = SP.getValue(1);
23870 
23871     if (Alignment) {
23872       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
23873                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
23874       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
23875     }
23876 
23877     Result = SP;
23878   }
23879 
23880   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
23881                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
23882 
23883   SDValue Ops[2] = {Result, Chain};
23884   return DAG.getMergeValues(Ops, dl);
23885 }
23886 
LowerVASTART(SDValue Op,SelectionDAG & DAG) const23887 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
23888   MachineFunction &MF = DAG.getMachineFunction();
23889   auto PtrVT = getPointerTy(MF.getDataLayout());
23890   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
23891 
23892   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
23893   SDLoc DL(Op);
23894 
23895   if (!Subtarget.is64Bit() ||
23896       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
23897     // vastart just stores the address of the VarArgsFrameIndex slot into the
23898     // memory location argument.
23899     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
23900     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
23901                         MachinePointerInfo(SV));
23902   }
23903 
23904   // __va_list_tag:
23905   //   gp_offset         (0 - 6 * 8)
23906   //   fp_offset         (48 - 48 + 8 * 16)
23907   //   overflow_arg_area (point to parameters coming in memory).
23908   //   reg_save_area
23909   SmallVector<SDValue, 8> MemOps;
23910   SDValue FIN = Op.getOperand(1);
23911   // Store gp_offset
23912   SDValue Store = DAG.getStore(
23913       Op.getOperand(0), DL,
23914       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
23915       MachinePointerInfo(SV));
23916   MemOps.push_back(Store);
23917 
23918   // Store fp_offset
23919   FIN = DAG.getMemBasePlusOffset(FIN, 4, DL);
23920   Store = DAG.getStore(
23921       Op.getOperand(0), DL,
23922       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
23923       MachinePointerInfo(SV, 4));
23924   MemOps.push_back(Store);
23925 
23926   // Store ptr to overflow_arg_area
23927   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
23928   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
23929   Store =
23930       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
23931   MemOps.push_back(Store);
23932 
23933   // Store ptr to reg_save_area.
23934   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
23935       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
23936   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
23937   Store = DAG.getStore(
23938       Op.getOperand(0), DL, RSFIN, FIN,
23939       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
23940   MemOps.push_back(Store);
23941   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
23942 }
23943 
LowerVAARG(SDValue Op,SelectionDAG & DAG) const23944 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
23945   assert(Subtarget.is64Bit() &&
23946          "LowerVAARG only handles 64-bit va_arg!");
23947   assert(Op.getNumOperands() == 4);
23948 
23949   MachineFunction &MF = DAG.getMachineFunction();
23950   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
23951     // The Win64 ABI uses char* instead of a structure.
23952     return DAG.expandVAArg(Op.getNode());
23953 
23954   SDValue Chain = Op.getOperand(0);
23955   SDValue SrcPtr = Op.getOperand(1);
23956   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
23957   unsigned Align = Op.getConstantOperandVal(3);
23958   SDLoc dl(Op);
23959 
23960   EVT ArgVT = Op.getNode()->getValueType(0);
23961   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
23962   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
23963   uint8_t ArgMode;
23964 
23965   // Decide which area this value should be read from.
23966   // TODO: Implement the AMD64 ABI in its entirety. This simple
23967   // selection mechanism works only for the basic types.
23968   assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
23969   if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
23970     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
23971   } else {
23972     assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
23973            "Unhandled argument type in LowerVAARG");
23974     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
23975   }
23976 
23977   if (ArgMode == 2) {
23978     // Sanity Check: Make sure using fp_offset makes sense.
23979     assert(!Subtarget.useSoftFloat() &&
23980            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
23981            Subtarget.hasSSE1());
23982   }
23983 
23984   // Insert VAARG_64 node into the DAG
23985   // VAARG_64 returns two values: Variable Argument Address, Chain
23986   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
23987                        DAG.getConstant(ArgMode, dl, MVT::i8),
23988                        DAG.getConstant(Align, dl, MVT::i32)};
23989   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
23990   SDValue VAARG = DAG.getMemIntrinsicNode(
23991       X86ISD::VAARG_64, dl, VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
23992       /*Align=*/None, MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
23993   Chain = VAARG.getValue(1);
23994 
23995   // Load the next argument and return it
23996   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
23997 }
23998 
LowerVACOPY(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)23999 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
24000                            SelectionDAG &DAG) {
24001   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
24002   // where a va_list is still an i8*.
24003   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
24004   if (Subtarget.isCallingConvWin64(
24005         DAG.getMachineFunction().getFunction().getCallingConv()))
24006     // Probably a Win64 va_copy.
24007     return DAG.expandVACopy(Op.getNode());
24008 
24009   SDValue Chain = Op.getOperand(0);
24010   SDValue DstPtr = Op.getOperand(1);
24011   SDValue SrcPtr = Op.getOperand(2);
24012   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
24013   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
24014   SDLoc DL(Op);
24015 
24016   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(24, DL),
24017                        Align(8), /*isVolatile*/ false, false, false,
24018                        /*MustPreserveCheriCapabilities=*/false,
24019                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
24020 }
24021 
24022 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
getTargetVShiftUniformOpcode(unsigned Opc,bool IsVariable)24023 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
24024   switch (Opc) {
24025   case ISD::SHL:
24026   case X86ISD::VSHL:
24027   case X86ISD::VSHLI:
24028     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
24029   case ISD::SRL:
24030   case X86ISD::VSRL:
24031   case X86ISD::VSRLI:
24032     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
24033   case ISD::SRA:
24034   case X86ISD::VSRA:
24035   case X86ISD::VSRAI:
24036     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
24037   }
24038   llvm_unreachable("Unknown target vector shift node");
24039 }
24040 
24041 /// Handle vector element shifts where the shift amount is a constant.
24042 /// Takes immediate version of shift as input.
getTargetVShiftByConstNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,uint64_t ShiftAmt,SelectionDAG & DAG)24043 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
24044                                           SDValue SrcOp, uint64_t ShiftAmt,
24045                                           SelectionDAG &DAG) {
24046   MVT ElementType = VT.getVectorElementType();
24047 
24048   // Bitcast the source vector to the output type, this is mainly necessary for
24049   // vXi8/vXi64 shifts.
24050   if (VT != SrcOp.getSimpleValueType())
24051     SrcOp = DAG.getBitcast(VT, SrcOp);
24052 
24053   // Fold this packed shift into its first operand if ShiftAmt is 0.
24054   if (ShiftAmt == 0)
24055     return SrcOp;
24056 
24057   // Check for ShiftAmt >= element width
24058   if (ShiftAmt >= ElementType.getSizeInBits()) {
24059     if (Opc == X86ISD::VSRAI)
24060       ShiftAmt = ElementType.getSizeInBits() - 1;
24061     else
24062       return DAG.getConstant(0, dl, VT);
24063   }
24064 
24065   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
24066          && "Unknown target vector shift-by-constant node");
24067 
24068   // Fold this packed vector shift into a build vector if SrcOp is a
24069   // vector of Constants or UNDEFs.
24070   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
24071     SmallVector<SDValue, 8> Elts;
24072     unsigned NumElts = SrcOp->getNumOperands();
24073 
24074     switch (Opc) {
24075     default: llvm_unreachable("Unknown opcode!");
24076     case X86ISD::VSHLI:
24077       for (unsigned i = 0; i != NumElts; ++i) {
24078         SDValue CurrentOp = SrcOp->getOperand(i);
24079         if (CurrentOp->isUndef()) {
24080           // Must produce 0s in the correct bits.
24081           Elts.push_back(DAG.getConstant(0, dl, ElementType));
24082           continue;
24083         }
24084         auto *ND = cast<ConstantSDNode>(CurrentOp);
24085         const APInt &C = ND->getAPIntValue();
24086         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
24087       }
24088       break;
24089     case X86ISD::VSRLI:
24090       for (unsigned i = 0; i != NumElts; ++i) {
24091         SDValue CurrentOp = SrcOp->getOperand(i);
24092         if (CurrentOp->isUndef()) {
24093           // Must produce 0s in the correct bits.
24094           Elts.push_back(DAG.getConstant(0, dl, ElementType));
24095           continue;
24096         }
24097         auto *ND = cast<ConstantSDNode>(CurrentOp);
24098         const APInt &C = ND->getAPIntValue();
24099         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
24100       }
24101       break;
24102     case X86ISD::VSRAI:
24103       for (unsigned i = 0; i != NumElts; ++i) {
24104         SDValue CurrentOp = SrcOp->getOperand(i);
24105         if (CurrentOp->isUndef()) {
24106           // All shifted in bits must be the same so use 0.
24107           Elts.push_back(DAG.getConstant(0, dl, ElementType));
24108           continue;
24109         }
24110         auto *ND = cast<ConstantSDNode>(CurrentOp);
24111         const APInt &C = ND->getAPIntValue();
24112         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
24113       }
24114       break;
24115     }
24116 
24117     return DAG.getBuildVector(VT, dl, Elts);
24118   }
24119 
24120   return DAG.getNode(Opc, dl, VT, SrcOp,
24121                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
24122 }
24123 
24124 /// Handle vector element shifts where the shift amount may or may not be a
24125 /// constant. Takes immediate version of shift as input.
getTargetVShiftNode(unsigned Opc,const SDLoc & dl,MVT VT,SDValue SrcOp,SDValue ShAmt,const X86Subtarget & Subtarget,SelectionDAG & DAG)24126 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
24127                                    SDValue SrcOp, SDValue ShAmt,
24128                                    const X86Subtarget &Subtarget,
24129                                    SelectionDAG &DAG) {
24130   MVT SVT = ShAmt.getSimpleValueType();
24131   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
24132 
24133   // Catch shift-by-constant.
24134   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
24135     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
24136                                       CShAmt->getZExtValue(), DAG);
24137 
24138   // Change opcode to non-immediate version.
24139   Opc = getTargetVShiftUniformOpcode(Opc, true);
24140 
24141   // Need to build a vector containing shift amount.
24142   // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
24143   // +====================+============+=======================================+
24144   // | ShAmt is           | HasSSE4.1? | Construct ShAmt vector as             |
24145   // +====================+============+=======================================+
24146   // | i64                | Yes, No    | Use ShAmt as lowest elt               |
24147   // | i32                | Yes        | zero-extend in-reg                    |
24148   // | (i32 zext(i16/i8)) | Yes        | zero-extend in-reg                    |
24149   // | (i32 zext(i16/i8)) | No         | byte-shift-in-reg                     |
24150   // | i16/i32            | No         | v4i32 build_vector(ShAmt, 0, ud, ud)) |
24151   // +====================+============+=======================================+
24152 
24153   if (SVT == MVT::i64)
24154     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
24155   else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
24156            ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24157            (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
24158             ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
24159     ShAmt = ShAmt.getOperand(0);
24160     MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
24161     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
24162     if (Subtarget.hasSSE41())
24163       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
24164                           MVT::v2i64, ShAmt);
24165     else {
24166       SDValue ByteShift = DAG.getTargetConstant(
24167           (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
24168       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
24169       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
24170                           ByteShift);
24171       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
24172                           ByteShift);
24173     }
24174   } else if (Subtarget.hasSSE41() &&
24175              ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24176     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
24177     ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
24178                         MVT::v2i64, ShAmt);
24179   } else {
24180     SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
24181                         DAG.getUNDEF(SVT)};
24182     ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
24183   }
24184 
24185   // The return type has to be a 128-bit type with the same element
24186   // type as the input type.
24187   MVT EltVT = VT.getVectorElementType();
24188   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
24189 
24190   ShAmt = DAG.getBitcast(ShVT, ShAmt);
24191   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
24192 }
24193 
24194 /// Return Mask with the necessary casting or extending
24195 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
getMaskNode(SDValue Mask,MVT MaskVT,const X86Subtarget & Subtarget,SelectionDAG & DAG,const SDLoc & dl)24196 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
24197                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
24198                            const SDLoc &dl) {
24199 
24200   if (isAllOnesConstant(Mask))
24201     return DAG.getConstant(1, dl, MaskVT);
24202   if (X86::isZeroNode(Mask))
24203     return DAG.getConstant(0, dl, MaskVT);
24204 
24205   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
24206 
24207   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
24208     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
24209     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
24210     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
24211     SDValue Lo, Hi;
24212     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
24213                         DAG.getConstant(0, dl, MVT::i32));
24214     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
24215                         DAG.getConstant(1, dl, MVT::i32));
24216 
24217     Lo = DAG.getBitcast(MVT::v32i1, Lo);
24218     Hi = DAG.getBitcast(MVT::v32i1, Hi);
24219 
24220     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
24221   } else {
24222     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
24223                                      Mask.getSimpleValueType().getSizeInBits());
24224     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
24225     // are extracted by EXTRACT_SUBVECTOR.
24226     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
24227                        DAG.getBitcast(BitcastVT, Mask),
24228                        DAG.getIntPtrConstant(0, dl));
24229   }
24230 }
24231 
24232 /// Return (and \p Op, \p Mask) for compare instructions or
24233 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
24234 /// necessary casting or extending for \p Mask when lowering masking intrinsics
getVectorMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)24235 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
24236                   SDValue PreservedSrc,
24237                   const X86Subtarget &Subtarget,
24238                   SelectionDAG &DAG) {
24239   MVT VT = Op.getSimpleValueType();
24240   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
24241   unsigned OpcodeSelect = ISD::VSELECT;
24242   SDLoc dl(Op);
24243 
24244   if (isAllOnesConstant(Mask))
24245     return Op;
24246 
24247   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24248 
24249   if (PreservedSrc.isUndef())
24250     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
24251   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
24252 }
24253 
24254 /// Creates an SDNode for a predicated scalar operation.
24255 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
24256 /// The mask is coming as MVT::i8 and it should be transformed
24257 /// to MVT::v1i1 while lowering masking intrinsics.
24258 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
24259 /// "X86select" instead of "vselect". We just can't create the "vselect" node
24260 /// for a scalar instruction.
getScalarMaskingNode(SDValue Op,SDValue Mask,SDValue PreservedSrc,const X86Subtarget & Subtarget,SelectionDAG & DAG)24261 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
24262                                     SDValue PreservedSrc,
24263                                     const X86Subtarget &Subtarget,
24264                                     SelectionDAG &DAG) {
24265 
24266   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
24267     if (MaskConst->getZExtValue() & 0x1)
24268       return Op;
24269 
24270   MVT VT = Op.getSimpleValueType();
24271   SDLoc dl(Op);
24272 
24273   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
24274   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
24275                               DAG.getBitcast(MVT::v8i1, Mask),
24276                               DAG.getIntPtrConstant(0, dl));
24277   if (Op.getOpcode() == X86ISD::FSETCCM ||
24278       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
24279       Op.getOpcode() == X86ISD::VFPCLASSS)
24280     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
24281 
24282   if (PreservedSrc.isUndef())
24283     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
24284   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
24285 }
24286 
getSEHRegistrationNodeSize(const Function * Fn)24287 static int getSEHRegistrationNodeSize(const Function *Fn) {
24288   if (!Fn->hasPersonalityFn())
24289     report_fatal_error(
24290         "querying registration node size for function without personality");
24291   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
24292   // WinEHStatePass for the full struct definition.
24293   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
24294   case EHPersonality::MSVC_X86SEH: return 24;
24295   case EHPersonality::MSVC_CXX: return 16;
24296   default: break;
24297   }
24298   report_fatal_error(
24299       "can only recover FP for 32-bit MSVC EH personality functions");
24300 }
24301 
24302 /// When the MSVC runtime transfers control to us, either to an outlined
24303 /// function or when returning to a parent frame after catching an exception, we
24304 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
24305 /// Here's the math:
24306 ///   RegNodeBase = EntryEBP - RegNodeSize
24307 ///   ParentFP = RegNodeBase - ParentFrameOffset
24308 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
24309 /// subtracting the offset (negative on x86) takes us back to the parent FP.
recoverFramePointer(SelectionDAG & DAG,const Function * Fn,SDValue EntryEBP)24310 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
24311                                    SDValue EntryEBP) {
24312   MachineFunction &MF = DAG.getMachineFunction();
24313   SDLoc dl;
24314 
24315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24316   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24317 
24318   // It's possible that the parent function no longer has a personality function
24319   // if the exceptional code was optimized away, in which case we just return
24320   // the incoming EBP.
24321   if (!Fn->hasPersonalityFn())
24322     return EntryEBP;
24323 
24324   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
24325   // registration, or the .set_setframe offset.
24326   MCSymbol *OffsetSym =
24327       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
24328           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
24329   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
24330   SDValue ParentFrameOffset =
24331       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
24332 
24333   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
24334   // prologue to RBP in the parent function.
24335   const X86Subtarget &Subtarget =
24336       static_cast<const X86Subtarget &>(DAG.getSubtarget());
24337   if (Subtarget.is64Bit())
24338     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
24339 
24340   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
24341   // RegNodeBase = EntryEBP - RegNodeSize
24342   // ParentFP = RegNodeBase - ParentFrameOffset
24343   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
24344                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
24345   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
24346 }
24347 
LowerINTRINSIC_WO_CHAIN(SDValue Op,SelectionDAG & DAG) const24348 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
24349                                                    SelectionDAG &DAG) const {
24350   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
24351   auto isRoundModeCurDirection = [](SDValue Rnd) {
24352     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
24353       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
24354 
24355     return false;
24356   };
24357   auto isRoundModeSAE = [](SDValue Rnd) {
24358     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
24359       unsigned RC = C->getZExtValue();
24360       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
24361         // Clear the NO_EXC bit and check remaining bits.
24362         RC ^= X86::STATIC_ROUNDING::NO_EXC;
24363         // As a convenience we allow no other bits or explicitly
24364         // current direction.
24365         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
24366       }
24367     }
24368 
24369     return false;
24370   };
24371   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
24372     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
24373       RC = C->getZExtValue();
24374       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
24375         // Clear the NO_EXC bit and check remaining bits.
24376         RC ^= X86::STATIC_ROUNDING::NO_EXC;
24377         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
24378                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
24379                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
24380                RC == X86::STATIC_ROUNDING::TO_ZERO;
24381       }
24382     }
24383 
24384     return false;
24385   };
24386 
24387   SDLoc dl(Op);
24388   unsigned IntNo = Op.getConstantOperandVal(0);
24389   MVT VT = Op.getSimpleValueType();
24390   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
24391 
24392   if (IntrData) {
24393     switch(IntrData->Type) {
24394     case INTR_TYPE_1OP: {
24395       // We specify 2 possible opcodes for intrinsics with rounding modes.
24396       // First, we check if the intrinsic may have non-default rounding mode,
24397       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
24398       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
24399       if (IntrWithRoundingModeOpcode != 0) {
24400         SDValue Rnd = Op.getOperand(2);
24401         unsigned RC = 0;
24402         if (isRoundModeSAEToX(Rnd, RC))
24403           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
24404                              Op.getOperand(1),
24405                              DAG.getTargetConstant(RC, dl, MVT::i32));
24406         if (!isRoundModeCurDirection(Rnd))
24407           return SDValue();
24408       }
24409       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24410                          Op.getOperand(1));
24411     }
24412     case INTR_TYPE_1OP_SAE: {
24413       SDValue Sae = Op.getOperand(2);
24414 
24415       unsigned Opc;
24416       if (isRoundModeCurDirection(Sae))
24417         Opc = IntrData->Opc0;
24418       else if (isRoundModeSAE(Sae))
24419         Opc = IntrData->Opc1;
24420       else
24421         return SDValue();
24422 
24423       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
24424     }
24425     case INTR_TYPE_2OP: {
24426       SDValue Src2 = Op.getOperand(2);
24427 
24428       // We specify 2 possible opcodes for intrinsics with rounding modes.
24429       // First, we check if the intrinsic may have non-default rounding mode,
24430       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
24431       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
24432       if (IntrWithRoundingModeOpcode != 0) {
24433         SDValue Rnd = Op.getOperand(3);
24434         unsigned RC = 0;
24435         if (isRoundModeSAEToX(Rnd, RC))
24436           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
24437                              Op.getOperand(1), Src2,
24438                              DAG.getTargetConstant(RC, dl, MVT::i32));
24439         if (!isRoundModeCurDirection(Rnd))
24440           return SDValue();
24441       }
24442 
24443       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24444                          Op.getOperand(1), Src2);
24445     }
24446     case INTR_TYPE_2OP_SAE: {
24447       SDValue Sae = Op.getOperand(3);
24448 
24449       unsigned Opc;
24450       if (isRoundModeCurDirection(Sae))
24451         Opc = IntrData->Opc0;
24452       else if (isRoundModeSAE(Sae))
24453         Opc = IntrData->Opc1;
24454       else
24455         return SDValue();
24456 
24457       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
24458                          Op.getOperand(2));
24459     }
24460     case INTR_TYPE_3OP:
24461     case INTR_TYPE_3OP_IMM8: {
24462       SDValue Src1 = Op.getOperand(1);
24463       SDValue Src2 = Op.getOperand(2);
24464       SDValue Src3 = Op.getOperand(3);
24465 
24466       // We specify 2 possible opcodes for intrinsics with rounding modes.
24467       // First, we check if the intrinsic may have non-default rounding mode,
24468       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
24469       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
24470       if (IntrWithRoundingModeOpcode != 0) {
24471         SDValue Rnd = Op.getOperand(4);
24472         unsigned RC = 0;
24473         if (isRoundModeSAEToX(Rnd, RC))
24474           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
24475                              Src1, Src2, Src3,
24476                              DAG.getTargetConstant(RC, dl, MVT::i32));
24477         if (!isRoundModeCurDirection(Rnd))
24478           return SDValue();
24479       }
24480 
24481       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24482                          {Src1, Src2, Src3});
24483     }
24484     case INTR_TYPE_4OP:
24485       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
24486         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
24487     case INTR_TYPE_1OP_MASK: {
24488       SDValue Src = Op.getOperand(1);
24489       SDValue PassThru = Op.getOperand(2);
24490       SDValue Mask = Op.getOperand(3);
24491       // We add rounding mode to the Node when
24492       //   - RC Opcode is specified and
24493       //   - RC is not "current direction".
24494       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
24495       if (IntrWithRoundingModeOpcode != 0) {
24496         SDValue Rnd = Op.getOperand(4);
24497         unsigned RC = 0;
24498         if (isRoundModeSAEToX(Rnd, RC))
24499           return getVectorMaskingNode(
24500               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
24501                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
24502               Mask, PassThru, Subtarget, DAG);
24503         if (!isRoundModeCurDirection(Rnd))
24504           return SDValue();
24505       }
24506       return getVectorMaskingNode(
24507           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
24508           Subtarget, DAG);
24509     }
24510     case INTR_TYPE_1OP_MASK_SAE: {
24511       SDValue Src = Op.getOperand(1);
24512       SDValue PassThru = Op.getOperand(2);
24513       SDValue Mask = Op.getOperand(3);
24514       SDValue Rnd = Op.getOperand(4);
24515 
24516       unsigned Opc;
24517       if (isRoundModeCurDirection(Rnd))
24518         Opc = IntrData->Opc0;
24519       else if (isRoundModeSAE(Rnd))
24520         Opc = IntrData->Opc1;
24521       else
24522         return SDValue();
24523 
24524       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
24525                                   Subtarget, DAG);
24526     }
24527     case INTR_TYPE_SCALAR_MASK: {
24528       SDValue Src1 = Op.getOperand(1);
24529       SDValue Src2 = Op.getOperand(2);
24530       SDValue passThru = Op.getOperand(3);
24531       SDValue Mask = Op.getOperand(4);
24532       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
24533       // There are 2 kinds of intrinsics in this group:
24534       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
24535       // (2) With rounding mode and sae - 7 operands.
24536       bool HasRounding = IntrWithRoundingModeOpcode != 0;
24537       if (Op.getNumOperands() == (5U + HasRounding)) {
24538         if (HasRounding) {
24539           SDValue Rnd = Op.getOperand(5);
24540           unsigned RC = 0;
24541           if (isRoundModeSAEToX(Rnd, RC))
24542             return getScalarMaskingNode(
24543                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
24544                             DAG.getTargetConstant(RC, dl, MVT::i32)),
24545                 Mask, passThru, Subtarget, DAG);
24546           if (!isRoundModeCurDirection(Rnd))
24547             return SDValue();
24548         }
24549         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
24550                                                 Src2),
24551                                     Mask, passThru, Subtarget, DAG);
24552       }
24553 
24554       assert(Op.getNumOperands() == (6U + HasRounding) &&
24555              "Unexpected intrinsic form");
24556       SDValue RoundingMode = Op.getOperand(5);
24557       unsigned Opc = IntrData->Opc0;
24558       if (HasRounding) {
24559         SDValue Sae = Op.getOperand(6);
24560         if (isRoundModeSAE(Sae))
24561           Opc = IntrWithRoundingModeOpcode;
24562         else if (!isRoundModeCurDirection(Sae))
24563           return SDValue();
24564       }
24565       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
24566                                               Src2, RoundingMode),
24567                                   Mask, passThru, Subtarget, DAG);
24568     }
24569     case INTR_TYPE_SCALAR_MASK_RND: {
24570       SDValue Src1 = Op.getOperand(1);
24571       SDValue Src2 = Op.getOperand(2);
24572       SDValue passThru = Op.getOperand(3);
24573       SDValue Mask = Op.getOperand(4);
24574       SDValue Rnd = Op.getOperand(5);
24575 
24576       SDValue NewOp;
24577       unsigned RC = 0;
24578       if (isRoundModeCurDirection(Rnd))
24579         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
24580       else if (isRoundModeSAEToX(Rnd, RC))
24581         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
24582                             DAG.getTargetConstant(RC, dl, MVT::i32));
24583       else
24584         return SDValue();
24585 
24586       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
24587     }
24588     case INTR_TYPE_SCALAR_MASK_SAE: {
24589       SDValue Src1 = Op.getOperand(1);
24590       SDValue Src2 = Op.getOperand(2);
24591       SDValue passThru = Op.getOperand(3);
24592       SDValue Mask = Op.getOperand(4);
24593       SDValue Sae = Op.getOperand(5);
24594       unsigned Opc;
24595       if (isRoundModeCurDirection(Sae))
24596         Opc = IntrData->Opc0;
24597       else if (isRoundModeSAE(Sae))
24598         Opc = IntrData->Opc1;
24599       else
24600         return SDValue();
24601 
24602       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
24603                                   Mask, passThru, Subtarget, DAG);
24604     }
24605     case INTR_TYPE_2OP_MASK: {
24606       SDValue Src1 = Op.getOperand(1);
24607       SDValue Src2 = Op.getOperand(2);
24608       SDValue PassThru = Op.getOperand(3);
24609       SDValue Mask = Op.getOperand(4);
24610       SDValue NewOp;
24611       if (IntrData->Opc1 != 0) {
24612         SDValue Rnd = Op.getOperand(5);
24613         unsigned RC = 0;
24614         if (isRoundModeSAEToX(Rnd, RC))
24615           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
24616                               DAG.getTargetConstant(RC, dl, MVT::i32));
24617         else if (!isRoundModeCurDirection(Rnd))
24618           return SDValue();
24619       }
24620       if (!NewOp)
24621         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
24622       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
24623     }
24624     case INTR_TYPE_2OP_MASK_SAE: {
24625       SDValue Src1 = Op.getOperand(1);
24626       SDValue Src2 = Op.getOperand(2);
24627       SDValue PassThru = Op.getOperand(3);
24628       SDValue Mask = Op.getOperand(4);
24629 
24630       unsigned Opc = IntrData->Opc0;
24631       if (IntrData->Opc1 != 0) {
24632         SDValue Sae = Op.getOperand(5);
24633         if (isRoundModeSAE(Sae))
24634           Opc = IntrData->Opc1;
24635         else if (!isRoundModeCurDirection(Sae))
24636           return SDValue();
24637       }
24638 
24639       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
24640                                   Mask, PassThru, Subtarget, DAG);
24641     }
24642     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
24643       SDValue Src1 = Op.getOperand(1);
24644       SDValue Src2 = Op.getOperand(2);
24645       SDValue Src3 = Op.getOperand(3);
24646       SDValue PassThru = Op.getOperand(4);
24647       SDValue Mask = Op.getOperand(5);
24648       SDValue Sae = Op.getOperand(6);
24649       unsigned Opc;
24650       if (isRoundModeCurDirection(Sae))
24651         Opc = IntrData->Opc0;
24652       else if (isRoundModeSAE(Sae))
24653         Opc = IntrData->Opc1;
24654       else
24655         return SDValue();
24656 
24657       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
24658                                   Mask, PassThru, Subtarget, DAG);
24659     }
24660     case INTR_TYPE_3OP_MASK_SAE: {
24661       SDValue Src1 = Op.getOperand(1);
24662       SDValue Src2 = Op.getOperand(2);
24663       SDValue Src3 = Op.getOperand(3);
24664       SDValue PassThru = Op.getOperand(4);
24665       SDValue Mask = Op.getOperand(5);
24666 
24667       unsigned Opc = IntrData->Opc0;
24668       if (IntrData->Opc1 != 0) {
24669         SDValue Sae = Op.getOperand(6);
24670         if (isRoundModeSAE(Sae))
24671           Opc = IntrData->Opc1;
24672         else if (!isRoundModeCurDirection(Sae))
24673           return SDValue();
24674       }
24675       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
24676                                   Mask, PassThru, Subtarget, DAG);
24677     }
24678     case BLENDV: {
24679       SDValue Src1 = Op.getOperand(1);
24680       SDValue Src2 = Op.getOperand(2);
24681       SDValue Src3 = Op.getOperand(3);
24682 
24683       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
24684       Src3 = DAG.getBitcast(MaskVT, Src3);
24685 
24686       // Reverse the operands to match VSELECT order.
24687       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
24688     }
24689     case VPERM_2OP : {
24690       SDValue Src1 = Op.getOperand(1);
24691       SDValue Src2 = Op.getOperand(2);
24692 
24693       // Swap Src1 and Src2 in the node creation
24694       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
24695     }
24696     case IFMA_OP:
24697       // NOTE: We need to swizzle the operands to pass the multiply operands
24698       // first.
24699       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24700                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
24701     case FPCLASSS: {
24702       SDValue Src1 = Op.getOperand(1);
24703       SDValue Imm = Op.getOperand(2);
24704       SDValue Mask = Op.getOperand(3);
24705       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
24706       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
24707                                                  Subtarget, DAG);
24708       // Need to fill with zeros to ensure the bitcast will produce zeroes
24709       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
24710       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
24711                                 DAG.getConstant(0, dl, MVT::v8i1),
24712                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
24713       return DAG.getBitcast(MVT::i8, Ins);
24714     }
24715 
24716     case CMP_MASK_CC: {
24717       MVT MaskVT = Op.getSimpleValueType();
24718       SDValue CC = Op.getOperand(3);
24719       // We specify 2 possible opcodes for intrinsics with rounding modes.
24720       // First, we check if the intrinsic may have non-default rounding mode,
24721       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
24722       if (IntrData->Opc1 != 0) {
24723         SDValue Sae = Op.getOperand(4);
24724         if (isRoundModeSAE(Sae))
24725           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
24726                              Op.getOperand(2), CC, Sae);
24727         if (!isRoundModeCurDirection(Sae))
24728           return SDValue();
24729       }
24730       //default rounding mode
24731       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
24732                          {Op.getOperand(1), Op.getOperand(2), CC});
24733     }
24734     case CMP_MASK_SCALAR_CC: {
24735       SDValue Src1 = Op.getOperand(1);
24736       SDValue Src2 = Op.getOperand(2);
24737       SDValue CC = Op.getOperand(3);
24738       SDValue Mask = Op.getOperand(4);
24739 
24740       SDValue Cmp;
24741       if (IntrData->Opc1 != 0) {
24742         SDValue Sae = Op.getOperand(5);
24743         if (isRoundModeSAE(Sae))
24744           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
24745         else if (!isRoundModeCurDirection(Sae))
24746           return SDValue();
24747       }
24748       //default rounding mode
24749       if (!Cmp.getNode())
24750         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
24751 
24752       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
24753                                              Subtarget, DAG);
24754       // Need to fill with zeros to ensure the bitcast will produce zeroes
24755       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
24756       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
24757                                 DAG.getConstant(0, dl, MVT::v8i1),
24758                                 CmpMask, DAG.getIntPtrConstant(0, dl));
24759       return DAG.getBitcast(MVT::i8, Ins);
24760     }
24761     case COMI: { // Comparison intrinsics
24762       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
24763       SDValue LHS = Op.getOperand(1);
24764       SDValue RHS = Op.getOperand(2);
24765       // Some conditions require the operands to be swapped.
24766       if (CC == ISD::SETLT || CC == ISD::SETLE)
24767         std::swap(LHS, RHS);
24768 
24769       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
24770       SDValue SetCC;
24771       switch (CC) {
24772       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
24773         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
24774         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
24775         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
24776         break;
24777       }
24778       case ISD::SETNE: { // (ZF = 1 or PF = 1)
24779         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
24780         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
24781         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
24782         break;
24783       }
24784       case ISD::SETGT: // (CF = 0 and ZF = 0)
24785       case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
24786         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
24787         break;
24788       }
24789       case ISD::SETGE: // CF = 0
24790       case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
24791         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
24792         break;
24793       default:
24794         llvm_unreachable("Unexpected illegal condition!");
24795       }
24796       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
24797     }
24798     case COMI_RM: { // Comparison intrinsics with Sae
24799       SDValue LHS = Op.getOperand(1);
24800       SDValue RHS = Op.getOperand(2);
24801       unsigned CondVal = Op.getConstantOperandVal(3);
24802       SDValue Sae = Op.getOperand(4);
24803 
24804       SDValue FCmp;
24805       if (isRoundModeCurDirection(Sae))
24806         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
24807                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
24808       else if (isRoundModeSAE(Sae))
24809         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
24810                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
24811       else
24812         return SDValue();
24813       // Need to fill with zeros to ensure the bitcast will produce zeroes
24814       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
24815       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
24816                                 DAG.getConstant(0, dl, MVT::v16i1),
24817                                 FCmp, DAG.getIntPtrConstant(0, dl));
24818       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
24819                          DAG.getBitcast(MVT::i16, Ins));
24820     }
24821     case VSHIFT:
24822       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
24823                                  Op.getOperand(1), Op.getOperand(2), Subtarget,
24824                                  DAG);
24825     case COMPRESS_EXPAND_IN_REG: {
24826       SDValue Mask = Op.getOperand(3);
24827       SDValue DataToCompress = Op.getOperand(1);
24828       SDValue PassThru = Op.getOperand(2);
24829       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
24830         return Op.getOperand(1);
24831 
24832       // Avoid false dependency.
24833       if (PassThru.isUndef())
24834         PassThru = DAG.getConstant(0, dl, VT);
24835 
24836       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
24837                          Mask);
24838     }
24839     case FIXUPIMM:
24840     case FIXUPIMM_MASKZ: {
24841       SDValue Src1 = Op.getOperand(1);
24842       SDValue Src2 = Op.getOperand(2);
24843       SDValue Src3 = Op.getOperand(3);
24844       SDValue Imm = Op.getOperand(4);
24845       SDValue Mask = Op.getOperand(5);
24846       SDValue Passthru = (IntrData->Type == FIXUPIMM)
24847                              ? Src1
24848                              : getZeroVector(VT, Subtarget, DAG, dl);
24849 
24850       unsigned Opc = IntrData->Opc0;
24851       if (IntrData->Opc1 != 0) {
24852         SDValue Sae = Op.getOperand(6);
24853         if (isRoundModeSAE(Sae))
24854           Opc = IntrData->Opc1;
24855         else if (!isRoundModeCurDirection(Sae))
24856           return SDValue();
24857       }
24858 
24859       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
24860 
24861       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
24862         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
24863 
24864       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
24865     }
24866     case ROUNDP: {
24867       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
24868       // Clear the upper bits of the rounding immediate so that the legacy
24869       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
24870       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
24871       SDValue RoundingMode =
24872           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
24873       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24874                          Op.getOperand(1), RoundingMode);
24875     }
24876     case ROUNDS: {
24877       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
24878       // Clear the upper bits of the rounding immediate so that the legacy
24879       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
24880       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
24881       SDValue RoundingMode =
24882           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
24883       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24884                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
24885     }
24886     case BEXTRI: {
24887       assert(IntrData->Opc0 == X86ISD::BEXTR && "Unexpected opcode");
24888 
24889       // The control is a TargetConstant, but we need to convert it to a
24890       // ConstantSDNode.
24891       uint64_t Imm = Op.getConstantOperandVal(2);
24892       SDValue Control = DAG.getConstant(Imm, dl, Op.getValueType());
24893       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
24894                          Op.getOperand(1), Control);
24895     }
24896     // ADC/ADCX/SBB
24897     case ADX: {
24898       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
24899       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
24900 
24901       SDValue Res;
24902       // If the carry in is zero, then we should just use ADD/SUB instead of
24903       // ADC/SBB.
24904       if (isNullConstant(Op.getOperand(1))) {
24905         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
24906                           Op.getOperand(3));
24907       } else {
24908         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
24909                                     DAG.getConstant(-1, dl, MVT::i8));
24910         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
24911                           Op.getOperand(3), GenCF.getValue(1));
24912       }
24913       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
24914       SDValue Results[] = { SetCC, Res };
24915       return DAG.getMergeValues(Results, dl);
24916     }
24917     case CVTPD2PS_MASK:
24918     case CVTPD2DQ_MASK:
24919     case CVTQQ2PS_MASK:
24920     case TRUNCATE_TO_REG: {
24921       SDValue Src = Op.getOperand(1);
24922       SDValue PassThru = Op.getOperand(2);
24923       SDValue Mask = Op.getOperand(3);
24924 
24925       if (isAllOnesConstant(Mask))
24926         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
24927 
24928       MVT SrcVT = Src.getSimpleValueType();
24929       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
24930       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24931       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
24932                          {Src, PassThru, Mask});
24933     }
24934     case CVTPS2PH_MASK: {
24935       SDValue Src = Op.getOperand(1);
24936       SDValue Rnd = Op.getOperand(2);
24937       SDValue PassThru = Op.getOperand(3);
24938       SDValue Mask = Op.getOperand(4);
24939 
24940       if (isAllOnesConstant(Mask))
24941         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
24942 
24943       MVT SrcVT = Src.getSimpleValueType();
24944       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
24945       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24946       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
24947                          PassThru, Mask);
24948 
24949     }
24950     case CVTNEPS2BF16_MASK: {
24951       SDValue Src = Op.getOperand(1);
24952       SDValue PassThru = Op.getOperand(2);
24953       SDValue Mask = Op.getOperand(3);
24954 
24955       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
24956         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
24957 
24958       // Break false dependency.
24959       if (PassThru.isUndef())
24960         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
24961 
24962       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
24963                          Mask);
24964     }
24965     default:
24966       break;
24967     }
24968   }
24969 
24970   switch (IntNo) {
24971   default: return SDValue();    // Don't custom lower most intrinsics.
24972 
24973   // ptest and testp intrinsics. The intrinsic these come from are designed to
24974   // return an integer value, not just an instruction so lower it to the ptest
24975   // or testp pattern and a setcc for the result.
24976   case Intrinsic::x86_avx512_ktestc_b:
24977   case Intrinsic::x86_avx512_ktestc_w:
24978   case Intrinsic::x86_avx512_ktestc_d:
24979   case Intrinsic::x86_avx512_ktestc_q:
24980   case Intrinsic::x86_avx512_ktestz_b:
24981   case Intrinsic::x86_avx512_ktestz_w:
24982   case Intrinsic::x86_avx512_ktestz_d:
24983   case Intrinsic::x86_avx512_ktestz_q:
24984   case Intrinsic::x86_sse41_ptestz:
24985   case Intrinsic::x86_sse41_ptestc:
24986   case Intrinsic::x86_sse41_ptestnzc:
24987   case Intrinsic::x86_avx_ptestz_256:
24988   case Intrinsic::x86_avx_ptestc_256:
24989   case Intrinsic::x86_avx_ptestnzc_256:
24990   case Intrinsic::x86_avx_vtestz_ps:
24991   case Intrinsic::x86_avx_vtestc_ps:
24992   case Intrinsic::x86_avx_vtestnzc_ps:
24993   case Intrinsic::x86_avx_vtestz_pd:
24994   case Intrinsic::x86_avx_vtestc_pd:
24995   case Intrinsic::x86_avx_vtestnzc_pd:
24996   case Intrinsic::x86_avx_vtestz_ps_256:
24997   case Intrinsic::x86_avx_vtestc_ps_256:
24998   case Intrinsic::x86_avx_vtestnzc_ps_256:
24999   case Intrinsic::x86_avx_vtestz_pd_256:
25000   case Intrinsic::x86_avx_vtestc_pd_256:
25001   case Intrinsic::x86_avx_vtestnzc_pd_256: {
25002     unsigned TestOpc = X86ISD::PTEST;
25003     X86::CondCode X86CC;
25004     switch (IntNo) {
25005     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
25006     case Intrinsic::x86_avx512_ktestc_b:
25007     case Intrinsic::x86_avx512_ktestc_w:
25008     case Intrinsic::x86_avx512_ktestc_d:
25009     case Intrinsic::x86_avx512_ktestc_q:
25010       // CF = 1
25011       TestOpc = X86ISD::KTEST;
25012       X86CC = X86::COND_B;
25013       break;
25014     case Intrinsic::x86_avx512_ktestz_b:
25015     case Intrinsic::x86_avx512_ktestz_w:
25016     case Intrinsic::x86_avx512_ktestz_d:
25017     case Intrinsic::x86_avx512_ktestz_q:
25018       TestOpc = X86ISD::KTEST;
25019       X86CC = X86::COND_E;
25020       break;
25021     case Intrinsic::x86_avx_vtestz_ps:
25022     case Intrinsic::x86_avx_vtestz_pd:
25023     case Intrinsic::x86_avx_vtestz_ps_256:
25024     case Intrinsic::x86_avx_vtestz_pd_256:
25025       TestOpc = X86ISD::TESTP;
25026       LLVM_FALLTHROUGH;
25027     case Intrinsic::x86_sse41_ptestz:
25028     case Intrinsic::x86_avx_ptestz_256:
25029       // ZF = 1
25030       X86CC = X86::COND_E;
25031       break;
25032     case Intrinsic::x86_avx_vtestc_ps:
25033     case Intrinsic::x86_avx_vtestc_pd:
25034     case Intrinsic::x86_avx_vtestc_ps_256:
25035     case Intrinsic::x86_avx_vtestc_pd_256:
25036       TestOpc = X86ISD::TESTP;
25037       LLVM_FALLTHROUGH;
25038     case Intrinsic::x86_sse41_ptestc:
25039     case Intrinsic::x86_avx_ptestc_256:
25040       // CF = 1
25041       X86CC = X86::COND_B;
25042       break;
25043     case Intrinsic::x86_avx_vtestnzc_ps:
25044     case Intrinsic::x86_avx_vtestnzc_pd:
25045     case Intrinsic::x86_avx_vtestnzc_ps_256:
25046     case Intrinsic::x86_avx_vtestnzc_pd_256:
25047       TestOpc = X86ISD::TESTP;
25048       LLVM_FALLTHROUGH;
25049     case Intrinsic::x86_sse41_ptestnzc:
25050     case Intrinsic::x86_avx_ptestnzc_256:
25051       // ZF and CF = 0
25052       X86CC = X86::COND_A;
25053       break;
25054     }
25055 
25056     SDValue LHS = Op.getOperand(1);
25057     SDValue RHS = Op.getOperand(2);
25058     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
25059     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
25060     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25061   }
25062 
25063   case Intrinsic::x86_sse42_pcmpistria128:
25064   case Intrinsic::x86_sse42_pcmpestria128:
25065   case Intrinsic::x86_sse42_pcmpistric128:
25066   case Intrinsic::x86_sse42_pcmpestric128:
25067   case Intrinsic::x86_sse42_pcmpistrio128:
25068   case Intrinsic::x86_sse42_pcmpestrio128:
25069   case Intrinsic::x86_sse42_pcmpistris128:
25070   case Intrinsic::x86_sse42_pcmpestris128:
25071   case Intrinsic::x86_sse42_pcmpistriz128:
25072   case Intrinsic::x86_sse42_pcmpestriz128: {
25073     unsigned Opcode;
25074     X86::CondCode X86CC;
25075     switch (IntNo) {
25076     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
25077     case Intrinsic::x86_sse42_pcmpistria128:
25078       Opcode = X86ISD::PCMPISTR;
25079       X86CC = X86::COND_A;
25080       break;
25081     case Intrinsic::x86_sse42_pcmpestria128:
25082       Opcode = X86ISD::PCMPESTR;
25083       X86CC = X86::COND_A;
25084       break;
25085     case Intrinsic::x86_sse42_pcmpistric128:
25086       Opcode = X86ISD::PCMPISTR;
25087       X86CC = X86::COND_B;
25088       break;
25089     case Intrinsic::x86_sse42_pcmpestric128:
25090       Opcode = X86ISD::PCMPESTR;
25091       X86CC = X86::COND_B;
25092       break;
25093     case Intrinsic::x86_sse42_pcmpistrio128:
25094       Opcode = X86ISD::PCMPISTR;
25095       X86CC = X86::COND_O;
25096       break;
25097     case Intrinsic::x86_sse42_pcmpestrio128:
25098       Opcode = X86ISD::PCMPESTR;
25099       X86CC = X86::COND_O;
25100       break;
25101     case Intrinsic::x86_sse42_pcmpistris128:
25102       Opcode = X86ISD::PCMPISTR;
25103       X86CC = X86::COND_S;
25104       break;
25105     case Intrinsic::x86_sse42_pcmpestris128:
25106       Opcode = X86ISD::PCMPESTR;
25107       X86CC = X86::COND_S;
25108       break;
25109     case Intrinsic::x86_sse42_pcmpistriz128:
25110       Opcode = X86ISD::PCMPISTR;
25111       X86CC = X86::COND_E;
25112       break;
25113     case Intrinsic::x86_sse42_pcmpestriz128:
25114       Opcode = X86ISD::PCMPESTR;
25115       X86CC = X86::COND_E;
25116       break;
25117     }
25118     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25119     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25120     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
25121     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
25122     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25123   }
25124 
25125   case Intrinsic::x86_sse42_pcmpistri128:
25126   case Intrinsic::x86_sse42_pcmpestri128: {
25127     unsigned Opcode;
25128     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
25129       Opcode = X86ISD::PCMPISTR;
25130     else
25131       Opcode = X86ISD::PCMPESTR;
25132 
25133     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25134     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25135     return DAG.getNode(Opcode, dl, VTs, NewOps);
25136   }
25137 
25138   case Intrinsic::x86_sse42_pcmpistrm128:
25139   case Intrinsic::x86_sse42_pcmpestrm128: {
25140     unsigned Opcode;
25141     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
25142       Opcode = X86ISD::PCMPISTR;
25143     else
25144       Opcode = X86ISD::PCMPESTR;
25145 
25146     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25147     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25148     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
25149   }
25150 
25151   case Intrinsic::eh_sjlj_lsda: {
25152     MachineFunction &MF = DAG.getMachineFunction();
25153     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25154     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
25155     auto &Context = MF.getMMI().getContext();
25156     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
25157                                             Twine(MF.getFunctionNumber()));
25158     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
25159                        DAG.getMCSymbol(S, PtrVT));
25160   }
25161 
25162   case Intrinsic::x86_seh_lsda: {
25163     // Compute the symbol for the LSDA. We know it'll get emitted later.
25164     MachineFunction &MF = DAG.getMachineFunction();
25165     SDValue Op1 = Op.getOperand(1);
25166     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
25167     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
25168         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
25169 
25170     // Generate a simple absolute symbol reference. This intrinsic is only
25171     // supported on 32-bit Windows, which isn't PIC.
25172     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
25173     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
25174   }
25175 
25176   case Intrinsic::eh_recoverfp: {
25177     SDValue FnOp = Op.getOperand(1);
25178     SDValue IncomingFPOp = Op.getOperand(2);
25179     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
25180     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
25181     if (!Fn)
25182       report_fatal_error(
25183           "llvm.eh.recoverfp must take a function as the first argument");
25184     return recoverFramePointer(DAG, Fn, IncomingFPOp);
25185   }
25186 
25187   case Intrinsic::localaddress: {
25188     // Returns one of the stack, base, or frame pointer registers, depending on
25189     // which is used to reference local variables.
25190     MachineFunction &MF = DAG.getMachineFunction();
25191     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25192     unsigned Reg;
25193     if (RegInfo->hasBasePointer(MF))
25194       Reg = RegInfo->getBaseRegister();
25195     else { // Handles the SP or FP case.
25196       bool CantUseFP = RegInfo->needsStackRealignment(MF);
25197       if (CantUseFP)
25198         Reg = RegInfo->getPtrSizedStackRegister(MF);
25199       else
25200         Reg = RegInfo->getPtrSizedFrameRegister(MF);
25201     }
25202     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
25203   }
25204 
25205   case Intrinsic::x86_avx512_vp2intersect_q_512:
25206   case Intrinsic::x86_avx512_vp2intersect_q_256:
25207   case Intrinsic::x86_avx512_vp2intersect_q_128:
25208   case Intrinsic::x86_avx512_vp2intersect_d_512:
25209   case Intrinsic::x86_avx512_vp2intersect_d_256:
25210   case Intrinsic::x86_avx512_vp2intersect_d_128: {
25211     MVT MaskVT = Op.getSimpleValueType();
25212 
25213     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
25214     SDLoc DL(Op);
25215 
25216     SDValue Operation =
25217         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
25218                     Op->getOperand(1), Op->getOperand(2));
25219 
25220     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
25221                                                  MaskVT, Operation);
25222     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
25223                                                  MaskVT, Operation);
25224     return DAG.getMergeValues({Result0, Result1}, DL);
25225   }
25226   case Intrinsic::x86_mmx_pslli_w:
25227   case Intrinsic::x86_mmx_pslli_d:
25228   case Intrinsic::x86_mmx_pslli_q:
25229   case Intrinsic::x86_mmx_psrli_w:
25230   case Intrinsic::x86_mmx_psrli_d:
25231   case Intrinsic::x86_mmx_psrli_q:
25232   case Intrinsic::x86_mmx_psrai_w:
25233   case Intrinsic::x86_mmx_psrai_d: {
25234     SDLoc DL(Op);
25235     SDValue ShAmt = Op.getOperand(2);
25236     // If the argument is a constant, convert it to a target constant.
25237     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
25238       // Clamp out of bounds shift amounts since they will otherwise be masked
25239       // to 8-bits which may make it no longer out of bounds.
25240       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
25241       if (ShiftAmount == 0)
25242         return Op.getOperand(1);
25243 
25244       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
25245                          Op.getOperand(0), Op.getOperand(1),
25246                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
25247     }
25248 
25249     unsigned NewIntrinsic;
25250     switch (IntNo) {
25251     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
25252     case Intrinsic::x86_mmx_pslli_w:
25253       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
25254       break;
25255     case Intrinsic::x86_mmx_pslli_d:
25256       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
25257       break;
25258     case Intrinsic::x86_mmx_pslli_q:
25259       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
25260       break;
25261     case Intrinsic::x86_mmx_psrli_w:
25262       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
25263       break;
25264     case Intrinsic::x86_mmx_psrli_d:
25265       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
25266       break;
25267     case Intrinsic::x86_mmx_psrli_q:
25268       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
25269       break;
25270     case Intrinsic::x86_mmx_psrai_w:
25271       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
25272       break;
25273     case Intrinsic::x86_mmx_psrai_d:
25274       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
25275       break;
25276     }
25277 
25278     // The vector shift intrinsics with scalars uses 32b shift amounts but
25279     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
25280     // MMX register.
25281     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
25282     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
25283                        DAG.getConstant(NewIntrinsic, DL, MVT::i32),
25284                        Op.getOperand(1), ShAmt);
25285 
25286   }
25287   }
25288 }
25289 
getAVX2GatherNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)25290 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
25291                                  SDValue Src, SDValue Mask, SDValue Base,
25292                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
25293                                  const X86Subtarget &Subtarget) {
25294   SDLoc dl(Op);
25295   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25296   // Scale must be constant.
25297   if (!C)
25298     return SDValue();
25299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25300   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25301                                         TLI.getPointerTy(DAG.getDataLayout()));
25302   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
25303   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
25304   // If source is undef or we know it won't be used, use a zero vector
25305   // to break register dependency.
25306   // TODO: use undef instead and let BreakFalseDeps deal with it?
25307   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
25308     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
25309 
25310   // Cast mask to an integer type.
25311   Mask = DAG.getBitcast(MaskVT, Mask);
25312 
25313   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
25314 
25315   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
25316   SDValue Res =
25317       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
25318                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
25319   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
25320 }
25321 
getGatherNode(SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)25322 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
25323                              SDValue Src, SDValue Mask, SDValue Base,
25324                              SDValue Index, SDValue ScaleOp, SDValue Chain,
25325                              const X86Subtarget &Subtarget) {
25326   MVT VT = Op.getSimpleValueType();
25327   SDLoc dl(Op);
25328   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25329   // Scale must be constant.
25330   if (!C)
25331     return SDValue();
25332   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25333   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25334                                         TLI.getPointerTy(DAG.getDataLayout()));
25335   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
25336                               VT.getVectorNumElements());
25337   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
25338 
25339   // We support two versions of the gather intrinsics. One with scalar mask and
25340   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
25341   if (Mask.getValueType() != MaskVT)
25342     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25343 
25344   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
25345   // If source is undef or we know it won't be used, use a zero vector
25346   // to break register dependency.
25347   // TODO: use undef instead and let BreakFalseDeps deal with it?
25348   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
25349     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
25350 
25351   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
25352 
25353   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
25354   SDValue Res =
25355       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
25356                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
25357   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
25358 }
25359 
getScatterNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Src,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)25360 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
25361                                SDValue Src, SDValue Mask, SDValue Base,
25362                                SDValue Index, SDValue ScaleOp, SDValue Chain,
25363                                const X86Subtarget &Subtarget) {
25364   SDLoc dl(Op);
25365   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25366   // Scale must be constant.
25367   if (!C)
25368     return SDValue();
25369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25370   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25371                                         TLI.getPointerTy(DAG.getDataLayout()));
25372   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
25373                               Src.getSimpleValueType().getVectorNumElements());
25374   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
25375 
25376   // We support two versions of the scatter intrinsics. One with scalar mask and
25377   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
25378   if (Mask.getValueType() != MaskVT)
25379     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25380 
25381   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
25382 
25383   SDVTList VTs = DAG.getVTList(MVT::Other);
25384   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
25385   SDValue Res =
25386       DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
25387                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
25388   return Res;
25389 }
25390 
getPrefetchNode(unsigned Opc,SDValue Op,SelectionDAG & DAG,SDValue Mask,SDValue Base,SDValue Index,SDValue ScaleOp,SDValue Chain,const X86Subtarget & Subtarget)25391 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
25392                                SDValue Mask, SDValue Base, SDValue Index,
25393                                SDValue ScaleOp, SDValue Chain,
25394                                const X86Subtarget &Subtarget) {
25395   SDLoc dl(Op);
25396   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25397   // Scale must be constant.
25398   if (!C)
25399     return SDValue();
25400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25401   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25402                                         TLI.getPointerTy(DAG.getDataLayout()));
25403   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
25404   SDValue Segment = DAG.getRegister(0, MVT::i32);
25405   MVT MaskVT =
25406     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
25407   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25408   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
25409   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
25410   return SDValue(Res, 0);
25411 }
25412 
25413 /// Handles the lowering of builtin intrinsics with chain that return their
25414 /// value into registers EDX:EAX.
25415 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
25416 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
25417 /// TargetOpcode.
25418 /// Returns a Glue value which can be used to add extra copy-from-reg if the
25419 /// expanded intrinsics implicitly defines extra registers (i.e. not just
25420 /// EDX:EAX).
expandIntrinsicWChainHelper(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,unsigned TargetOpcode,unsigned SrcReg,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)25421 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
25422                                         SelectionDAG &DAG,
25423                                         unsigned TargetOpcode,
25424                                         unsigned SrcReg,
25425                                         const X86Subtarget &Subtarget,
25426                                         SmallVectorImpl<SDValue> &Results) {
25427   SDValue Chain = N->getOperand(0);
25428   SDValue Glue;
25429 
25430   if (SrcReg) {
25431     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
25432     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
25433     Glue = Chain.getValue(1);
25434   }
25435 
25436   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
25437   SDValue N1Ops[] = {Chain, Glue};
25438   SDNode *N1 = DAG.getMachineNode(
25439       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
25440   Chain = SDValue(N1, 0);
25441 
25442   // Reads the content of XCR and returns it in registers EDX:EAX.
25443   SDValue LO, HI;
25444   if (Subtarget.is64Bit()) {
25445     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
25446     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
25447                             LO.getValue(2));
25448   } else {
25449     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
25450     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
25451                             LO.getValue(2));
25452   }
25453   Chain = HI.getValue(1);
25454   Glue = HI.getValue(2);
25455 
25456   if (Subtarget.is64Bit()) {
25457     // Merge the two 32-bit values into a 64-bit one.
25458     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
25459                               DAG.getConstant(32, DL, MVT::i8));
25460     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
25461     Results.push_back(Chain);
25462     return Glue;
25463   }
25464 
25465   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
25466   SDValue Ops[] = { LO, HI };
25467   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
25468   Results.push_back(Pair);
25469   Results.push_back(Chain);
25470   return Glue;
25471 }
25472 
25473 /// Handles the lowering of builtin intrinsics that read the time stamp counter
25474 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
25475 /// READCYCLECOUNTER nodes.
getReadTimeStampCounter(SDNode * N,const SDLoc & DL,unsigned Opcode,SelectionDAG & DAG,const X86Subtarget & Subtarget,SmallVectorImpl<SDValue> & Results)25476 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
25477                                     SelectionDAG &DAG,
25478                                     const X86Subtarget &Subtarget,
25479                                     SmallVectorImpl<SDValue> &Results) {
25480   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
25481   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
25482   // and the EAX register is loaded with the low-order 32 bits.
25483   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
25484                                              /* NoRegister */0, Subtarget,
25485                                              Results);
25486   if (Opcode != X86::RDTSCP)
25487     return;
25488 
25489   SDValue Chain = Results[1];
25490   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
25491   // the ECX register. Add 'ecx' explicitly to the chain.
25492   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
25493   Results[1] = ecx;
25494   Results.push_back(ecx.getValue(1));
25495 }
25496 
LowerREADCYCLECOUNTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25497 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
25498                                      SelectionDAG &DAG) {
25499   SmallVector<SDValue, 3> Results;
25500   SDLoc DL(Op);
25501   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
25502                           Results);
25503   return DAG.getMergeValues(Results, DL);
25504 }
25505 
MarkEHRegistrationNode(SDValue Op,SelectionDAG & DAG)25506 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
25507   MachineFunction &MF = DAG.getMachineFunction();
25508   SDValue Chain = Op.getOperand(0);
25509   SDValue RegNode = Op.getOperand(2);
25510   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
25511   if (!EHInfo)
25512     report_fatal_error("EH registrations only live in functions using WinEH");
25513 
25514   // Cast the operand to an alloca, and remember the frame index.
25515   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
25516   if (!FINode)
25517     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
25518   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
25519 
25520   // Return the chain operand without making any DAG nodes.
25521   return Chain;
25522 }
25523 
MarkEHGuard(SDValue Op,SelectionDAG & DAG)25524 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
25525   MachineFunction &MF = DAG.getMachineFunction();
25526   SDValue Chain = Op.getOperand(0);
25527   SDValue EHGuard = Op.getOperand(2);
25528   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
25529   if (!EHInfo)
25530     report_fatal_error("EHGuard only live in functions using WinEH");
25531 
25532   // Cast the operand to an alloca, and remember the frame index.
25533   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
25534   if (!FINode)
25535     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
25536   EHInfo->EHGuardFrameIndex = FINode->getIndex();
25537 
25538   // Return the chain operand without making any DAG nodes.
25539   return Chain;
25540 }
25541 
25542 /// Emit Truncating Store with signed or unsigned saturation.
25543 static SDValue
EmitTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & Dl,SDValue Val,SDValue Ptr,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)25544 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
25545                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
25546                 SelectionDAG &DAG) {
25547   SDVTList VTs = DAG.getVTList(MVT::Other);
25548   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
25549   SDValue Ops[] = { Chain, Val, Ptr, Undef };
25550   unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
25551   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
25552 }
25553 
25554 /// Emit Masked Truncating Store with signed or unsigned saturation.
25555 static SDValue
EmitMaskedTruncSStore(bool SignedSat,SDValue Chain,const SDLoc & Dl,SDValue Val,SDValue Ptr,SDValue Mask,EVT MemVT,MachineMemOperand * MMO,SelectionDAG & DAG)25556 EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
25557                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
25558                       MachineMemOperand *MMO, SelectionDAG &DAG) {
25559   SDVTList VTs = DAG.getVTList(MVT::Other);
25560   SDValue Ops[] = { Chain, Val, Ptr, Mask };
25561   unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
25562   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
25563 }
25564 
LowerINTRINSIC_W_CHAIN(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)25565 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
25566                                       SelectionDAG &DAG) {
25567   unsigned IntNo = Op.getConstantOperandVal(1);
25568   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
25569   if (!IntrData) {
25570     switch (IntNo) {
25571     case llvm::Intrinsic::x86_seh_ehregnode:
25572       return MarkEHRegistrationNode(Op, DAG);
25573     case llvm::Intrinsic::x86_seh_ehguard:
25574       return MarkEHGuard(Op, DAG);
25575     case llvm::Intrinsic::x86_rdpkru: {
25576       SDLoc dl(Op);
25577       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
25578       // Create a RDPKRU node and pass 0 to the ECX parameter.
25579       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
25580                          DAG.getConstant(0, dl, MVT::i32));
25581     }
25582     case llvm::Intrinsic::x86_wrpkru: {
25583       SDLoc dl(Op);
25584       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
25585       // to the EDX and ECX parameters.
25586       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
25587                          Op.getOperand(0), Op.getOperand(2),
25588                          DAG.getConstant(0, dl, MVT::i32),
25589                          DAG.getConstant(0, dl, MVT::i32));
25590     }
25591     case llvm::Intrinsic::x86_flags_read_u32:
25592     case llvm::Intrinsic::x86_flags_read_u64:
25593     case llvm::Intrinsic::x86_flags_write_u32:
25594     case llvm::Intrinsic::x86_flags_write_u64: {
25595       // We need a frame pointer because this will get lowered to a PUSH/POP
25596       // sequence.
25597       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
25598       MFI.setHasCopyImplyingStackAdjustment(true);
25599       // Don't do anything here, we will expand these intrinsics out later
25600       // during FinalizeISel in EmitInstrWithCustomInserter.
25601       return Op;
25602     }
25603     case Intrinsic::x86_lwpins32:
25604     case Intrinsic::x86_lwpins64:
25605     case Intrinsic::x86_umwait:
25606     case Intrinsic::x86_tpause: {
25607       SDLoc dl(Op);
25608       SDValue Chain = Op->getOperand(0);
25609       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
25610       unsigned Opcode;
25611 
25612       switch (IntNo) {
25613       default: llvm_unreachable("Impossible intrinsic");
25614       case Intrinsic::x86_umwait:
25615         Opcode = X86ISD::UMWAIT;
25616         break;
25617       case Intrinsic::x86_tpause:
25618         Opcode = X86ISD::TPAUSE;
25619         break;
25620       case Intrinsic::x86_lwpins32:
25621       case Intrinsic::x86_lwpins64:
25622         Opcode = X86ISD::LWPINS;
25623         break;
25624       }
25625 
25626       SDValue Operation =
25627           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
25628                       Op->getOperand(3), Op->getOperand(4));
25629       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
25630       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
25631                          Operation.getValue(1));
25632     }
25633     case Intrinsic::x86_enqcmd:
25634     case Intrinsic::x86_enqcmds: {
25635       SDLoc dl(Op);
25636       SDValue Chain = Op.getOperand(0);
25637       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
25638       unsigned Opcode;
25639       switch (IntNo) {
25640       default: llvm_unreachable("Impossible intrinsic!");
25641       case Intrinsic::x86_enqcmd:
25642         Opcode = X86ISD::ENQCMD;
25643         break;
25644       case Intrinsic::x86_enqcmds:
25645         Opcode = X86ISD::ENQCMDS;
25646         break;
25647       }
25648       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
25649                                       Op.getOperand(3));
25650       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
25651       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
25652                          Operation.getValue(1));
25653     }
25654     }
25655     return SDValue();
25656   }
25657 
25658   SDLoc dl(Op);
25659   switch(IntrData->Type) {
25660   default: llvm_unreachable("Unknown Intrinsic Type");
25661   case RDSEED:
25662   case RDRAND: {
25663     // Emit the node with the right value type.
25664     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
25665     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
25666 
25667     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
25668     // Otherwise return the value from Rand, which is always 0, casted to i32.
25669     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
25670                      DAG.getConstant(1, dl, Op->getValueType(1)),
25671                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
25672                      SDValue(Result.getNode(), 1)};
25673     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
25674 
25675     // Return { result, isValid, chain }.
25676     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
25677                        SDValue(Result.getNode(), 2));
25678   }
25679   case GATHER_AVX2: {
25680     SDValue Chain = Op.getOperand(0);
25681     SDValue Src   = Op.getOperand(2);
25682     SDValue Base  = Op.getOperand(3);
25683     SDValue Index = Op.getOperand(4);
25684     SDValue Mask  = Op.getOperand(5);
25685     SDValue Scale = Op.getOperand(6);
25686     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
25687                              Scale, Chain, Subtarget);
25688   }
25689   case GATHER: {
25690   //gather(v1, mask, index, base, scale);
25691     SDValue Chain = Op.getOperand(0);
25692     SDValue Src   = Op.getOperand(2);
25693     SDValue Base  = Op.getOperand(3);
25694     SDValue Index = Op.getOperand(4);
25695     SDValue Mask  = Op.getOperand(5);
25696     SDValue Scale = Op.getOperand(6);
25697     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
25698                          Chain, Subtarget);
25699   }
25700   case SCATTER: {
25701   //scatter(base, mask, index, v1, scale);
25702     SDValue Chain = Op.getOperand(0);
25703     SDValue Base  = Op.getOperand(2);
25704     SDValue Mask  = Op.getOperand(3);
25705     SDValue Index = Op.getOperand(4);
25706     SDValue Src   = Op.getOperand(5);
25707     SDValue Scale = Op.getOperand(6);
25708     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
25709                           Scale, Chain, Subtarget);
25710   }
25711   case PREFETCH: {
25712     const APInt &HintVal = Op.getConstantOperandAPInt(6);
25713     assert((HintVal == 2 || HintVal == 3) &&
25714            "Wrong prefetch hint in intrinsic: should be 2 or 3");
25715     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
25716     SDValue Chain = Op.getOperand(0);
25717     SDValue Mask  = Op.getOperand(2);
25718     SDValue Index = Op.getOperand(3);
25719     SDValue Base  = Op.getOperand(4);
25720     SDValue Scale = Op.getOperand(5);
25721     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
25722                            Subtarget);
25723   }
25724   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
25725   case RDTSC: {
25726     SmallVector<SDValue, 2> Results;
25727     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
25728                             Results);
25729     return DAG.getMergeValues(Results, dl);
25730   }
25731   // Read Performance Monitoring Counters.
25732   case RDPMC:
25733   // GetExtended Control Register.
25734   case XGETBV: {
25735     SmallVector<SDValue, 2> Results;
25736 
25737     // RDPMC uses ECX to select the index of the performance counter to read.
25738     // XGETBV uses ECX to select the index of the XCR register to return.
25739     // The result is stored into registers EDX:EAX.
25740     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
25741                                 Subtarget, Results);
25742     return DAG.getMergeValues(Results, dl);
25743   }
25744   // XTEST intrinsics.
25745   case XTEST: {
25746     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
25747     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
25748 
25749     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
25750     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
25751     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
25752                        Ret, SDValue(InTrans.getNode(), 1));
25753   }
25754   case TRUNCATE_TO_MEM_VI8:
25755   case TRUNCATE_TO_MEM_VI16:
25756   case TRUNCATE_TO_MEM_VI32: {
25757     SDValue Mask = Op.getOperand(4);
25758     SDValue DataToTruncate = Op.getOperand(3);
25759     SDValue Addr = Op.getOperand(2);
25760     SDValue Chain = Op.getOperand(0);
25761 
25762     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
25763     assert(MemIntr && "Expected MemIntrinsicSDNode!");
25764 
25765     EVT MemVT  = MemIntr->getMemoryVT();
25766 
25767     uint16_t TruncationOp = IntrData->Opc0;
25768     switch (TruncationOp) {
25769     case X86ISD::VTRUNC: {
25770       if (isAllOnesConstant(Mask)) // return just a truncate store
25771         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
25772                                  MemIntr->getMemOperand());
25773 
25774       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
25775       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25776       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
25777 
25778       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
25779                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
25780                                 true /* truncating */);
25781     }
25782     case X86ISD::VTRUNCUS:
25783     case X86ISD::VTRUNCS: {
25784       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
25785       if (isAllOnesConstant(Mask))
25786         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
25787                                MemIntr->getMemOperand(), DAG);
25788 
25789       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
25790       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25791 
25792       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
25793                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
25794     }
25795     default:
25796       llvm_unreachable("Unsupported truncstore intrinsic");
25797     }
25798   }
25799   }
25800 }
25801 
LowerRETURNADDR(SDValue Op,SelectionDAG & DAG) const25802 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
25803                                            SelectionDAG &DAG) const {
25804   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
25805   MFI.setReturnAddressIsTaken(true);
25806 
25807   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
25808     return SDValue();
25809 
25810   unsigned Depth = Op.getConstantOperandVal(0);
25811   SDLoc dl(Op);
25812   EVT PtrVT = getPointerTy(DAG.getDataLayout());
25813 
25814   if (Depth > 0) {
25815     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
25816     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25817     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
25818     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
25819                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
25820                        MachinePointerInfo());
25821   }
25822 
25823   // Just load the return address.
25824   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
25825   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
25826                      MachinePointerInfo());
25827 }
25828 
LowerADDROFRETURNADDR(SDValue Op,SelectionDAG & DAG) const25829 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
25830                                                  SelectionDAG &DAG) const {
25831   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
25832   return getReturnAddressFrameIndex(DAG);
25833 }
25834 
LowerFRAMEADDR(SDValue Op,SelectionDAG & DAG) const25835 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
25836   MachineFunction &MF = DAG.getMachineFunction();
25837   MachineFrameInfo &MFI = MF.getFrameInfo();
25838   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
25839   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25840   EVT VT = Op.getValueType();
25841 
25842   MFI.setFrameAddressIsTaken(true);
25843 
25844   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
25845     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
25846     // is not possible to crawl up the stack without looking at the unwind codes
25847     // simultaneously.
25848     int FrameAddrIndex = FuncInfo->getFAIndex();
25849     if (!FrameAddrIndex) {
25850       // Set up a frame object for the return address.
25851       unsigned SlotSize = RegInfo->getSlotSize();
25852       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
25853           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
25854       FuncInfo->setFAIndex(FrameAddrIndex);
25855     }
25856     return DAG.getFrameIndex(FrameAddrIndex, VT);
25857   }
25858 
25859   unsigned FrameReg =
25860       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
25861   SDLoc dl(Op);  // FIXME probably not meaningful
25862   unsigned Depth = Op.getConstantOperandVal(0);
25863   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
25864           (FrameReg == X86::EBP && VT == MVT::i32)) &&
25865          "Invalid Frame Register!");
25866   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
25867   while (Depth--)
25868     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
25869                             MachinePointerInfo());
25870   return FrameAddr;
25871 }
25872 
25873 // FIXME? Maybe this could be a TableGen attribute on some registers and
25874 // this table could be generated automatically from RegInfo.
getRegisterByName(const char * RegName,LLT VT,const MachineFunction & MF) const25875 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
25876                                               const MachineFunction &MF) const {
25877   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
25878 
25879   Register Reg = StringSwitch<unsigned>(RegName)
25880                        .Case("esp", X86::ESP)
25881                        .Case("rsp", X86::RSP)
25882                        .Case("ebp", X86::EBP)
25883                        .Case("rbp", X86::RBP)
25884                        .Default(0);
25885 
25886   if (Reg == X86::EBP || Reg == X86::RBP) {
25887     if (!TFI.hasFP(MF))
25888       report_fatal_error("register " + StringRef(RegName) +
25889                          " is allocatable: function has no frame pointer");
25890 #ifndef NDEBUG
25891     else {
25892       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25893       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
25894       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
25895              "Invalid Frame Register!");
25896     }
25897 #endif
25898   }
25899 
25900   if (Reg)
25901     return Reg;
25902 
25903   report_fatal_error("Invalid register name global variable");
25904 }
25905 
LowerFRAME_TO_ARGS_OFFSET(SDValue Op,SelectionDAG & DAG) const25906 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
25907                                                      SelectionDAG &DAG) const {
25908   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25909   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
25910 }
25911 
getExceptionPointerRegister(const Constant * PersonalityFn) const25912 Register X86TargetLowering::getExceptionPointerRegister(
25913     const Constant *PersonalityFn) const {
25914   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
25915     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
25916 
25917   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
25918 }
25919 
getExceptionSelectorRegister(const Constant * PersonalityFn) const25920 Register X86TargetLowering::getExceptionSelectorRegister(
25921     const Constant *PersonalityFn) const {
25922   // Funclet personalities don't use selectors (the runtime does the selection).
25923   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
25924   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
25925 }
25926 
needsFixedCatchObjects() const25927 bool X86TargetLowering::needsFixedCatchObjects() const {
25928   return Subtarget.isTargetWin64();
25929 }
25930 
LowerEH_RETURN(SDValue Op,SelectionDAG & DAG) const25931 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
25932   SDValue Chain     = Op.getOperand(0);
25933   SDValue Offset    = Op.getOperand(1);
25934   SDValue Handler   = Op.getOperand(2);
25935   SDLoc dl      (Op);
25936 
25937   EVT PtrVT = getPointerTy(DAG.getDataLayout());
25938   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25939   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
25940   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
25941           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
25942          "Invalid Frame Register!");
25943   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
25944   Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
25945 
25946   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
25947                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
25948                                                        dl));
25949   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
25950   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
25951   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
25952 
25953   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
25954                      DAG.getRegister(StoreAddrReg, PtrVT));
25955 }
25956 
lowerEH_SJLJ_SETJMP(SDValue Op,SelectionDAG & DAG) const25957 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
25958                                                SelectionDAG &DAG) const {
25959   SDLoc DL(Op);
25960   // If the subtarget is not 64bit, we may need the global base reg
25961   // after isel expand pseudo, i.e., after CGBR pass ran.
25962   // Therefore, ask for the GlobalBaseReg now, so that the pass
25963   // inserts the code for us in case we need it.
25964   // Otherwise, we will end up in a situation where we will
25965   // reference a virtual register that is not defined!
25966   if (!Subtarget.is64Bit()) {
25967     const X86InstrInfo *TII = Subtarget.getInstrInfo();
25968     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
25969   }
25970   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
25971                      DAG.getVTList(MVT::i32, MVT::Other),
25972                      Op.getOperand(0), Op.getOperand(1));
25973 }
25974 
lowerEH_SJLJ_LONGJMP(SDValue Op,SelectionDAG & DAG) const25975 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
25976                                                 SelectionDAG &DAG) const {
25977   SDLoc DL(Op);
25978   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
25979                      Op.getOperand(0), Op.getOperand(1));
25980 }
25981 
lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,SelectionDAG & DAG) const25982 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
25983                                                        SelectionDAG &DAG) const {
25984   SDLoc DL(Op);
25985   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
25986                      Op.getOperand(0));
25987 }
25988 
LowerADJUST_TRAMPOLINE(SDValue Op,SelectionDAG & DAG)25989 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
25990   return Op.getOperand(0);
25991 }
25992 
LowerINIT_TRAMPOLINE(SDValue Op,SelectionDAG & DAG) const25993 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
25994                                                 SelectionDAG &DAG) const {
25995   SDValue Root = Op.getOperand(0);
25996   SDValue Trmp = Op.getOperand(1); // trampoline
25997   SDValue FPtr = Op.getOperand(2); // nested function
25998   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
25999   SDLoc dl (Op);
26000 
26001   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
26002   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
26003 
26004   if (Subtarget.is64Bit()) {
26005     SDValue OutChains[6];
26006 
26007     // Large code-model.
26008     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
26009     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
26010 
26011     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
26012     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
26013 
26014     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
26015 
26016     // Load the pointer to the nested function into R11.
26017     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
26018     SDValue Addr = Trmp;
26019     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26020                                 Addr, MachinePointerInfo(TrmpAddr));
26021 
26022     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26023                        DAG.getConstant(2, dl, MVT::i64));
26024     OutChains[1] =
26025         DAG.getStore(Root, dl, FPtr, Addr, MachinePointerInfo(TrmpAddr, 2),
26026                      /* Alignment = */ 2);
26027 
26028     // Load the 'nest' parameter value into R10.
26029     // R10 is specified in X86CallingConv.td
26030     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
26031     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26032                        DAG.getConstant(10, dl, MVT::i64));
26033     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26034                                 Addr, MachinePointerInfo(TrmpAddr, 10));
26035 
26036     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26037                        DAG.getConstant(12, dl, MVT::i64));
26038     OutChains[3] =
26039         DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 12),
26040                      /* Alignment = */ 2);
26041 
26042     // Jump to the nested function.
26043     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
26044     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26045                        DAG.getConstant(20, dl, MVT::i64));
26046     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26047                                 Addr, MachinePointerInfo(TrmpAddr, 20));
26048 
26049     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
26050     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26051                        DAG.getConstant(22, dl, MVT::i64));
26052     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
26053                                 Addr, MachinePointerInfo(TrmpAddr, 22));
26054 
26055     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
26056   } else {
26057     const Function *Func =
26058       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
26059     CallingConv::ID CC = Func->getCallingConv();
26060     unsigned NestReg;
26061 
26062     switch (CC) {
26063     default:
26064       llvm_unreachable("Unsupported calling convention");
26065     case CallingConv::C:
26066     case CallingConv::X86_StdCall: {
26067       // Pass 'nest' parameter in ECX.
26068       // Must be kept in sync with X86CallingConv.td
26069       NestReg = X86::ECX;
26070 
26071       // Check that ECX wasn't needed by an 'inreg' parameter.
26072       FunctionType *FTy = Func->getFunctionType();
26073       const AttributeList &Attrs = Func->getAttributes();
26074 
26075       if (!Attrs.isEmpty() && !Func->isVarArg()) {
26076         unsigned InRegCount = 0;
26077         unsigned Idx = 1;
26078 
26079         for (FunctionType::param_iterator I = FTy->param_begin(),
26080              E = FTy->param_end(); I != E; ++I, ++Idx)
26081           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
26082             auto &DL = DAG.getDataLayout();
26083             // FIXME: should only count parameters that are lowered to integers.
26084             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
26085           }
26086 
26087         if (InRegCount > 2) {
26088           report_fatal_error("Nest register in use - reduce number of inreg"
26089                              " parameters!");
26090         }
26091       }
26092       break;
26093     }
26094     case CallingConv::X86_FastCall:
26095     case CallingConv::X86_ThisCall:
26096     case CallingConv::Fast:
26097     case CallingConv::Tail:
26098       // Pass 'nest' parameter in EAX.
26099       // Must be kept in sync with X86CallingConv.td
26100       NestReg = X86::EAX;
26101       break;
26102     }
26103 
26104     SDValue OutChains[4];
26105     SDValue Addr, Disp;
26106 
26107     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26108                        DAG.getConstant(10, dl, MVT::i32));
26109     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
26110 
26111     // This is storing the opcode for MOV32ri.
26112     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
26113     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
26114     OutChains[0] =
26115         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
26116                      Trmp, MachinePointerInfo(TrmpAddr));
26117 
26118     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26119                        DAG.getConstant(1, dl, MVT::i32));
26120     OutChains[1] =
26121         DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 1),
26122                      /* Alignment = */ 1);
26123 
26124     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
26125     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26126                        DAG.getConstant(5, dl, MVT::i32));
26127     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
26128                                 Addr, MachinePointerInfo(TrmpAddr, 5),
26129                                 /* Alignment = */ 1);
26130 
26131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26132                        DAG.getConstant(6, dl, MVT::i32));
26133     OutChains[3] =
26134         DAG.getStore(Root, dl, Disp, Addr, MachinePointerInfo(TrmpAddr, 6),
26135                      /* Alignment = */ 1);
26136 
26137     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
26138   }
26139 }
26140 
LowerFLT_ROUNDS_(SDValue Op,SelectionDAG & DAG) const26141 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
26142                                             SelectionDAG &DAG) const {
26143   /*
26144    The rounding mode is in bits 11:10 of FPSR, and has the following
26145    settings:
26146      00 Round to nearest
26147      01 Round to -inf
26148      10 Round to +inf
26149      11 Round to 0
26150 
26151   FLT_ROUNDS, on the other hand, expects the following:
26152     -1 Undefined
26153      0 Round to 0
26154      1 Round to nearest
26155      2 Round to +inf
26156      3 Round to -inf
26157 
26158   To perform the conversion, we use a packed lookup table of the four 2-bit
26159   values that we can index by FPSP[11:10]
26160     0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
26161 
26162     (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
26163   */
26164 
26165   MachineFunction &MF = DAG.getMachineFunction();
26166   MVT VT = Op.getSimpleValueType();
26167   SDLoc DL(Op);
26168 
26169   // Save FP Control Word to stack slot
26170   int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
26171   SDValue StackSlot =
26172       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
26173 
26174   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
26175 
26176   SDValue Chain = Op.getOperand(0);
26177   SDValue Ops[] = {Chain, StackSlot};
26178   Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
26179                                   DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
26180                                   Align(2), MachineMemOperand::MOStore);
26181 
26182   // Load FP Control Word from stack slot
26183   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
26184   Chain = CWD.getValue(1);
26185 
26186   // Mask and turn the control bits into a shift for the lookup table.
26187   SDValue Shift =
26188     DAG.getNode(ISD::SRL, DL, MVT::i16,
26189                 DAG.getNode(ISD::AND, DL, MVT::i16,
26190                             CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
26191                 DAG.getConstant(9, DL, MVT::i8));
26192   Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
26193 
26194   SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
26195   SDValue RetVal =
26196     DAG.getNode(ISD::AND, DL, MVT::i32,
26197                 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
26198                 DAG.getConstant(3, DL, MVT::i32));
26199 
26200   RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
26201 
26202   return DAG.getMergeValues({RetVal, Chain}, DL);
26203 }
26204 
26205 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
26206 //
26207 // i8/i16 vector implemented using dword LZCNT vector instruction
26208 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
26209 // split the vector, perform operation on it's Lo a Hi part and
26210 // concatenate the results.
LowerVectorCTLZ_AVX512CDI(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)26211 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
26212                                          const X86Subtarget &Subtarget) {
26213   assert(Op.getOpcode() == ISD::CTLZ);
26214   SDLoc dl(Op);
26215   MVT VT = Op.getSimpleValueType();
26216   MVT EltVT = VT.getVectorElementType();
26217   unsigned NumElems = VT.getVectorNumElements();
26218 
26219   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
26220           "Unsupported element type");
26221 
26222   // Split vector, it's Lo and Hi parts will be handled in next iteration.
26223   if (NumElems > 16 ||
26224       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
26225     return splitVectorIntUnary(Op, DAG);
26226 
26227   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
26228   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
26229           "Unsupported value type for operation");
26230 
26231   // Use native supported vector instruction vplzcntd.
26232   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
26233   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
26234   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
26235   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
26236 
26237   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
26238 }
26239 
26240 // Lower CTLZ using a PSHUFB lookup table implementation.
LowerVectorCTLZInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)26241 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
26242                                        const X86Subtarget &Subtarget,
26243                                        SelectionDAG &DAG) {
26244   MVT VT = Op.getSimpleValueType();
26245   int NumElts = VT.getVectorNumElements();
26246   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
26247   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
26248 
26249   // Per-nibble leading zero PSHUFB lookup table.
26250   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
26251                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
26252                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
26253                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
26254 
26255   SmallVector<SDValue, 64> LUTVec;
26256   for (int i = 0; i < NumBytes; ++i)
26257     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
26258   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
26259 
26260   // Begin by bitcasting the input to byte vector, then split those bytes
26261   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
26262   // If the hi input nibble is zero then we add both results together, otherwise
26263   // we just take the hi result (by masking the lo result to zero before the
26264   // add).
26265   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
26266   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
26267 
26268   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
26269   SDValue Lo = Op0;
26270   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
26271   SDValue HiZ;
26272   if (CurrVT.is512BitVector()) {
26273     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
26274     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
26275     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
26276   } else {
26277     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
26278   }
26279 
26280   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
26281   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
26282   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
26283   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
26284 
26285   // Merge result back from vXi8 back to VT, working on the lo/hi halves
26286   // of the current vector width in the same way we did for the nibbles.
26287   // If the upper half of the input element is zero then add the halves'
26288   // leading zero counts together, otherwise just use the upper half's.
26289   // Double the width of the result until we are at target width.
26290   while (CurrVT != VT) {
26291     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
26292     int CurrNumElts = CurrVT.getVectorNumElements();
26293     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
26294     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
26295     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
26296 
26297     // Check if the upper half of the input element is zero.
26298     if (CurrVT.is512BitVector()) {
26299       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
26300       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
26301                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
26302       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
26303     } else {
26304       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
26305                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
26306     }
26307     HiZ = DAG.getBitcast(NextVT, HiZ);
26308 
26309     // Move the upper/lower halves to the lower bits as we'll be extending to
26310     // NextVT. Mask the lower result to zero if HiZ is true and add the results
26311     // together.
26312     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
26313     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
26314     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
26315     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
26316     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
26317     CurrVT = NextVT;
26318   }
26319 
26320   return Res;
26321 }
26322 
LowerVectorCTLZ(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)26323 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
26324                                const X86Subtarget &Subtarget,
26325                                SelectionDAG &DAG) {
26326   MVT VT = Op.getSimpleValueType();
26327 
26328   if (Subtarget.hasCDI() &&
26329       // vXi8 vectors need to be promoted to 512-bits for vXi32.
26330       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
26331     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
26332 
26333   // Decompose 256-bit ops into smaller 128-bit ops.
26334   if (VT.is256BitVector() && !Subtarget.hasInt256())
26335     return splitVectorIntUnary(Op, DAG);
26336 
26337   // Decompose 512-bit ops into smaller 256-bit ops.
26338   if (VT.is512BitVector() && !Subtarget.hasBWI())
26339     return splitVectorIntUnary(Op, DAG);
26340 
26341   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
26342   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
26343 }
26344 
LowerCTLZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26345 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
26346                          SelectionDAG &DAG) {
26347   MVT VT = Op.getSimpleValueType();
26348   MVT OpVT = VT;
26349   unsigned NumBits = VT.getSizeInBits();
26350   SDLoc dl(Op);
26351   unsigned Opc = Op.getOpcode();
26352 
26353   if (VT.isVector())
26354     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
26355 
26356   Op = Op.getOperand(0);
26357   if (VT == MVT::i8) {
26358     // Zero extend to i32 since there is not an i8 bsr.
26359     OpVT = MVT::i32;
26360     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
26361   }
26362 
26363   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
26364   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
26365   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
26366 
26367   if (Opc == ISD::CTLZ) {
26368     // If src is zero (i.e. bsr sets ZF), returns NumBits.
26369     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
26370                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
26371                      Op.getValue(1)};
26372     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
26373   }
26374 
26375   // Finally xor with NumBits-1.
26376   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
26377                    DAG.getConstant(NumBits - 1, dl, OpVT));
26378 
26379   if (VT == MVT::i8)
26380     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
26381   return Op;
26382 }
26383 
LowerCTTZ(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26384 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
26385                          SelectionDAG &DAG) {
26386   MVT VT = Op.getSimpleValueType();
26387   unsigned NumBits = VT.getScalarSizeInBits();
26388   SDValue N0 = Op.getOperand(0);
26389   SDLoc dl(Op);
26390 
26391   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
26392          "Only scalar CTTZ requires custom lowering");
26393 
26394   // Issue a bsf (scan bits forward) which also sets EFLAGS.
26395   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
26396   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
26397 
26398   // If src is zero (i.e. bsf sets ZF), returns NumBits.
26399   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
26400                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
26401                    Op.getValue(1)};
26402   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
26403 }
26404 
lowerAddSub(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)26405 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
26406                            const X86Subtarget &Subtarget) {
26407   MVT VT = Op.getSimpleValueType();
26408   if (VT == MVT::i16 || VT == MVT::i32)
26409     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
26410 
26411   if (VT.getScalarType() == MVT::i1)
26412     return DAG.getNode(ISD::XOR, SDLoc(Op), VT,
26413                        Op.getOperand(0), Op.getOperand(1));
26414 
26415   if (VT == MVT::v32i16 || VT == MVT::v64i8)
26416     return splitVectorIntBinary(Op, DAG);
26417 
26418   assert(Op.getSimpleValueType().is256BitVector() &&
26419          Op.getSimpleValueType().isInteger() &&
26420          "Only handle AVX 256-bit vector integer operation");
26421   return splitVectorIntBinary(Op, DAG);
26422 }
26423 
LowerADDSAT_SUBSAT(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)26424 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
26425                                   const X86Subtarget &Subtarget) {
26426   MVT VT = Op.getSimpleValueType();
26427   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
26428   unsigned Opcode = Op.getOpcode();
26429   if (VT.getScalarType() == MVT::i1) {
26430     SDLoc dl(Op);
26431     switch (Opcode) {
26432     default: llvm_unreachable("Expected saturated arithmetic opcode");
26433     case ISD::UADDSAT:
26434     case ISD::SADDSAT:
26435       // *addsat i1 X, Y --> X | Y
26436       return DAG.getNode(ISD::OR, dl, VT, X, Y);
26437     case ISD::USUBSAT:
26438     case ISD::SSUBSAT:
26439       // *subsat i1 X, Y --> X & ~Y
26440       return DAG.getNode(ISD::AND, dl, VT, X, DAG.getNOT(dl, Y, VT));
26441     }
26442   }
26443 
26444   if (VT.is128BitVector()) {
26445     // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
26446     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26447     EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
26448                                                  *DAG.getContext(), VT);
26449     SDLoc DL(Op);
26450     if (Opcode == ISD::UADDSAT && !TLI.isOperationLegal(ISD::UMIN, VT)) {
26451       // uaddsat X, Y --> (X >u (X + Y)) ? -1 : X + Y
26452       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, X, Y);
26453       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Add, ISD::SETUGT);
26454       return DAG.getSelect(DL, VT, Cmp, DAG.getAllOnesConstant(DL, VT), Add);
26455     }
26456     if (Opcode == ISD::USUBSAT && !TLI.isOperationLegal(ISD::UMAX, VT)) {
26457       // usubsat X, Y --> (X >u Y) ? X - Y : 0
26458       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
26459       SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
26460       return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
26461     }
26462     // Use default expansion.
26463     return SDValue();
26464   }
26465 
26466   if (VT == MVT::v32i16 || VT == MVT::v64i8)
26467     return splitVectorIntBinary(Op, DAG);
26468 
26469   assert(Op.getSimpleValueType().is256BitVector() &&
26470          Op.getSimpleValueType().isInteger() &&
26471          "Only handle AVX 256-bit vector integer operation");
26472   return splitVectorIntBinary(Op, DAG);
26473 }
26474 
LowerABS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26475 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
26476                         SelectionDAG &DAG) {
26477   MVT VT = Op.getSimpleValueType();
26478   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
26479     // Since X86 does not have CMOV for 8-bit integer, we don't convert
26480     // 8-bit integer abs to NEG and CMOV.
26481     SDLoc DL(Op);
26482     SDValue N0 = Op.getOperand(0);
26483     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
26484                               DAG.getConstant(0, DL, VT), N0);
26485     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_GE, DL, MVT::i8),
26486                      SDValue(Neg.getNode(), 1)};
26487     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
26488   }
26489 
26490   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
26491   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
26492     SDLoc DL(Op);
26493     SDValue Src = Op.getOperand(0);
26494     SDValue Sub =
26495         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
26496     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
26497   }
26498 
26499   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
26500     assert(VT.isInteger() &&
26501            "Only handle AVX 256-bit vector integer operation");
26502     return splitVectorIntUnary(Op, DAG);
26503   }
26504 
26505   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
26506     return splitVectorIntUnary(Op, DAG);
26507 
26508   // Default to expand.
26509   return SDValue();
26510 }
26511 
LowerMINMAX(SDValue Op,SelectionDAG & DAG)26512 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
26513   MVT VT = Op.getSimpleValueType();
26514 
26515   // For AVX1 cases, split to use legal ops (everything but v4i64).
26516   if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
26517     return splitVectorIntBinary(Op, DAG);
26518 
26519   if (VT == MVT::v32i16 || VT == MVT::v64i8)
26520     return splitVectorIntBinary(Op, DAG);
26521 
26522   SDLoc DL(Op);
26523   unsigned Opcode = Op.getOpcode();
26524   SDValue N0 = Op.getOperand(0);
26525   SDValue N1 = Op.getOperand(1);
26526 
26527   // For pre-SSE41, we can perform UMIN/UMAX v8i16 by flipping the signbit,
26528   // using the SMIN/SMAX instructions and flipping the signbit back.
26529   if (VT == MVT::v8i16) {
26530     assert((Opcode == ISD::UMIN || Opcode == ISD::UMAX) &&
26531            "Unexpected MIN/MAX opcode");
26532     SDValue Sign = DAG.getConstant(APInt::getSignedMinValue(16), DL, VT);
26533     N0 = DAG.getNode(ISD::XOR, DL, VT, N0, Sign);
26534     N1 = DAG.getNode(ISD::XOR, DL, VT, N1, Sign);
26535     Opcode = (Opcode == ISD::UMIN ? ISD::SMIN : ISD::SMAX);
26536     SDValue Result = DAG.getNode(Opcode, DL, VT, N0, N1);
26537     return DAG.getNode(ISD::XOR, DL, VT, Result, Sign);
26538   }
26539 
26540   // Else, expand to a compare/select.
26541   ISD::CondCode CC;
26542   switch (Opcode) {
26543   case ISD::SMIN: CC = ISD::CondCode::SETLT;  break;
26544   case ISD::SMAX: CC = ISD::CondCode::SETGT;  break;
26545   case ISD::UMIN: CC = ISD::CondCode::SETULT; break;
26546   case ISD::UMAX: CC = ISD::CondCode::SETUGT; break;
26547   default: llvm_unreachable("Unknown MINMAX opcode");
26548   }
26549 
26550   SDValue Cond = DAG.getSetCC(DL, VT, N0, N1, CC);
26551   return DAG.getSelect(DL, VT, Cond, N0, N1);
26552 }
26553 
LowerMUL(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26554 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
26555                         SelectionDAG &DAG) {
26556   SDLoc dl(Op);
26557   MVT VT = Op.getSimpleValueType();
26558 
26559   if (VT.getScalarType() == MVT::i1)
26560     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
26561 
26562   // Decompose 256-bit ops into 128-bit ops.
26563   if (VT.is256BitVector() && !Subtarget.hasInt256())
26564     return splitVectorIntBinary(Op, DAG);
26565 
26566   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
26567     return splitVectorIntBinary(Op, DAG);
26568 
26569   SDValue A = Op.getOperand(0);
26570   SDValue B = Op.getOperand(1);
26571 
26572   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
26573   // vector pairs, multiply and truncate.
26574   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
26575     unsigned NumElts = VT.getVectorNumElements();
26576 
26577     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
26578         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
26579       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
26580       return DAG.getNode(
26581           ISD::TRUNCATE, dl, VT,
26582           DAG.getNode(ISD::MUL, dl, ExVT,
26583                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
26584                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
26585     }
26586 
26587     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
26588 
26589     // Extract the lo/hi parts to any extend to i16.
26590     // We're going to mask off the low byte of each result element of the
26591     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
26592     // element.
26593     SDValue Undef = DAG.getUNDEF(VT);
26594     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
26595     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
26596 
26597     SDValue BLo, BHi;
26598     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
26599       // If the LHS is a constant, manually unpackl/unpackh.
26600       SmallVector<SDValue, 16> LoOps, HiOps;
26601       for (unsigned i = 0; i != NumElts; i += 16) {
26602         for (unsigned j = 0; j != 8; ++j) {
26603           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
26604                                                MVT::i16));
26605           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
26606                                                MVT::i16));
26607         }
26608       }
26609 
26610       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
26611       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
26612     } else {
26613       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
26614       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
26615     }
26616 
26617     // Multiply, mask the lower 8bits of the lo/hi results and pack.
26618     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
26619     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
26620     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
26621     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
26622     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
26623   }
26624 
26625   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
26626   if (VT == MVT::v4i32) {
26627     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
26628            "Should not custom lower when pmulld is available!");
26629 
26630     // Extract the odd parts.
26631     static const int UnpackMask[] = { 1, -1, 3, -1 };
26632     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
26633     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
26634 
26635     // Multiply the even parts.
26636     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
26637                                 DAG.getBitcast(MVT::v2i64, A),
26638                                 DAG.getBitcast(MVT::v2i64, B));
26639     // Now multiply odd parts.
26640     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
26641                                DAG.getBitcast(MVT::v2i64, Aodds),
26642                                DAG.getBitcast(MVT::v2i64, Bodds));
26643 
26644     Evens = DAG.getBitcast(VT, Evens);
26645     Odds = DAG.getBitcast(VT, Odds);
26646 
26647     // Merge the two vectors back together with a shuffle. This expands into 2
26648     // shuffles.
26649     static const int ShufMask[] = { 0, 4, 2, 6 };
26650     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
26651   }
26652 
26653   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
26654          "Only know how to lower V2I64/V4I64/V8I64 multiply");
26655   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
26656 
26657   //  Ahi = psrlqi(a, 32);
26658   //  Bhi = psrlqi(b, 32);
26659   //
26660   //  AloBlo = pmuludq(a, b);
26661   //  AloBhi = pmuludq(a, Bhi);
26662   //  AhiBlo = pmuludq(Ahi, b);
26663   //
26664   //  Hi = psllqi(AloBhi + AhiBlo, 32);
26665   //  return AloBlo + Hi;
26666   KnownBits AKnown = DAG.computeKnownBits(A);
26667   KnownBits BKnown = DAG.computeKnownBits(B);
26668 
26669   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
26670   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
26671   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
26672 
26673   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
26674   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
26675   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
26676 
26677   SDValue Zero = DAG.getConstant(0, dl, VT);
26678 
26679   // Only multiply lo/hi halves that aren't known to be zero.
26680   SDValue AloBlo = Zero;
26681   if (!ALoIsZero && !BLoIsZero)
26682     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
26683 
26684   SDValue AloBhi = Zero;
26685   if (!ALoIsZero && !BHiIsZero) {
26686     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
26687     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
26688   }
26689 
26690   SDValue AhiBlo = Zero;
26691   if (!AHiIsZero && !BLoIsZero) {
26692     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
26693     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
26694   }
26695 
26696   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
26697   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
26698 
26699   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
26700 }
26701 
LowerMULH(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)26702 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
26703                          SelectionDAG &DAG) {
26704   SDLoc dl(Op);
26705   MVT VT = Op.getSimpleValueType();
26706   bool IsSigned = Op->getOpcode() == ISD::MULHS;
26707   unsigned NumElts = VT.getVectorNumElements();
26708   SDValue A = Op.getOperand(0);
26709   SDValue B = Op.getOperand(1);
26710 
26711   // Decompose 256-bit ops into 128-bit ops.
26712   if (VT.is256BitVector() && !Subtarget.hasInt256())
26713     return splitVectorIntBinary(Op, DAG);
26714 
26715   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
26716     return splitVectorIntBinary(Op, DAG);
26717 
26718   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
26719     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
26720            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
26721            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
26722 
26723     // PMULxD operations multiply each even value (starting at 0) of LHS with
26724     // the related value of RHS and produce a widen result.
26725     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
26726     // => <2 x i64> <ae|cg>
26727     //
26728     // In other word, to have all the results, we need to perform two PMULxD:
26729     // 1. one with the even values.
26730     // 2. one with the odd values.
26731     // To achieve #2, with need to place the odd values at an even position.
26732     //
26733     // Place the odd value at an even position (basically, shift all values 1
26734     // step to the left):
26735     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
26736                         9, -1, 11, -1, 13, -1, 15, -1};
26737     // <a|b|c|d> => <b|undef|d|undef>
26738     SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
26739                                         makeArrayRef(&Mask[0], NumElts));
26740     // <e|f|g|h> => <f|undef|h|undef>
26741     SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
26742                                         makeArrayRef(&Mask[0], NumElts));
26743 
26744     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
26745     // ints.
26746     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
26747     unsigned Opcode =
26748         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
26749     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
26750     // => <2 x i64> <ae|cg>
26751     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
26752                                                   DAG.getBitcast(MulVT, A),
26753                                                   DAG.getBitcast(MulVT, B)));
26754     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
26755     // => <2 x i64> <bf|dh>
26756     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
26757                                                   DAG.getBitcast(MulVT, Odd0),
26758                                                   DAG.getBitcast(MulVT, Odd1)));
26759 
26760     // Shuffle it back into the right order.
26761     SmallVector<int, 16> ShufMask(NumElts);
26762     for (int i = 0; i != (int)NumElts; ++i)
26763       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
26764 
26765     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
26766 
26767     // If we have a signed multiply but no PMULDQ fix up the result of an
26768     // unsigned multiply.
26769     if (IsSigned && !Subtarget.hasSSE41()) {
26770       SDValue Zero = DAG.getConstant(0, dl, VT);
26771       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
26772                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
26773       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
26774                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
26775 
26776       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
26777       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
26778     }
26779 
26780     return Res;
26781   }
26782 
26783   // Only i8 vectors should need custom lowering after this.
26784   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
26785          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
26786          "Unsupported vector type");
26787 
26788   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
26789   // logical shift down the upper half and pack back to i8.
26790 
26791   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
26792   // and then ashr/lshr the upper bits down to the lower bits before multiply.
26793   unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
26794 
26795   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
26796       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
26797     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
26798     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
26799     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
26800     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
26801     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
26802     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
26803   }
26804 
26805   // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
26806   // to a vXi16 type. Do the multiplies, shift the results and pack the half
26807   // lane results back together.
26808 
26809   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
26810 
26811   static const int PSHUFDMask[] = { 8,  9, 10, 11, 12, 13, 14, 15,
26812                                    -1, -1, -1, -1, -1, -1, -1, -1};
26813 
26814   // Extract the lo parts and zero/sign extend to i16.
26815   // Only use SSE4.1 instructions for signed v16i8 where using unpack requires
26816   // shifts to sign extend. Using unpack for unsigned only requires an xor to
26817   // create zeros and a copy due to tied registers contraints pre-avx. But using
26818   // zero_extend_vector_inreg would require an additional pshufd for the high
26819   // part.
26820 
26821   SDValue ALo, AHi;
26822   if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
26823     ALo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, A);
26824 
26825     AHi = DAG.getVectorShuffle(VT, dl, A, A, PSHUFDMask);
26826     AHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, AHi);
26827   } else if (IsSigned) {
26828     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), A));
26829     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), A));
26830 
26831     ALo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, ALo, 8, DAG);
26832     AHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, AHi, 8, DAG);
26833   } else {
26834     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A,
26835                                           DAG.getConstant(0, dl, VT)));
26836     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A,
26837                                           DAG.getConstant(0, dl, VT)));
26838   }
26839 
26840   SDValue BLo, BHi;
26841   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
26842     // If the LHS is a constant, manually unpackl/unpackh and extend.
26843     SmallVector<SDValue, 16> LoOps, HiOps;
26844     for (unsigned i = 0; i != NumElts; i += 16) {
26845       for (unsigned j = 0; j != 8; ++j) {
26846         SDValue LoOp = B.getOperand(i + j);
26847         SDValue HiOp = B.getOperand(i + j + 8);
26848 
26849         if (IsSigned) {
26850           LoOp = DAG.getSExtOrTrunc(LoOp, dl, MVT::i16);
26851           HiOp = DAG.getSExtOrTrunc(HiOp, dl, MVT::i16);
26852         } else {
26853           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
26854           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
26855         }
26856 
26857         LoOps.push_back(LoOp);
26858         HiOps.push_back(HiOp);
26859       }
26860     }
26861 
26862     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
26863     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
26864   } else if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
26865     BLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, B);
26866 
26867     BHi = DAG.getVectorShuffle(VT, dl, B, B, PSHUFDMask);
26868     BHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, BHi);
26869   } else if (IsSigned) {
26870     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), B));
26871     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), B));
26872 
26873     BLo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BLo, 8, DAG);
26874     BHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BHi, 8, DAG);
26875   } else {
26876     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B,
26877                                           DAG.getConstant(0, dl, VT)));
26878     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B,
26879                                           DAG.getConstant(0, dl, VT)));
26880   }
26881 
26882   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
26883   // pack back to vXi8.
26884   SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
26885   SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
26886   RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RLo, 8, DAG);
26887   RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RHi, 8, DAG);
26888 
26889   // Bitcast back to VT and then pack all the even elements from Lo and Hi.
26890   return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
26891 }
26892 
LowerWin64_i128OP(SDValue Op,SelectionDAG & DAG) const26893 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
26894   assert(Subtarget.isTargetWin64() && "Unexpected target");
26895   EVT VT = Op.getValueType();
26896   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
26897          "Unexpected return type for lowering");
26898 
26899   RTLIB::Libcall LC;
26900   bool isSigned;
26901   switch (Op->getOpcode()) {
26902   default: llvm_unreachable("Unexpected request for libcall!");
26903   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
26904   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
26905   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
26906   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
26907   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
26908   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
26909   }
26910 
26911   SDLoc dl(Op);
26912   SDValue InChain = DAG.getEntryNode();
26913 
26914   TargetLowering::ArgListTy Args;
26915   TargetLowering::ArgListEntry Entry;
26916   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
26917     EVT ArgVT = Op->getOperand(i).getValueType();
26918     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
26919            "Unexpected argument type for lowering");
26920     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
26921     int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
26922     MachinePointerInfo MPI =
26923         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
26924     Entry.Node = StackPtr;
26925     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr,
26926                            MPI, /* Alignment = */ 16);
26927     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
26928     Entry.Ty = PointerType::get(ArgTy,0);
26929     Entry.IsSExt = false;
26930     Entry.IsZExt = false;
26931     Args.push_back(Entry);
26932   }
26933 
26934   SDValue Callee = DAG.getExternalFunctionSymbol(getLibcallName(LC));
26935 
26936   TargetLowering::CallLoweringInfo CLI(DAG);
26937   CLI.setDebugLoc(dl)
26938       .setChain(InChain)
26939       .setLibCallee(
26940           getLibcallCallingConv(LC),
26941           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
26942           std::move(Args))
26943       .setInRegister()
26944       .setSExtResult(isSigned)
26945       .setZExtResult(!isSigned);
26946 
26947   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
26948   return DAG.getBitcast(VT, CallInfo.first);
26949 }
26950 
26951 // Return true if the required (according to Opcode) shift-imm form is natively
26952 // supported by the Subtarget
SupportedVectorShiftWithImm(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)26953 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
26954                                         unsigned Opcode) {
26955   if (VT.getScalarSizeInBits() < 16)
26956     return false;
26957 
26958   if (VT.is512BitVector() && Subtarget.hasAVX512() &&
26959       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
26960     return true;
26961 
26962   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
26963                 (VT.is256BitVector() && Subtarget.hasInt256());
26964 
26965   bool AShift = LShift && (Subtarget.hasAVX512() ||
26966                            (VT != MVT::v2i64 && VT != MVT::v4i64));
26967   return (Opcode == ISD::SRA) ? AShift : LShift;
26968 }
26969 
26970 // The shift amount is a variable, but it is the same for all vector lanes.
26971 // These instructions are defined together with shift-immediate.
26972 static
SupportedVectorShiftWithBaseAmnt(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)26973 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
26974                                       unsigned Opcode) {
26975   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
26976 }
26977 
26978 // Return true if the required (according to Opcode) variable-shift form is
26979 // natively supported by the Subtarget
SupportedVectorVarShift(MVT VT,const X86Subtarget & Subtarget,unsigned Opcode)26980 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
26981                                     unsigned Opcode) {
26982 
26983   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
26984     return false;
26985 
26986   // vXi16 supported only on AVX-512, BWI
26987   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
26988     return false;
26989 
26990   if (Subtarget.hasAVX512())
26991     return true;
26992 
26993   bool LShift = VT.is128BitVector() || VT.is256BitVector();
26994   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
26995   return (Opcode == ISD::SRA) ? AShift : LShift;
26996 }
26997 
LowerScalarImmediateShift(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)26998 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
26999                                          const X86Subtarget &Subtarget) {
27000   MVT VT = Op.getSimpleValueType();
27001   SDLoc dl(Op);
27002   SDValue R = Op.getOperand(0);
27003   SDValue Amt = Op.getOperand(1);
27004   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
27005 
27006   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
27007     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
27008     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
27009     SDValue Ex = DAG.getBitcast(ExVT, R);
27010 
27011     // ashr(R, 63) === cmp_slt(R, 0)
27012     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
27013       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
27014              "Unsupported PCMPGT op");
27015       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
27016     }
27017 
27018     if (ShiftAmt >= 32) {
27019       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
27020       SDValue Upper =
27021           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
27022       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
27023                                                  ShiftAmt - 32, DAG);
27024       if (VT == MVT::v2i64)
27025         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
27026       if (VT == MVT::v4i64)
27027         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
27028                                   {9, 1, 11, 3, 13, 5, 15, 7});
27029     } else {
27030       // SRA upper i32, SRL whole i64 and select lower i32.
27031       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
27032                                                  ShiftAmt, DAG);
27033       SDValue Lower =
27034           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
27035       Lower = DAG.getBitcast(ExVT, Lower);
27036       if (VT == MVT::v2i64)
27037         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
27038       if (VT == MVT::v4i64)
27039         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
27040                                   {8, 1, 10, 3, 12, 5, 14, 7});
27041     }
27042     return DAG.getBitcast(VT, Ex);
27043   };
27044 
27045   // Optimize shl/srl/sra with constant shift amount.
27046   APInt APIntShiftAmt;
27047   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
27048     return SDValue();
27049 
27050   // If the shift amount is out of range, return undef.
27051   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
27052     return DAG.getUNDEF(VT);
27053 
27054   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
27055 
27056   if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
27057     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
27058 
27059   // i64 SRA needs to be performed as partial shifts.
27060   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
27061        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
27062       Op.getOpcode() == ISD::SRA)
27063     return ArithmeticShiftRight64(ShiftAmt);
27064 
27065   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
27066       (Subtarget.hasBWI() && VT == MVT::v64i8)) {
27067     unsigned NumElts = VT.getVectorNumElements();
27068     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27069 
27070     // Simple i8 add case
27071     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
27072       return DAG.getNode(ISD::ADD, dl, VT, R, R);
27073 
27074     // ashr(R, 7)  === cmp_slt(R, 0)
27075     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
27076       SDValue Zeros = DAG.getConstant(0, dl, VT);
27077       if (VT.is512BitVector()) {
27078         assert(VT == MVT::v64i8 && "Unexpected element type!");
27079         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
27080         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
27081       }
27082       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
27083     }
27084 
27085     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
27086     if (VT == MVT::v16i8 && Subtarget.hasXOP())
27087       return SDValue();
27088 
27089     if (Op.getOpcode() == ISD::SHL) {
27090       // Make a large shift.
27091       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
27092                                                ShiftAmt, DAG);
27093       SHL = DAG.getBitcast(VT, SHL);
27094       // Zero out the rightmost bits.
27095       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
27096       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
27097     }
27098     if (Op.getOpcode() == ISD::SRL) {
27099       // Make a large shift.
27100       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
27101                                                ShiftAmt, DAG);
27102       SRL = DAG.getBitcast(VT, SRL);
27103       // Zero out the leftmost bits.
27104       return DAG.getNode(ISD::AND, dl, VT, SRL,
27105                          DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
27106     }
27107     if (Op.getOpcode() == ISD::SRA) {
27108       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
27109       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
27110 
27111       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
27112       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
27113       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
27114       return Res;
27115     }
27116     llvm_unreachable("Unknown shift opcode.");
27117   }
27118 
27119   return SDValue();
27120 }
27121 
LowerScalarVariableShift(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)27122 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
27123                                         const X86Subtarget &Subtarget) {
27124   MVT VT = Op.getSimpleValueType();
27125   SDLoc dl(Op);
27126   SDValue R = Op.getOperand(0);
27127   SDValue Amt = Op.getOperand(1);
27128   unsigned Opcode = Op.getOpcode();
27129   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
27130   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
27131 
27132   if (SDValue BaseShAmt = DAG.getSplatValue(Amt)) {
27133     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
27134       MVT EltVT = VT.getVectorElementType();
27135       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
27136       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
27137         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
27138       else if (EltVT.bitsLT(MVT::i32))
27139         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
27140 
27141       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
27142     }
27143 
27144     // vXi8 shifts - shift as v8i16 + mask result.
27145     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
27146          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
27147          VT == MVT::v64i8) &&
27148         !Subtarget.hasXOP()) {
27149       unsigned NumElts = VT.getVectorNumElements();
27150       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27151       if (SupportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
27152         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
27153         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
27154         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
27155 
27156         // Create the mask using vXi16 shifts. For shift-rights we need to move
27157         // the upper byte down before splatting the vXi8 mask.
27158         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
27159         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
27160                                       BaseShAmt, Subtarget, DAG);
27161         if (Opcode != ISD::SHL)
27162           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
27163                                                8, DAG);
27164         BitMask = DAG.getBitcast(VT, BitMask);
27165         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
27166                                        SmallVector<int, 64>(NumElts, 0));
27167 
27168         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
27169                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
27170                                           Subtarget, DAG);
27171         Res = DAG.getBitcast(VT, Res);
27172         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
27173 
27174         if (Opcode == ISD::SRA) {
27175           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
27176           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
27177           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
27178           SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
27179                                          BaseShAmt, Subtarget, DAG);
27180           SignMask = DAG.getBitcast(VT, SignMask);
27181           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
27182           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
27183         }
27184         return Res;
27185       }
27186     }
27187   }
27188 
27189   // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
27190   if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
27191       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
27192     Amt = Amt.getOperand(0);
27193     unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
27194     std::vector<SDValue> Vals(Ratio);
27195     for (unsigned i = 0; i != Ratio; ++i)
27196       Vals[i] = Amt.getOperand(i);
27197     for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
27198       for (unsigned j = 0; j != Ratio; ++j)
27199         if (Vals[j] != Amt.getOperand(i + j))
27200           return SDValue();
27201     }
27202 
27203     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
27204       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
27205   }
27206   return SDValue();
27207 }
27208 
27209 // Convert a shift/rotate left amount to a multiplication scale factor.
convertShiftLeftToScale(SDValue Amt,const SDLoc & dl,const X86Subtarget & Subtarget,SelectionDAG & DAG)27210 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
27211                                        const X86Subtarget &Subtarget,
27212                                        SelectionDAG &DAG) {
27213   MVT VT = Amt.getSimpleValueType();
27214   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
27215         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
27216         (!Subtarget.hasAVX512() && VT == MVT::v16i8)))
27217     return SDValue();
27218 
27219   if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
27220     SmallVector<SDValue, 8> Elts;
27221     MVT SVT = VT.getVectorElementType();
27222     unsigned SVTBits = SVT.getSizeInBits();
27223     APInt One(SVTBits, 1);
27224     unsigned NumElems = VT.getVectorNumElements();
27225 
27226     for (unsigned i = 0; i != NumElems; ++i) {
27227       SDValue Op = Amt->getOperand(i);
27228       if (Op->isUndef()) {
27229         Elts.push_back(Op);
27230         continue;
27231       }
27232 
27233       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
27234       APInt C(SVTBits, ND->getZExtValue());
27235       uint64_t ShAmt = C.getZExtValue();
27236       if (ShAmt >= SVTBits) {
27237         Elts.push_back(DAG.getUNDEF(SVT));
27238         continue;
27239       }
27240       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
27241     }
27242     return DAG.getBuildVector(VT, dl, Elts);
27243   }
27244 
27245   // If the target doesn't support variable shifts, use either FP conversion
27246   // or integer multiplication to avoid shifting each element individually.
27247   if (VT == MVT::v4i32) {
27248     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
27249     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
27250                       DAG.getConstant(0x3f800000U, dl, VT));
27251     Amt = DAG.getBitcast(MVT::v4f32, Amt);
27252     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
27253   }
27254 
27255   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
27256   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
27257     SDValue Z = DAG.getConstant(0, dl, VT);
27258     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
27259     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
27260     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
27261     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
27262     if (Subtarget.hasSSE41())
27263       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
27264 
27265     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, Lo),
27266                                         DAG.getBitcast(VT, Hi),
27267                                         {0, 2, 4, 6, 8, 10, 12, 14});
27268   }
27269 
27270   return SDValue();
27271 }
27272 
LowerShift(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27273 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
27274                           SelectionDAG &DAG) {
27275   MVT VT = Op.getSimpleValueType();
27276   SDLoc dl(Op);
27277   SDValue R = Op.getOperand(0);
27278   SDValue Amt = Op.getOperand(1);
27279   unsigned EltSizeInBits = VT.getScalarSizeInBits();
27280   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
27281 
27282   unsigned Opc = Op.getOpcode();
27283   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
27284   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
27285 
27286   assert(VT.isVector() && "Custom lowering only for vector shifts!");
27287   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
27288 
27289   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
27290     return V;
27291 
27292   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
27293     return V;
27294 
27295   if (SupportedVectorVarShift(VT, Subtarget, Opc))
27296     return Op;
27297 
27298   // XOP has 128-bit variable logical/arithmetic shifts.
27299   // +ve/-ve Amt = shift left/right.
27300   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
27301                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
27302     if (Opc == ISD::SRL || Opc == ISD::SRA) {
27303       SDValue Zero = DAG.getConstant(0, dl, VT);
27304       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
27305     }
27306     if (Opc == ISD::SHL || Opc == ISD::SRL)
27307       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
27308     if (Opc == ISD::SRA)
27309       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
27310   }
27311 
27312   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
27313   // shifts per-lane and then shuffle the partial results back together.
27314   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
27315     // Splat the shift amounts so the scalar shifts above will catch it.
27316     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
27317     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
27318     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
27319     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
27320     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
27321   }
27322 
27323   // i64 vector arithmetic shift can be emulated with the transform:
27324   // M = lshr(SIGN_MASK, Amt)
27325   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
27326   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
27327       Opc == ISD::SRA) {
27328     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
27329     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
27330     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
27331     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
27332     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
27333     return R;
27334   }
27335 
27336   // If possible, lower this shift as a sequence of two shifts by
27337   // constant plus a BLENDing shuffle instead of scalarizing it.
27338   // Example:
27339   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
27340   //
27341   // Could be rewritten as:
27342   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
27343   //
27344   // The advantage is that the two shifts from the example would be
27345   // lowered as X86ISD::VSRLI nodes in parallel before blending.
27346   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
27347                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
27348     SDValue Amt1, Amt2;
27349     unsigned NumElts = VT.getVectorNumElements();
27350     SmallVector<int, 8> ShuffleMask;
27351     for (unsigned i = 0; i != NumElts; ++i) {
27352       SDValue A = Amt->getOperand(i);
27353       if (A.isUndef()) {
27354         ShuffleMask.push_back(SM_SentinelUndef);
27355         continue;
27356       }
27357       if (!Amt1 || Amt1 == A) {
27358         ShuffleMask.push_back(i);
27359         Amt1 = A;
27360         continue;
27361       }
27362       if (!Amt2 || Amt2 == A) {
27363         ShuffleMask.push_back(i + NumElts);
27364         Amt2 = A;
27365         continue;
27366       }
27367       break;
27368     }
27369 
27370     // Only perform this blend if we can perform it without loading a mask.
27371     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
27372         (VT != MVT::v16i16 ||
27373          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
27374         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
27375          canWidenShuffleElements(ShuffleMask))) {
27376       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
27377       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
27378       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
27379           Cst2->getAPIntValue().ult(EltSizeInBits)) {
27380         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
27381                                                     Cst1->getZExtValue(), DAG);
27382         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
27383                                                     Cst2->getZExtValue(), DAG);
27384         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
27385       }
27386     }
27387   }
27388 
27389   // If possible, lower this packed shift into a vector multiply instead of
27390   // expanding it into a sequence of scalar shifts.
27391   if (Opc == ISD::SHL)
27392     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
27393       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
27394 
27395   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
27396   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
27397   if (Opc == ISD::SRL && ConstantAmt &&
27398       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
27399     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
27400     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
27401     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
27402       SDValue Zero = DAG.getConstant(0, dl, VT);
27403       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
27404       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
27405       return DAG.getSelect(dl, VT, ZAmt, R, Res);
27406     }
27407   }
27408 
27409   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
27410   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
27411   // TODO: Special case handling for shift by 0/1, really we can afford either
27412   // of these cases in pre-SSE41/XOP/AVX512 but not both.
27413   if (Opc == ISD::SRA && ConstantAmt &&
27414       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
27415       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
27416         !Subtarget.hasAVX512()) ||
27417        DAG.isKnownNeverZero(Amt))) {
27418     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
27419     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
27420     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
27421       SDValue Amt0 =
27422           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
27423       SDValue Amt1 =
27424           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
27425       SDValue Sra1 =
27426           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
27427       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
27428       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
27429       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
27430     }
27431   }
27432 
27433   // v4i32 Non Uniform Shifts.
27434   // If the shift amount is constant we can shift each lane using the SSE2
27435   // immediate shifts, else we need to zero-extend each lane to the lower i64
27436   // and shift using the SSE2 variable shifts.
27437   // The separate results can then be blended together.
27438   if (VT == MVT::v4i32) {
27439     SDValue Amt0, Amt1, Amt2, Amt3;
27440     if (ConstantAmt) {
27441       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
27442       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
27443       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
27444       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
27445     } else {
27446       // The SSE2 shifts use the lower i64 as the same shift amount for
27447       // all lanes and the upper i64 is ignored. On AVX we're better off
27448       // just zero-extending, but for SSE just duplicating the top 16-bits is
27449       // cheaper and has the same effect for out of range values.
27450       if (Subtarget.hasAVX()) {
27451         SDValue Z = DAG.getConstant(0, dl, VT);
27452         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
27453         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
27454         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
27455         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
27456       } else {
27457         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
27458         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
27459                                              {4, 5, 6, 7, -1, -1, -1, -1});
27460         Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
27461                                     {0, 1, 1, 1, -1, -1, -1, -1});
27462         Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
27463                                     {2, 3, 3, 3, -1, -1, -1, -1});
27464         Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
27465                                     {0, 1, 1, 1, -1, -1, -1, -1});
27466         Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
27467                                     {2, 3, 3, 3, -1, -1, -1, -1});
27468       }
27469     }
27470 
27471     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
27472     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
27473     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
27474     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
27475     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
27476 
27477     // Merge the shifted lane results optimally with/without PBLENDW.
27478     // TODO - ideally shuffle combining would handle this.
27479     if (Subtarget.hasSSE41()) {
27480       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
27481       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
27482       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
27483     }
27484     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
27485     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
27486     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
27487   }
27488 
27489   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
27490   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
27491   // make the existing SSE solution better.
27492   // NOTE: We honor prefered vector width before promoting to 512-bits.
27493   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
27494       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
27495       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
27496       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
27497       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
27498     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
27499            "Unexpected vector type");
27500     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
27501     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
27502     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
27503     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
27504     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
27505     return DAG.getNode(ISD::TRUNCATE, dl, VT,
27506                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
27507   }
27508 
27509   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
27510   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
27511   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
27512       (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
27513        (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
27514       !Subtarget.hasXOP()) {
27515     int NumElts = VT.getVectorNumElements();
27516     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
27517 
27518     // Extend constant shift amount to vXi16 (it doesn't matter if the type
27519     // isn't legal).
27520     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
27521     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
27522     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
27523     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
27524     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
27525            "Constant build vector expected");
27526 
27527     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
27528       R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
27529                           : DAG.getZExtOrTrunc(R, dl, ExVT);
27530       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
27531       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
27532       return DAG.getZExtOrTrunc(R, dl, VT);
27533     }
27534 
27535     SmallVector<SDValue, 16> LoAmt, HiAmt;
27536     for (int i = 0; i != NumElts; i += 16) {
27537       for (int j = 0; j != 8; ++j) {
27538         LoAmt.push_back(Amt.getOperand(i + j));
27539         HiAmt.push_back(Amt.getOperand(i + j + 8));
27540       }
27541     }
27542 
27543     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
27544     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
27545     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
27546 
27547     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
27548     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
27549     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
27550     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
27551     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
27552     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
27553     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
27554     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
27555     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
27556   }
27557 
27558   if (VT == MVT::v16i8 ||
27559       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
27560       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
27561     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
27562 
27563     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
27564       if (VT.is512BitVector()) {
27565         // On AVX512BW targets we make use of the fact that VSELECT lowers
27566         // to a masked blend which selects bytes based just on the sign bit
27567         // extracted to a mask.
27568         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
27569         V0 = DAG.getBitcast(VT, V0);
27570         V1 = DAG.getBitcast(VT, V1);
27571         Sel = DAG.getBitcast(VT, Sel);
27572         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
27573                            ISD::SETGT);
27574         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
27575       } else if (Subtarget.hasSSE41()) {
27576         // On SSE41 targets we can use PBLENDVB which selects bytes based just
27577         // on the sign bit.
27578         V0 = DAG.getBitcast(VT, V0);
27579         V1 = DAG.getBitcast(VT, V1);
27580         Sel = DAG.getBitcast(VT, Sel);
27581         return DAG.getBitcast(SelVT,
27582                               DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
27583       }
27584       // On pre-SSE41 targets we test for the sign bit by comparing to
27585       // zero - a negative value will set all bits of the lanes to true
27586       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
27587       SDValue Z = DAG.getConstant(0, dl, SelVT);
27588       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
27589       return DAG.getSelect(dl, SelVT, C, V0, V1);
27590     };
27591 
27592     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
27593     // We can safely do this using i16 shifts as we're only interested in
27594     // the 3 lower bits of each byte.
27595     Amt = DAG.getBitcast(ExtVT, Amt);
27596     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
27597     Amt = DAG.getBitcast(VT, Amt);
27598 
27599     if (Opc == ISD::SHL || Opc == ISD::SRL) {
27600       // r = VSELECT(r, shift(r, 4), a);
27601       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
27602       R = SignBitSelect(VT, Amt, M, R);
27603 
27604       // a += a
27605       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27606 
27607       // r = VSELECT(r, shift(r, 2), a);
27608       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
27609       R = SignBitSelect(VT, Amt, M, R);
27610 
27611       // a += a
27612       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27613 
27614       // return VSELECT(r, shift(r, 1), a);
27615       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
27616       R = SignBitSelect(VT, Amt, M, R);
27617       return R;
27618     }
27619 
27620     if (Opc == ISD::SRA) {
27621       // For SRA we need to unpack each byte to the higher byte of a i16 vector
27622       // so we can correctly sign extend. We don't care what happens to the
27623       // lower byte.
27624       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
27625       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
27626       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
27627       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
27628       ALo = DAG.getBitcast(ExtVT, ALo);
27629       AHi = DAG.getBitcast(ExtVT, AHi);
27630       RLo = DAG.getBitcast(ExtVT, RLo);
27631       RHi = DAG.getBitcast(ExtVT, RHi);
27632 
27633       // r = VSELECT(r, shift(r, 4), a);
27634       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
27635       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
27636       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
27637       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
27638 
27639       // a += a
27640       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
27641       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
27642 
27643       // r = VSELECT(r, shift(r, 2), a);
27644       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
27645       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
27646       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
27647       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
27648 
27649       // a += a
27650       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
27651       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
27652 
27653       // r = VSELECT(r, shift(r, 1), a);
27654       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
27655       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
27656       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
27657       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
27658 
27659       // Logical shift the result back to the lower byte, leaving a zero upper
27660       // byte meaning that we can safely pack with PACKUSWB.
27661       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
27662       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
27663       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
27664     }
27665   }
27666 
27667   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
27668     MVT ExtVT = MVT::v8i32;
27669     SDValue Z = DAG.getConstant(0, dl, VT);
27670     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
27671     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
27672     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
27673     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
27674     ALo = DAG.getBitcast(ExtVT, ALo);
27675     AHi = DAG.getBitcast(ExtVT, AHi);
27676     RLo = DAG.getBitcast(ExtVT, RLo);
27677     RHi = DAG.getBitcast(ExtVT, RHi);
27678     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
27679     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
27680     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
27681     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
27682     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
27683   }
27684 
27685   if (VT == MVT::v8i16) {
27686     // If we have a constant shift amount, the non-SSE41 path is best as
27687     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
27688     bool UseSSE41 = Subtarget.hasSSE41() &&
27689                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
27690 
27691     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
27692       // On SSE41 targets we can use PBLENDVB which selects bytes based just on
27693       // the sign bit.
27694       if (UseSSE41) {
27695         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
27696         V0 = DAG.getBitcast(ExtVT, V0);
27697         V1 = DAG.getBitcast(ExtVT, V1);
27698         Sel = DAG.getBitcast(ExtVT, Sel);
27699         return DAG.getBitcast(
27700             VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
27701       }
27702       // On pre-SSE41 targets we splat the sign bit - a negative value will
27703       // set all bits of the lanes to true and VSELECT uses that in
27704       // its OR(AND(V0,C),AND(V1,~C)) lowering.
27705       SDValue C =
27706           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
27707       return DAG.getSelect(dl, VT, C, V0, V1);
27708     };
27709 
27710     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
27711     if (UseSSE41) {
27712       // On SSE41 targets we need to replicate the shift mask in both
27713       // bytes for PBLENDVB.
27714       Amt = DAG.getNode(
27715           ISD::OR, dl, VT,
27716           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
27717           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
27718     } else {
27719       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
27720     }
27721 
27722     // r = VSELECT(r, shift(r, 8), a);
27723     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
27724     R = SignBitSelect(Amt, M, R);
27725 
27726     // a += a
27727     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27728 
27729     // r = VSELECT(r, shift(r, 4), a);
27730     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
27731     R = SignBitSelect(Amt, M, R);
27732 
27733     // a += a
27734     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27735 
27736     // r = VSELECT(r, shift(r, 2), a);
27737     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
27738     R = SignBitSelect(Amt, M, R);
27739 
27740     // a += a
27741     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
27742 
27743     // return VSELECT(r, shift(r, 1), a);
27744     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
27745     R = SignBitSelect(Amt, M, R);
27746     return R;
27747   }
27748 
27749   // Decompose 256-bit shifts into 128-bit shifts.
27750   if (VT.is256BitVector())
27751     return splitVectorIntBinary(Op, DAG);
27752 
27753   if (VT == MVT::v32i16 || VT == MVT::v64i8)
27754     return splitVectorIntBinary(Op, DAG);
27755 
27756   return SDValue();
27757 }
27758 
LowerRotate(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)27759 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
27760                            SelectionDAG &DAG) {
27761   MVT VT = Op.getSimpleValueType();
27762   assert(VT.isVector() && "Custom lowering only for vector rotates!");
27763 
27764   SDLoc DL(Op);
27765   SDValue R = Op.getOperand(0);
27766   SDValue Amt = Op.getOperand(1);
27767   unsigned Opcode = Op.getOpcode();
27768   unsigned EltSizeInBits = VT.getScalarSizeInBits();
27769   int NumElts = VT.getVectorNumElements();
27770 
27771   // Check for constant splat rotation amount.
27772   APInt CstSplatValue;
27773   bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
27774 
27775   // Check for splat rotate by zero.
27776   if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
27777     return R;
27778 
27779   // AVX512 implicitly uses modulo rotation amounts.
27780   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
27781     // Attempt to rotate by immediate.
27782     if (IsCstSplat) {
27783       unsigned RotOpc = (Opcode == ISD::ROTL ? X86ISD::VROTLI : X86ISD::VROTRI);
27784       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
27785       return DAG.getNode(RotOpc, DL, VT, R,
27786                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
27787     }
27788 
27789     // Else, fall-back on VPROLV/VPRORV.
27790     return Op;
27791   }
27792 
27793   assert((Opcode == ISD::ROTL) && "Only ROTL supported");
27794 
27795   // XOP has 128-bit vector variable + immediate rotates.
27796   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
27797   // XOP implicitly uses modulo rotation amounts.
27798   if (Subtarget.hasXOP()) {
27799     if (VT.is256BitVector())
27800       return splitVectorIntBinary(Op, DAG);
27801     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
27802 
27803     // Attempt to rotate by immediate.
27804     if (IsCstSplat) {
27805       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
27806       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
27807                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
27808     }
27809 
27810     // Use general rotate by variable (per-element).
27811     return Op;
27812   }
27813 
27814   // Split 256-bit integers on pre-AVX2 targets.
27815   if (VT.is256BitVector() && !Subtarget.hasAVX2())
27816     return splitVectorIntBinary(Op, DAG);
27817 
27818   assert((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
27819           ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&
27820            Subtarget.hasAVX2())) &&
27821          "Only vXi32/vXi16/vXi8 vector rotates supported");
27822 
27823   // Rotate by an uniform constant - expand back to shifts.
27824   if (IsCstSplat)
27825     return SDValue();
27826 
27827   bool IsSplatAmt = DAG.isSplatValue(Amt);
27828 
27829   // v16i8/v32i8: Split rotation into rot4/rot2/rot1 stages and select by
27830   // the amount bit.
27831   if (EltSizeInBits == 8 && !IsSplatAmt) {
27832     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()))
27833       return SDValue();
27834 
27835     // We don't need ModuloAmt here as we just peek at individual bits.
27836     MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27837 
27838     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
27839       if (Subtarget.hasSSE41()) {
27840         // On SSE41 targets we can use PBLENDVB which selects bytes based just
27841         // on the sign bit.
27842         V0 = DAG.getBitcast(VT, V0);
27843         V1 = DAG.getBitcast(VT, V1);
27844         Sel = DAG.getBitcast(VT, Sel);
27845         return DAG.getBitcast(SelVT,
27846                               DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
27847       }
27848       // On pre-SSE41 targets we test for the sign bit by comparing to
27849       // zero - a negative value will set all bits of the lanes to true
27850       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
27851       SDValue Z = DAG.getConstant(0, DL, SelVT);
27852       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
27853       return DAG.getSelect(DL, SelVT, C, V0, V1);
27854     };
27855 
27856     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
27857     // We can safely do this using i16 shifts as we're only interested in
27858     // the 3 lower bits of each byte.
27859     Amt = DAG.getBitcast(ExtVT, Amt);
27860     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
27861     Amt = DAG.getBitcast(VT, Amt);
27862 
27863     // r = VSELECT(r, rot(r, 4), a);
27864     SDValue M;
27865     M = DAG.getNode(
27866         ISD::OR, DL, VT,
27867         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(4, DL, VT)),
27868         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(4, DL, VT)));
27869     R = SignBitSelect(VT, Amt, M, R);
27870 
27871     // a += a
27872     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
27873 
27874     // r = VSELECT(r, rot(r, 2), a);
27875     M = DAG.getNode(
27876         ISD::OR, DL, VT,
27877         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(2, DL, VT)),
27878         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(6, DL, VT)));
27879     R = SignBitSelect(VT, Amt, M, R);
27880 
27881     // a += a
27882     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
27883 
27884     // return VSELECT(r, rot(r, 1), a);
27885     M = DAG.getNode(
27886         ISD::OR, DL, VT,
27887         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(1, DL, VT)),
27888         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(7, DL, VT)));
27889     return SignBitSelect(VT, Amt, M, R);
27890   }
27891 
27892   // ISD::ROT* uses modulo rotate amounts.
27893   Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
27894                     DAG.getConstant(EltSizeInBits - 1, DL, VT));
27895 
27896   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
27897   bool LegalVarShifts = SupportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
27898                         SupportedVectorVarShift(VT, Subtarget, ISD::SRL);
27899 
27900   // Fallback for splats + all supported variable shifts.
27901   // Fallback for non-constants AVX2 vXi16 as well.
27902   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
27903     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
27904     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
27905     SDValue SHL = DAG.getNode(ISD::SHL, DL, VT, R, Amt);
27906     SDValue SRL = DAG.getNode(ISD::SRL, DL, VT, R, AmtR);
27907     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
27908   }
27909 
27910   // As with shifts, convert the rotation amount to a multiplication factor.
27911   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
27912   assert(Scale && "Failed to convert ROTL amount to scale");
27913 
27914   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
27915   if (EltSizeInBits == 16) {
27916     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
27917     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
27918     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
27919   }
27920 
27921   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
27922   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
27923   // that can then be OR'd with the lower 32-bits.
27924   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
27925   static const int OddMask[] = {1, -1, 3, -1};
27926   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
27927   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
27928 
27929   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
27930                               DAG.getBitcast(MVT::v2i64, R),
27931                               DAG.getBitcast(MVT::v2i64, Scale));
27932   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
27933                               DAG.getBitcast(MVT::v2i64, R13),
27934                               DAG.getBitcast(MVT::v2i64, Scale13));
27935   Res02 = DAG.getBitcast(VT, Res02);
27936   Res13 = DAG.getBitcast(VT, Res13);
27937 
27938   return DAG.getNode(ISD::OR, DL, VT,
27939                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
27940                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
27941 }
27942 
27943 /// Returns true if the operand type is exactly twice the native width, and
27944 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
27945 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
27946 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
needsCmpXchgNb(Type * MemType) const27947 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
27948   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
27949 
27950   if (OpWidth == 64)
27951     return Subtarget.hasCmpxchg8b() && !Subtarget.is64Bit();
27952   if (OpWidth == 128)
27953     return Subtarget.hasCmpxchg16b();
27954 
27955   return false;
27956 }
27957 
shouldExpandAtomicStoreInIR(StoreInst * SI) const27958 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
27959   Type *MemType = SI->getValueOperand()->getType();
27960 
27961   bool NoImplicitFloatOps =
27962       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
27963   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
27964       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
27965       (Subtarget.hasSSE1() || Subtarget.hasX87()))
27966     return false;
27967 
27968   return needsCmpXchgNb(MemType);
27969 }
27970 
27971 // Note: this turns large loads into lock cmpxchg8b/16b.
27972 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
27973 TargetLowering::AtomicExpansionKind
shouldExpandAtomicLoadInIR(LoadInst * LI) const27974 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
27975   Type *MemType = LI->getType();
27976 
27977   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
27978   // can use movq to do the load. If we have X87 we can load into an 80-bit
27979   // X87 register and store it to a stack temporary.
27980   bool NoImplicitFloatOps =
27981       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
27982   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
27983       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
27984       (Subtarget.hasSSE1() || Subtarget.hasX87()))
27985     return AtomicExpansionKind::None;
27986 
27987   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
27988                                  : AtomicExpansionKind::None;
27989 }
27990 
27991 TargetLowering::AtomicExpansionKind
shouldExpandAtomicRMWInIR(AtomicRMWInst * AI) const27992 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
27993   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
27994   Type *MemType = AI->getType();
27995 
27996   // If the operand is too big, we must see if cmpxchg8/16b is available
27997   // and default to library calls otherwise.
27998   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
27999     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
28000                                    : AtomicExpansionKind::None;
28001   }
28002 
28003   AtomicRMWInst::BinOp Op = AI->getOperation();
28004   switch (Op) {
28005   default:
28006     llvm_unreachable("Unknown atomic operation");
28007   case AtomicRMWInst::Xchg:
28008   case AtomicRMWInst::Add:
28009   case AtomicRMWInst::Sub:
28010     // It's better to use xadd, xsub or xchg for these in all cases.
28011     return AtomicExpansionKind::None;
28012   case AtomicRMWInst::Or:
28013   case AtomicRMWInst::And:
28014   case AtomicRMWInst::Xor:
28015     // If the atomicrmw's result isn't actually used, we can just add a "lock"
28016     // prefix to a normal instruction for these operations.
28017     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
28018                             : AtomicExpansionKind::None;
28019   case AtomicRMWInst::Nand:
28020   case AtomicRMWInst::Max:
28021   case AtomicRMWInst::Min:
28022   case AtomicRMWInst::UMax:
28023   case AtomicRMWInst::UMin:
28024   case AtomicRMWInst::FAdd:
28025   case AtomicRMWInst::FSub:
28026     // These always require a non-trivial set of data operations on x86. We must
28027     // use a cmpxchg loop.
28028     return AtomicExpansionKind::CmpXChg;
28029   }
28030 }
28031 
28032 LoadInst *
lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst * AI) const28033 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
28034   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
28035   Type *MemType = AI->getType();
28036   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
28037   // there is no benefit in turning such RMWs into loads, and it is actually
28038   // harmful as it introduces a mfence.
28039   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
28040     return nullptr;
28041 
28042   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
28043   // lowering available in lowerAtomicArith.
28044   // TODO: push more cases through this path.
28045   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
28046     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
28047         AI->use_empty())
28048       return nullptr;
28049 
28050   IRBuilder<> Builder(AI);
28051   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
28052   auto SSID = AI->getSyncScopeID();
28053   // We must restrict the ordering to avoid generating loads with Release or
28054   // ReleaseAcquire orderings.
28055   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
28056 
28057   // Before the load we need a fence. Here is an example lifted from
28058   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
28059   // is required:
28060   // Thread 0:
28061   //   x.store(1, relaxed);
28062   //   r1 = y.fetch_add(0, release);
28063   // Thread 1:
28064   //   y.fetch_add(42, acquire);
28065   //   r2 = x.load(relaxed);
28066   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
28067   // lowered to just a load without a fence. A mfence flushes the store buffer,
28068   // making the optimization clearly correct.
28069   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
28070   // otherwise, we might be able to be more aggressive on relaxed idempotent
28071   // rmw. In practice, they do not look useful, so we don't try to be
28072   // especially clever.
28073   if (SSID == SyncScope::SingleThread)
28074     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
28075     // the IR level, so we must wrap it in an intrinsic.
28076     return nullptr;
28077 
28078   if (!Subtarget.hasMFence())
28079     // FIXME: it might make sense to use a locked operation here but on a
28080     // different cache-line to prevent cache-line bouncing. In practice it
28081     // is probably a small win, and x86 processors without mfence are rare
28082     // enough that we do not bother.
28083     return nullptr;
28084 
28085   Function *MFence =
28086       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
28087   Builder.CreateCall(MFence, {});
28088 
28089   // Finally we can emit the atomic load.
28090   LoadInst *Loaded =
28091       Builder.CreateAlignedLoad(AI->getType(), AI->getPointerOperand(),
28092                                 Align(AI->getType()->getPrimitiveSizeInBits()));
28093   Loaded->setAtomic(Order, SSID);
28094   AI->replaceAllUsesWith(Loaded);
28095   AI->eraseFromParent();
28096   return Loaded;
28097 }
28098 
lowerAtomicStoreAsStoreSDNode(const StoreInst & SI) const28099 bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
28100   if (!SI.isUnordered())
28101     return false;
28102   return ExperimentalUnorderedISEL;
28103 }
lowerAtomicLoadAsLoadSDNode(const LoadInst & LI) const28104 bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
28105   if (!LI.isUnordered())
28106     return false;
28107   return ExperimentalUnorderedISEL;
28108 }
28109 
28110 
28111 /// Emit a locked operation on a stack location which does not change any
28112 /// memory location, but does involve a lock prefix.  Location is chosen to be
28113 /// a) very likely accessed only by a single thread to minimize cache traffic,
28114 /// and b) definitely dereferenceable.  Returns the new Chain result.
emitLockedStackOp(SelectionDAG & DAG,const X86Subtarget & Subtarget,SDValue Chain,SDLoc DL)28115 static SDValue emitLockedStackOp(SelectionDAG &DAG,
28116                                  const X86Subtarget &Subtarget,
28117                                  SDValue Chain, SDLoc DL) {
28118   // Implementation notes:
28119   // 1) LOCK prefix creates a full read/write reordering barrier for memory
28120   // operations issued by the current processor.  As such, the location
28121   // referenced is not relevant for the ordering properties of the instruction.
28122   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
28123   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
28124   // 2) Using an immediate operand appears to be the best encoding choice
28125   // here since it doesn't require an extra register.
28126   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
28127   // is small enough it might just be measurement noise.)
28128   // 4) When choosing offsets, there are several contributing factors:
28129   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
28130   //      line aligned stack object to improve this case.)
28131   //   b) To minimize our chances of introducing a false dependence, we prefer
28132   //      to offset the stack usage from TOS slightly.
28133   //   c) To minimize concerns about cross thread stack usage - in particular,
28134   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
28135   //      captures state in the TOS frame and accesses it from many threads -
28136   //      we want to use an offset such that the offset is in a distinct cache
28137   //      line from the TOS frame.
28138   //
28139   // For a general discussion of the tradeoffs and benchmark results, see:
28140   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
28141 
28142   auto &MF = DAG.getMachineFunction();
28143   auto &TFL = *Subtarget.getFrameLowering();
28144   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
28145 
28146   if (Subtarget.is64Bit()) {
28147     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
28148     SDValue Ops[] = {
28149       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
28150       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
28151       DAG.getRegister(0, MVT::i64),                         // Index
28152       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
28153       DAG.getRegister(0, MVT::i16),                         // Segment.
28154       Zero,
28155       Chain};
28156     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
28157                                      MVT::Other, Ops);
28158     return SDValue(Res, 1);
28159   }
28160 
28161   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
28162   SDValue Ops[] = {
28163     DAG.getRegister(X86::ESP, MVT::i32),            // Base
28164     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
28165     DAG.getRegister(0, MVT::i32),                   // Index
28166     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
28167     DAG.getRegister(0, MVT::i16),                   // Segment.
28168     Zero,
28169     Chain
28170   };
28171   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
28172                                    MVT::Other, Ops);
28173   return SDValue(Res, 1);
28174 }
28175 
LowerATOMIC_FENCE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28176 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
28177                                  SelectionDAG &DAG) {
28178   SDLoc dl(Op);
28179   AtomicOrdering FenceOrdering =
28180       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
28181   SyncScope::ID FenceSSID =
28182       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
28183 
28184   // The only fence that needs an instruction is a sequentially-consistent
28185   // cross-thread fence.
28186   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
28187       FenceSSID == SyncScope::System) {
28188     if (Subtarget.hasMFence())
28189       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
28190 
28191     SDValue Chain = Op.getOperand(0);
28192     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
28193   }
28194 
28195   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
28196   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
28197 }
28198 
LowerCMP_SWAP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28199 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
28200                              SelectionDAG &DAG) {
28201   MVT T = Op.getSimpleValueType();
28202   SDLoc DL(Op);
28203   unsigned Reg = 0;
28204   unsigned size = 0;
28205   switch(T.SimpleTy) {
28206   default: llvm_unreachable("Invalid value type!");
28207   case MVT::i8:  Reg = X86::AL;  size = 1; break;
28208   case MVT::i16: Reg = X86::AX;  size = 2; break;
28209   case MVT::i32: Reg = X86::EAX; size = 4; break;
28210   case MVT::i64:
28211     assert(Subtarget.is64Bit() && "Node not type legal!");
28212     Reg = X86::RAX; size = 8;
28213     break;
28214   }
28215   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
28216                                   Op.getOperand(2), SDValue());
28217   SDValue Ops[] = { cpIn.getValue(0),
28218                     Op.getOperand(1),
28219                     Op.getOperand(3),
28220                     DAG.getTargetConstant(size, DL, MVT::i8),
28221                     cpIn.getValue(1) };
28222   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
28223   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
28224   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
28225                                            Ops, T, MMO);
28226 
28227   SDValue cpOut =
28228     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
28229   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
28230                                       MVT::i32, cpOut.getValue(2));
28231   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
28232 
28233   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
28234                      cpOut, Success, EFLAGS.getValue(1));
28235 }
28236 
28237 // Create MOVMSKB, taking into account whether we need to split for AVX1.
getPMOVMSKB(const SDLoc & DL,SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)28238 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
28239                            const X86Subtarget &Subtarget) {
28240   MVT InVT = V.getSimpleValueType();
28241 
28242   if (InVT == MVT::v64i8) {
28243     SDValue Lo, Hi;
28244     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
28245     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
28246     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
28247     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
28248     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
28249     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
28250                      DAG.getConstant(32, DL, MVT::i8));
28251     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
28252   }
28253   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
28254     SDValue Lo, Hi;
28255     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
28256     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
28257     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
28258     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
28259                      DAG.getConstant(16, DL, MVT::i8));
28260     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
28261   }
28262 
28263   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
28264 }
28265 
LowerBITCAST(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28266 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
28267                             SelectionDAG &DAG) {
28268   SDValue Src = Op.getOperand(0);
28269   MVT SrcVT = Src.getSimpleValueType();
28270   MVT DstVT = Op.getSimpleValueType();
28271 
28272   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
28273   // half to v32i1 and concatenating the result.
28274   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
28275     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
28276     assert(Subtarget.hasBWI() && "Expected BWI target");
28277     SDLoc dl(Op);
28278     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
28279                              DAG.getIntPtrConstant(0, dl));
28280     Lo = DAG.getBitcast(MVT::v32i1, Lo);
28281     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
28282                              DAG.getIntPtrConstant(1, dl));
28283     Hi = DAG.getBitcast(MVT::v32i1, Hi);
28284     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
28285   }
28286 
28287   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
28288   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
28289     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
28290     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
28291     SDLoc DL(Op);
28292     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
28293     V = getPMOVMSKB(DL, V, DAG, Subtarget);
28294     return DAG.getZExtOrTrunc(V, DL, DstVT);
28295   }
28296 
28297   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
28298           SrcVT == MVT::i64) && "Unexpected VT!");
28299 
28300   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
28301   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
28302       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
28303     // This conversion needs to be expanded.
28304     return SDValue();
28305 
28306   SDLoc dl(Op);
28307   if (SrcVT.isVector()) {
28308     // Widen the vector in input in the case of MVT::v2i32.
28309     // Example: from MVT::v2i32 to MVT::v4i32.
28310     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
28311                                  SrcVT.getVectorNumElements() * 2);
28312     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
28313                       DAG.getUNDEF(SrcVT));
28314   } else {
28315     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
28316            "Unexpected source type in LowerBITCAST");
28317     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
28318   }
28319 
28320   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
28321   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
28322 
28323   if (DstVT == MVT::x86mmx)
28324     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
28325 
28326   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
28327                      DAG.getIntPtrConstant(0, dl));
28328 }
28329 
28330 /// Compute the horizontal sum of bytes in V for the elements of VT.
28331 ///
28332 /// Requires V to be a byte vector and VT to be an integer vector type with
28333 /// wider elements than V's type. The width of the elements of VT determines
28334 /// how many bytes of V are summed horizontally to produce each element of the
28335 /// result.
LowerHorizontalByteSum(SDValue V,MVT VT,const X86Subtarget & Subtarget,SelectionDAG & DAG)28336 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
28337                                       const X86Subtarget &Subtarget,
28338                                       SelectionDAG &DAG) {
28339   SDLoc DL(V);
28340   MVT ByteVecVT = V.getSimpleValueType();
28341   MVT EltVT = VT.getVectorElementType();
28342   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
28343          "Expected value to have byte element type.");
28344   assert(EltVT != MVT::i8 &&
28345          "Horizontal byte sum only makes sense for wider elements!");
28346   unsigned VecSize = VT.getSizeInBits();
28347   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
28348 
28349   // PSADBW instruction horizontally add all bytes and leave the result in i64
28350   // chunks, thus directly computes the pop count for v2i64 and v4i64.
28351   if (EltVT == MVT::i64) {
28352     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
28353     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
28354     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
28355     return DAG.getBitcast(VT, V);
28356   }
28357 
28358   if (EltVT == MVT::i32) {
28359     // We unpack the low half and high half into i32s interleaved with zeros so
28360     // that we can use PSADBW to horizontally sum them. The most useful part of
28361     // this is that it lines up the results of two PSADBW instructions to be
28362     // two v2i64 vectors which concatenated are the 4 population counts. We can
28363     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
28364     SDValue Zeros = DAG.getConstant(0, DL, VT);
28365     SDValue V32 = DAG.getBitcast(VT, V);
28366     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
28367     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
28368 
28369     // Do the horizontal sums into two v2i64s.
28370     Zeros = DAG.getConstant(0, DL, ByteVecVT);
28371     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
28372     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
28373                       DAG.getBitcast(ByteVecVT, Low), Zeros);
28374     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
28375                        DAG.getBitcast(ByteVecVT, High), Zeros);
28376 
28377     // Merge them together.
28378     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
28379     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
28380                     DAG.getBitcast(ShortVecVT, Low),
28381                     DAG.getBitcast(ShortVecVT, High));
28382 
28383     return DAG.getBitcast(VT, V);
28384   }
28385 
28386   // The only element type left is i16.
28387   assert(EltVT == MVT::i16 && "Unknown how to handle type");
28388 
28389   // To obtain pop count for each i16 element starting from the pop count for
28390   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
28391   // right by 8. It is important to shift as i16s as i8 vector shift isn't
28392   // directly supported.
28393   SDValue ShifterV = DAG.getConstant(8, DL, VT);
28394   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
28395   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
28396                   DAG.getBitcast(ByteVecVT, V));
28397   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
28398 }
28399 
LowerVectorCTPOPInRegLUT(SDValue Op,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)28400 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
28401                                         const X86Subtarget &Subtarget,
28402                                         SelectionDAG &DAG) {
28403   MVT VT = Op.getSimpleValueType();
28404   MVT EltVT = VT.getVectorElementType();
28405   int NumElts = VT.getVectorNumElements();
28406   (void)EltVT;
28407   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
28408 
28409   // Implement a lookup table in register by using an algorithm based on:
28410   // http://wm.ite.pl/articles/sse-popcount.html
28411   //
28412   // The general idea is that every lower byte nibble in the input vector is an
28413   // index into a in-register pre-computed pop count table. We then split up the
28414   // input vector in two new ones: (1) a vector with only the shifted-right
28415   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
28416   // masked out higher ones) for each byte. PSHUFB is used separately with both
28417   // to index the in-register table. Next, both are added and the result is a
28418   // i8 vector where each element contains the pop count for input byte.
28419   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
28420                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
28421                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
28422                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
28423 
28424   SmallVector<SDValue, 64> LUTVec;
28425   for (int i = 0; i < NumElts; ++i)
28426     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
28427   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
28428   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
28429 
28430   // High nibbles
28431   SDValue FourV = DAG.getConstant(4, DL, VT);
28432   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
28433 
28434   // Low nibbles
28435   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
28436 
28437   // The input vector is used as the shuffle mask that index elements into the
28438   // LUT. After counting low and high nibbles, add the vector to obtain the
28439   // final pop count per i8 element.
28440   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
28441   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
28442   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
28443 }
28444 
28445 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
28446 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
LowerVectorCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28447 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
28448                                 SelectionDAG &DAG) {
28449   MVT VT = Op.getSimpleValueType();
28450   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
28451          "Unknown CTPOP type to handle");
28452   SDLoc DL(Op.getNode());
28453   SDValue Op0 = Op.getOperand(0);
28454 
28455   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
28456   if (Subtarget.hasVPOPCNTDQ()) {
28457     unsigned NumElems = VT.getVectorNumElements();
28458     assert((VT.getVectorElementType() == MVT::i8 ||
28459             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
28460     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
28461       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
28462       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
28463       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
28464       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
28465     }
28466   }
28467 
28468   // Decompose 256-bit ops into smaller 128-bit ops.
28469   if (VT.is256BitVector() && !Subtarget.hasInt256())
28470     return splitVectorIntUnary(Op, DAG);
28471 
28472   // Decompose 512-bit ops into smaller 256-bit ops.
28473   if (VT.is512BitVector() && !Subtarget.hasBWI())
28474     return splitVectorIntUnary(Op, DAG);
28475 
28476   // For element types greater than i8, do vXi8 pop counts and a bytesum.
28477   if (VT.getScalarType() != MVT::i8) {
28478     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
28479     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
28480     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
28481     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
28482   }
28483 
28484   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
28485   if (!Subtarget.hasSSSE3())
28486     return SDValue();
28487 
28488   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
28489 }
28490 
LowerCTPOP(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28491 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
28492                           SelectionDAG &DAG) {
28493   assert(Op.getSimpleValueType().isVector() &&
28494          "We only do custom lowering for vector population count.");
28495   return LowerVectorCTPOP(Op, Subtarget, DAG);
28496 }
28497 
LowerBITREVERSE_XOP(SDValue Op,SelectionDAG & DAG)28498 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
28499   MVT VT = Op.getSimpleValueType();
28500   SDValue In = Op.getOperand(0);
28501   SDLoc DL(Op);
28502 
28503   // For scalars, its still beneficial to transfer to/from the SIMD unit to
28504   // perform the BITREVERSE.
28505   if (!VT.isVector()) {
28506     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
28507     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
28508     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
28509     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
28510                        DAG.getIntPtrConstant(0, DL));
28511   }
28512 
28513   int NumElts = VT.getVectorNumElements();
28514   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
28515 
28516   // Decompose 256-bit ops into smaller 128-bit ops.
28517   if (VT.is256BitVector())
28518     return splitVectorIntUnary(Op, DAG);
28519 
28520   assert(VT.is128BitVector() &&
28521          "Only 128-bit vector bitreverse lowering supported.");
28522 
28523   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
28524   // perform the BSWAP in the shuffle.
28525   // Its best to shuffle using the second operand as this will implicitly allow
28526   // memory folding for multiple vectors.
28527   SmallVector<SDValue, 16> MaskElts;
28528   for (int i = 0; i != NumElts; ++i) {
28529     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
28530       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
28531       int PermuteByte = SourceByte | (2 << 5);
28532       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
28533     }
28534   }
28535 
28536   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
28537   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
28538   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
28539                     Res, Mask);
28540   return DAG.getBitcast(VT, Res);
28541 }
28542 
LowerBITREVERSE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28543 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
28544                                SelectionDAG &DAG) {
28545   MVT VT = Op.getSimpleValueType();
28546 
28547   if (Subtarget.hasXOP() && !VT.is512BitVector())
28548     return LowerBITREVERSE_XOP(Op, DAG);
28549 
28550   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
28551 
28552   SDValue In = Op.getOperand(0);
28553   SDLoc DL(Op);
28554 
28555   // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
28556   if (VT == MVT::v64i8 && !Subtarget.hasBWI())
28557     return splitVectorIntUnary(Op, DAG);
28558 
28559   unsigned NumElts = VT.getVectorNumElements();
28560   assert(VT.getScalarType() == MVT::i8 &&
28561          "Only byte vector BITREVERSE supported");
28562 
28563   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
28564   if (VT.is256BitVector() && !Subtarget.hasInt256())
28565     return splitVectorIntUnary(Op, DAG);
28566 
28567   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
28568   // two nibbles and a PSHUFB lookup to find the bitreverse of each
28569   // 0-15 value (moved to the other nibble).
28570   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
28571   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
28572   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
28573 
28574   const int LoLUT[16] = {
28575       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
28576       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
28577       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
28578       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
28579   const int HiLUT[16] = {
28580       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
28581       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
28582       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
28583       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
28584 
28585   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
28586   for (unsigned i = 0; i < NumElts; ++i) {
28587     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
28588     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
28589   }
28590 
28591   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
28592   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
28593   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
28594   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
28595   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
28596 }
28597 
lowerAtomicArithWithLOCK(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)28598 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
28599                                         const X86Subtarget &Subtarget) {
28600   unsigned NewOpc = 0;
28601   switch (N->getOpcode()) {
28602   case ISD::ATOMIC_LOAD_ADD:
28603     NewOpc = X86ISD::LADD;
28604     break;
28605   case ISD::ATOMIC_LOAD_SUB:
28606     NewOpc = X86ISD::LSUB;
28607     break;
28608   case ISD::ATOMIC_LOAD_OR:
28609     NewOpc = X86ISD::LOR;
28610     break;
28611   case ISD::ATOMIC_LOAD_XOR:
28612     NewOpc = X86ISD::LXOR;
28613     break;
28614   case ISD::ATOMIC_LOAD_AND:
28615     NewOpc = X86ISD::LAND;
28616     break;
28617   default:
28618     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
28619   }
28620 
28621   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
28622 
28623   return DAG.getMemIntrinsicNode(
28624       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
28625       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
28626       /*MemVT=*/N->getSimpleValueType(0), MMO);
28627 }
28628 
28629 /// Lower atomic_load_ops into LOCK-prefixed operations.
lowerAtomicArith(SDValue N,SelectionDAG & DAG,const X86Subtarget & Subtarget)28630 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
28631                                 const X86Subtarget &Subtarget) {
28632   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
28633   SDValue Chain = N->getOperand(0);
28634   SDValue LHS = N->getOperand(1);
28635   SDValue RHS = N->getOperand(2);
28636   unsigned Opc = N->getOpcode();
28637   MVT VT = N->getSimpleValueType(0);
28638   SDLoc DL(N);
28639 
28640   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
28641   // can only be lowered when the result is unused.  They should have already
28642   // been transformed into a cmpxchg loop in AtomicExpand.
28643   if (N->hasAnyUseOfValue(0)) {
28644     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
28645     // select LXADD if LOCK_SUB can't be selected.
28646     if (Opc == ISD::ATOMIC_LOAD_SUB) {
28647       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
28648       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
28649                            RHS, AN->getMemOperand());
28650     }
28651     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
28652            "Used AtomicRMW ops other than Add should have been expanded!");
28653     return N;
28654   }
28655 
28656   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
28657   // The core idea here is that since the memory location isn't actually
28658   // changing, all we need is a lowering for the *ordering* impacts of the
28659   // atomicrmw.  As such, we can chose a different operation and memory
28660   // location to minimize impact on other code.
28661   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
28662     // On X86, the only ordering which actually requires an instruction is
28663     // seq_cst which isn't SingleThread, everything just needs to be preserved
28664     // during codegen and then dropped. Note that we expect (but don't assume),
28665     // that orderings other than seq_cst and acq_rel have been canonicalized to
28666     // a store or load.
28667     if (AN->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
28668         AN->getSyncScopeID() == SyncScope::System) {
28669       // Prefer a locked operation against a stack location to minimize cache
28670       // traffic.  This assumes that stack locations are very likely to be
28671       // accessed only by the owning thread.
28672       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
28673       assert(!N->hasAnyUseOfValue(0));
28674       // NOTE: The getUNDEF is needed to give something for the unused result 0.
28675       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
28676                          DAG.getUNDEF(VT), NewChain);
28677     }
28678     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
28679     SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
28680     assert(!N->hasAnyUseOfValue(0));
28681     // NOTE: The getUNDEF is needed to give something for the unused result 0.
28682     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
28683                        DAG.getUNDEF(VT), NewChain);
28684   }
28685 
28686   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
28687   // RAUW the chain, but don't worry about the result, as it's unused.
28688   assert(!N->hasAnyUseOfValue(0));
28689   // NOTE: The getUNDEF is needed to give something for the unused result 0.
28690   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
28691                      DAG.getUNDEF(VT), LockOp.getValue(1));
28692 }
28693 
LowerATOMIC_STORE(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)28694 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
28695                                  const X86Subtarget &Subtarget) {
28696   auto *Node = cast<AtomicSDNode>(Op.getNode());
28697   SDLoc dl(Node);
28698   EVT VT = Node->getMemoryVT();
28699 
28700   bool IsSeqCst = Node->getOrdering() == AtomicOrdering::SequentiallyConsistent;
28701   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
28702 
28703   // If this store is not sequentially consistent and the type is legal
28704   // we can just keep it.
28705   if (!IsSeqCst && IsTypeLegal)
28706     return Op;
28707 
28708   if (VT == MVT::i64 && !IsTypeLegal) {
28709     // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
28710     // is enabled.
28711     bool NoImplicitFloatOps =
28712         DAG.getMachineFunction().getFunction().hasFnAttribute(
28713             Attribute::NoImplicitFloat);
28714     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
28715       SDValue Chain;
28716       if (Subtarget.hasSSE1()) {
28717         SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
28718                                        Node->getOperand(2));
28719         MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
28720         SclToVec = DAG.getBitcast(StVT, SclToVec);
28721         SDVTList Tys = DAG.getVTList(MVT::Other);
28722         SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
28723         Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
28724                                         MVT::i64, Node->getMemOperand());
28725       } else if (Subtarget.hasX87()) {
28726         // First load this into an 80-bit X87 register using a stack temporary.
28727         // This will put the whole integer into the significand.
28728         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
28729         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
28730         MachinePointerInfo MPI =
28731             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
28732         Chain =
28733             DAG.getStore(Node->getChain(), dl, Node->getOperand(2), StackPtr,
28734                          MPI, /*Align*/ 0, MachineMemOperand::MOStore);
28735         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
28736         SDValue LdOps[] = {Chain, StackPtr};
28737         SDValue Value =
28738             DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
28739                                     /*Align*/ None, MachineMemOperand::MOLoad);
28740         Chain = Value.getValue(1);
28741 
28742         // Now use an FIST to do the atomic store.
28743         SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
28744         Chain =
28745             DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
28746                                     StoreOps, MVT::i64, Node->getMemOperand());
28747       }
28748 
28749       if (Chain) {
28750         // If this is a sequentially consistent store, also emit an appropriate
28751         // barrier.
28752         if (IsSeqCst)
28753           Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
28754 
28755         return Chain;
28756       }
28757     }
28758   }
28759 
28760   // Convert seq_cst store -> xchg
28761   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
28762   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
28763   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
28764                                Node->getMemoryVT(),
28765                                Node->getOperand(0),
28766                                Node->getOperand(1), Node->getOperand(2),
28767                                Node->getMemOperand());
28768   return Swap.getValue(1);
28769 }
28770 
LowerADDSUBCARRY(SDValue Op,SelectionDAG & DAG)28771 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
28772   SDNode *N = Op.getNode();
28773   MVT VT = N->getSimpleValueType(0);
28774 
28775   // Let legalize expand this if it isn't a legal type yet.
28776   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
28777     return SDValue();
28778 
28779   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
28780   SDLoc DL(N);
28781 
28782   // Set the carry flag.
28783   SDValue Carry = Op.getOperand(2);
28784   EVT CarryVT = Carry.getValueType();
28785   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
28786                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
28787 
28788   unsigned Opc = Op.getOpcode() == ISD::ADDCARRY ? X86ISD::ADC : X86ISD::SBB;
28789   SDValue Sum = DAG.getNode(Opc, DL, VTs, Op.getOperand(0),
28790                             Op.getOperand(1), Carry.getValue(1));
28791 
28792   SDValue SetCC = getSETCC(X86::COND_B, Sum.getValue(1), DL, DAG);
28793   if (N->getValueType(1) == MVT::i1)
28794     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
28795 
28796   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
28797 }
28798 
LowerFSINCOS(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28799 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
28800                             SelectionDAG &DAG) {
28801   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
28802 
28803   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
28804   // which returns the values as { float, float } (in XMM0) or
28805   // { double, double } (which is returned in XMM0, XMM1).
28806   SDLoc dl(Op);
28807   SDValue Arg = Op.getOperand(0);
28808   EVT ArgVT = Arg.getValueType();
28809   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
28810 
28811   TargetLowering::ArgListTy Args;
28812   TargetLowering::ArgListEntry Entry;
28813 
28814   Entry.Node = Arg;
28815   Entry.Ty = ArgTy;
28816   Entry.IsSExt = false;
28817   Entry.IsZExt = false;
28818   Args.push_back(Entry);
28819 
28820   bool isF64 = ArgVT == MVT::f64;
28821   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
28822   // the small struct {f32, f32} is returned in (eax, edx). For f64,
28823   // the results are returned via SRet in memory.
28824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28825   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
28826   const char *LibcallName = TLI.getLibcallName(LC);
28827   SDValue Callee = DAG.getExternalFunctionSymbol(LibcallName);
28828 
28829   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
28830                       : (Type *)FixedVectorType::get(ArgTy, 4);
28831 
28832   TargetLowering::CallLoweringInfo CLI(DAG);
28833   CLI.setDebugLoc(dl)
28834       .setChain(DAG.getEntryNode())
28835       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
28836 
28837   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
28838 
28839   if (isF64)
28840     // Returned in xmm0 and xmm1.
28841     return CallResult.first;
28842 
28843   // Returned in bits 0:31 and 32:64 xmm0.
28844   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
28845                                CallResult.first, DAG.getIntPtrConstant(0, dl));
28846   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
28847                                CallResult.first, DAG.getIntPtrConstant(1, dl));
28848   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
28849   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
28850 }
28851 
28852 /// Widen a vector input to a vector of NVT.  The
28853 /// input vector must have the same element type as NVT.
ExtendToType(SDValue InOp,MVT NVT,SelectionDAG & DAG,bool FillWithZeroes=false)28854 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
28855                             bool FillWithZeroes = false) {
28856   // Check if InOp already has the right width.
28857   MVT InVT = InOp.getSimpleValueType();
28858   if (InVT == NVT)
28859     return InOp;
28860 
28861   if (InOp.isUndef())
28862     return DAG.getUNDEF(NVT);
28863 
28864   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
28865          "input and widen element type must match");
28866 
28867   unsigned InNumElts = InVT.getVectorNumElements();
28868   unsigned WidenNumElts = NVT.getVectorNumElements();
28869   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
28870          "Unexpected request for vector widening");
28871 
28872   SDLoc dl(InOp);
28873   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
28874       InOp.getNumOperands() == 2) {
28875     SDValue N1 = InOp.getOperand(1);
28876     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
28877         N1.isUndef()) {
28878       InOp = InOp.getOperand(0);
28879       InVT = InOp.getSimpleValueType();
28880       InNumElts = InVT.getVectorNumElements();
28881     }
28882   }
28883   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
28884       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
28885     SmallVector<SDValue, 16> Ops;
28886     for (unsigned i = 0; i < InNumElts; ++i)
28887       Ops.push_back(InOp.getOperand(i));
28888 
28889     EVT EltVT = InOp.getOperand(0).getValueType();
28890 
28891     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
28892       DAG.getUNDEF(EltVT);
28893     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
28894       Ops.push_back(FillVal);
28895     return DAG.getBuildVector(NVT, dl, Ops);
28896   }
28897   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
28898     DAG.getUNDEF(NVT);
28899   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
28900                      InOp, DAG.getIntPtrConstant(0, dl));
28901 }
28902 
LowerMSCATTER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28903 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
28904                              SelectionDAG &DAG) {
28905   assert(Subtarget.hasAVX512() &&
28906          "MGATHER/MSCATTER are supported on AVX-512 arch only");
28907 
28908   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
28909   SDValue Src = N->getValue();
28910   MVT VT = Src.getSimpleValueType();
28911   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
28912   SDLoc dl(Op);
28913 
28914   SDValue Scale = N->getScale();
28915   SDValue Index = N->getIndex();
28916   SDValue Mask = N->getMask();
28917   SDValue Chain = N->getChain();
28918   SDValue BasePtr = N->getBasePtr();
28919 
28920   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
28921     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
28922     // If the index is v2i64 and we have VLX we can use xmm for data and index.
28923     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
28924       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
28925       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
28926       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
28927       SDVTList VTs = DAG.getVTList(MVT::Other);
28928       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
28929       return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
28930                                      N->getMemoryVT(), N->getMemOperand());
28931     }
28932     return SDValue();
28933   }
28934 
28935   MVT IndexVT = Index.getSimpleValueType();
28936 
28937   // If the index is v2i32, we're being called by type legalization and we
28938   // should just let the default handling take care of it.
28939   if (IndexVT == MVT::v2i32)
28940     return SDValue();
28941 
28942   // If we don't have VLX and neither the passthru or index is 512-bits, we
28943   // need to widen until one is.
28944   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
28945       !Index.getSimpleValueType().is512BitVector()) {
28946     // Determine how much we need to widen by to get a 512-bit type.
28947     unsigned Factor = std::min(512/VT.getSizeInBits(),
28948                                512/IndexVT.getSizeInBits());
28949     unsigned NumElts = VT.getVectorNumElements() * Factor;
28950 
28951     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
28952     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
28953     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
28954 
28955     Src = ExtendToType(Src, VT, DAG);
28956     Index = ExtendToType(Index, IndexVT, DAG);
28957     Mask = ExtendToType(Mask, MaskVT, DAG, true);
28958   }
28959 
28960   SDVTList VTs = DAG.getVTList(MVT::Other);
28961   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
28962   return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
28963                                  N->getMemoryVT(), N->getMemOperand());
28964 }
28965 
LowerMLOAD(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)28966 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
28967                           SelectionDAG &DAG) {
28968 
28969   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
28970   MVT VT = Op.getSimpleValueType();
28971   MVT ScalarVT = VT.getScalarType();
28972   SDValue Mask = N->getMask();
28973   MVT MaskVT = Mask.getSimpleValueType();
28974   SDValue PassThru = N->getPassThru();
28975   SDLoc dl(Op);
28976 
28977   // Handle AVX masked loads which don't support passthru other than 0.
28978   if (MaskVT.getVectorElementType() != MVT::i1) {
28979     // We also allow undef in the isel pattern.
28980     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
28981       return Op;
28982 
28983     SDValue NewLoad = DAG.getMaskedLoad(
28984         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
28985         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
28986         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
28987         N->isExpandingLoad());
28988     // Emit a blend.
28989     SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
28990     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
28991   }
28992 
28993   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
28994          "Expanding masked load is supported on AVX-512 target only!");
28995 
28996   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
28997          "Expanding masked load is supported for 32 and 64-bit types only!");
28998 
28999   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
29000          "Cannot lower masked load op.");
29001 
29002   assert((ScalarVT.getSizeInBits() >= 32 ||
29003           (Subtarget.hasBWI() &&
29004               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
29005          "Unsupported masked load op.");
29006 
29007   // This operation is legal for targets with VLX, but without
29008   // VLX the vector should be widened to 512 bit
29009   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
29010   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
29011   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
29012 
29013   // Mask element has to be i1.
29014   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
29015          "Unexpected mask type");
29016 
29017   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
29018 
29019   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
29020   SDValue NewLoad = DAG.getMaskedLoad(
29021       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
29022       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
29023       N->getExtensionType(), N->isExpandingLoad());
29024 
29025   SDValue Extract =
29026       DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
29027                   DAG.getIntPtrConstant(0, dl));
29028   SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
29029   return DAG.getMergeValues(RetOps, dl);
29030 }
29031 
LowerMSTORE(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)29032 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
29033                            SelectionDAG &DAG) {
29034   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
29035   SDValue DataToStore = N->getValue();
29036   MVT VT = DataToStore.getSimpleValueType();
29037   MVT ScalarVT = VT.getScalarType();
29038   SDValue Mask = N->getMask();
29039   SDLoc dl(Op);
29040 
29041   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
29042          "Expanding masked load is supported on AVX-512 target only!");
29043 
29044   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
29045          "Expanding masked load is supported for 32 and 64-bit types only!");
29046 
29047   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
29048          "Cannot lower masked store op.");
29049 
29050   assert((ScalarVT.getSizeInBits() >= 32 ||
29051           (Subtarget.hasBWI() &&
29052               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
29053           "Unsupported masked store op.");
29054 
29055   // This operation is legal for targets with VLX, but without
29056   // VLX the vector should be widened to 512 bit
29057   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
29058   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
29059 
29060   // Mask element has to be i1.
29061   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
29062          "Unexpected mask type");
29063 
29064   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
29065 
29066   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
29067   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
29068   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
29069                             N->getOffset(), Mask, N->getMemoryVT(),
29070                             N->getMemOperand(), N->getAddressingMode(),
29071                             N->isTruncatingStore(), N->isCompressingStore());
29072 }
29073 
LowerMGATHER(SDValue Op,const X86Subtarget & Subtarget,SelectionDAG & DAG)29074 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
29075                             SelectionDAG &DAG) {
29076   assert(Subtarget.hasAVX2() &&
29077          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
29078 
29079   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
29080   SDLoc dl(Op);
29081   MVT VT = Op.getSimpleValueType();
29082   SDValue Index = N->getIndex();
29083   SDValue Mask = N->getMask();
29084   SDValue PassThru = N->getPassThru();
29085   MVT IndexVT = Index.getSimpleValueType();
29086 
29087   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
29088 
29089   // If the index is v2i32, we're being called by type legalization.
29090   if (IndexVT == MVT::v2i32)
29091     return SDValue();
29092 
29093   // If we don't have VLX and neither the passthru or index is 512-bits, we
29094   // need to widen until one is.
29095   MVT OrigVT = VT;
29096   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
29097       !IndexVT.is512BitVector()) {
29098     // Determine how much we need to widen by to get a 512-bit type.
29099     unsigned Factor = std::min(512/VT.getSizeInBits(),
29100                                512/IndexVT.getSizeInBits());
29101 
29102     unsigned NumElts = VT.getVectorNumElements() * Factor;
29103 
29104     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
29105     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
29106     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
29107 
29108     PassThru = ExtendToType(PassThru, VT, DAG);
29109     Index = ExtendToType(Index, IndexVT, DAG);
29110     Mask = ExtendToType(Mask, MaskVT, DAG, true);
29111   }
29112 
29113   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
29114                     N->getScale() };
29115   SDValue NewGather = DAG.getMemIntrinsicNode(
29116       X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
29117       N->getMemOperand());
29118   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
29119                                 NewGather, DAG.getIntPtrConstant(0, dl));
29120   return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
29121 }
29122 
LowerADDRSPACECAST(SDValue Op,SelectionDAG & DAG)29123 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
29124   SDLoc dl(Op);
29125   SDValue Src = Op.getOperand(0);
29126   MVT DstVT = Op.getSimpleValueType();
29127 
29128   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
29129   unsigned SrcAS = N->getSrcAddressSpace();
29130 
29131   assert(SrcAS != N->getDestAddressSpace() &&
29132          "addrspacecast must be between different address spaces");
29133 
29134   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
29135     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
29136   } else if (DstVT == MVT::i64) {
29137     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
29138   } else if (DstVT == MVT::i32) {
29139     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
29140   } else {
29141     report_fatal_error("Bad address space in addrspacecast");
29142   }
29143   return Op;
29144 }
29145 
LowerGC_TRANSITION(SDValue Op,SelectionDAG & DAG) const29146 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
29147                                               SelectionDAG &DAG) const {
29148   // TODO: Eventually, the lowering of these nodes should be informed by or
29149   // deferred to the GC strategy for the function in which they appear. For
29150   // now, however, they must be lowered to something. Since they are logically
29151   // no-ops in the case of a null GC strategy (or a GC strategy which does not
29152   // require special handling for these nodes), lower them as literal NOOPs for
29153   // the time being.
29154   SmallVector<SDValue, 2> Ops;
29155 
29156   Ops.push_back(Op.getOperand(0));
29157   if (Op->getGluedNode())
29158     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
29159 
29160   SDLoc OpDL(Op);
29161   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
29162   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
29163 
29164   return NOOP;
29165 }
29166 
LowerF128Call(SDValue Op,SelectionDAG & DAG,RTLIB::Libcall Call) const29167 SDValue X86TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
29168                                          RTLIB::Libcall Call) const {
29169 
29170   bool IsStrict = Op->isStrictFPOpcode();
29171   unsigned Offset = IsStrict ? 1 : 0;
29172   SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end());
29173 
29174   SDLoc dl(Op);
29175   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
29176   MakeLibCallOptions CallOptions;
29177   std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, Call, MVT::f128, Ops,
29178                                                 CallOptions, dl, Chain);
29179 
29180   if (IsStrict)
29181     return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
29182 
29183   return Tmp.first;
29184 }
29185 
29186 // Custom split CVTPS2PH with wide types.
LowerCVTPS2PH(SDValue Op,SelectionDAG & DAG)29187 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
29188   SDLoc dl(Op);
29189   EVT VT = Op.getValueType();
29190   SDValue Lo, Hi;
29191   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
29192   EVT LoVT, HiVT;
29193   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
29194   SDValue RC = Op.getOperand(1);
29195   Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
29196   Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
29197   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29198 }
29199 
29200 /// Provide custom lowering hooks for some operations.
LowerOperation(SDValue Op,SelectionDAG & DAG) const29201 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
29202   switch (Op.getOpcode()) {
29203   default: llvm_unreachable("Should not custom lower this!");
29204   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
29205   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
29206     return LowerCMP_SWAP(Op, Subtarget, DAG);
29207   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
29208   case ISD::ATOMIC_LOAD_ADD:
29209   case ISD::ATOMIC_LOAD_SUB:
29210   case ISD::ATOMIC_LOAD_OR:
29211   case ISD::ATOMIC_LOAD_XOR:
29212   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
29213   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
29214   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
29215   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
29216   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
29217   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
29218   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
29219   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
29220   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
29221   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
29222   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
29223   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
29224   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
29225   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
29226   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
29227   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
29228   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
29229   case ISD::SHL_PARTS:
29230   case ISD::SRA_PARTS:
29231   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
29232   case ISD::FSHL:
29233   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
29234   case ISD::STRICT_SINT_TO_FP:
29235   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
29236   case ISD::STRICT_UINT_TO_FP:
29237   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
29238   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
29239   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
29240   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
29241   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
29242   case ISD::ZERO_EXTEND_VECTOR_INREG:
29243   case ISD::SIGN_EXTEND_VECTOR_INREG:
29244     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
29245   case ISD::FP_TO_SINT:
29246   case ISD::STRICT_FP_TO_SINT:
29247   case ISD::FP_TO_UINT:
29248   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
29249   case ISD::FP_EXTEND:
29250   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
29251   case ISD::FP_ROUND:
29252   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
29253   case ISD::FP16_TO_FP:
29254   case ISD::STRICT_FP16_TO_FP:  return LowerFP16_TO_FP(Op, DAG);
29255   case ISD::FP_TO_FP16:
29256   case ISD::STRICT_FP_TO_FP16:  return LowerFP_TO_FP16(Op, DAG);
29257   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
29258   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
29259   case ISD::FADD:
29260   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
29261   case ISD::FROUND:             return LowerFROUND(Op, DAG);
29262   case ISD::FABS:
29263   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
29264   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
29265   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
29266   case ISD::LRINT:
29267   case ISD::LLRINT:             return LowerLRINT_LLRINT(Op, DAG);
29268   case ISD::SETCC:
29269   case ISD::STRICT_FSETCC:
29270   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
29271   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
29272   case ISD::SELECT:             return LowerSELECT(Op, DAG);
29273   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
29274   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
29275   case ISD::VASTART:            return LowerVASTART(Op, DAG);
29276   case ISD::VAARG:              return LowerVAARG(Op, DAG);
29277   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
29278   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
29279   case ISD::INTRINSIC_VOID:
29280   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
29281   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
29282   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
29283   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
29284   case ISD::FRAME_TO_ARGS_OFFSET:
29285                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
29286   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
29287   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
29288   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
29289   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
29290   case ISD::EH_SJLJ_SETUP_DISPATCH:
29291     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
29292   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
29293   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
29294   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
29295   case ISD::CTLZ:
29296   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
29297   case ISD::CTTZ:
29298   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
29299   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
29300   case ISD::MULHS:
29301   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
29302   case ISD::ROTL:
29303   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
29304   case ISD::SRA:
29305   case ISD::SRL:
29306   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
29307   case ISD::SADDO:
29308   case ISD::UADDO:
29309   case ISD::SSUBO:
29310   case ISD::USUBO:
29311   case ISD::SMULO:
29312   case ISD::UMULO:              return LowerXALUO(Op, DAG);
29313   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
29314   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
29315   case ISD::ADDCARRY:
29316   case ISD::SUBCARRY:           return LowerADDSUBCARRY(Op, DAG);
29317   case ISD::ADD:
29318   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
29319   case ISD::UADDSAT:
29320   case ISD::SADDSAT:
29321   case ISD::USUBSAT:
29322   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
29323   case ISD::SMAX:
29324   case ISD::SMIN:
29325   case ISD::UMAX:
29326   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
29327   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
29328   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
29329   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
29330   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
29331   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
29332   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
29333   case ISD::GC_TRANSITION_START:
29334   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
29335   case ISD::ADDRSPACECAST:      return LowerADDRSPACECAST(Op, DAG);
29336   case X86ISD::CVTPS2PH:        return LowerCVTPS2PH(Op, DAG);
29337   }
29338 }
29339 
29340 /// Places new result values for the node in Results (their number
29341 /// and types must exactly match those of the original return values of
29342 /// the node), or leaves Results empty, which indicates that the node is not
29343 /// to be custom lowered after all.
LowerOperationWrapper(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const29344 void X86TargetLowering::LowerOperationWrapper(SDNode *N,
29345                                               SmallVectorImpl<SDValue> &Results,
29346                                               SelectionDAG &DAG) const {
29347   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
29348 
29349   if (!Res.getNode())
29350     return;
29351 
29352   // If the original node has one result, take the return value from
29353   // LowerOperation as is. It might not be result number 0.
29354   if (N->getNumValues() == 1) {
29355     Results.push_back(Res);
29356     return;
29357   }
29358 
29359   // If the original node has multiple results, then the return node should
29360   // have the same number of results.
29361   assert((N->getNumValues() == Res->getNumValues()) &&
29362       "Lowering returned the wrong number of results!");
29363 
29364   // Places new result values base on N result number.
29365   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
29366     Results.push_back(Res.getValue(I));
29367 }
29368 
29369 /// Replace a node with an illegal result type with a new node built out of
29370 /// custom code.
ReplaceNodeResults(SDNode * N,SmallVectorImpl<SDValue> & Results,SelectionDAG & DAG) const29371 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
29372                                            SmallVectorImpl<SDValue>&Results,
29373                                            SelectionDAG &DAG) const {
29374   SDLoc dl(N);
29375   switch (N->getOpcode()) {
29376   default:
29377 #ifndef NDEBUG
29378     dbgs() << "ReplaceNodeResults: ";
29379     N->dump(&DAG);
29380 #endif
29381     llvm_unreachable("Do not know how to custom type legalize this operation!");
29382   case X86ISD::CVTPH2PS: {
29383     EVT VT = N->getValueType(0);
29384     SDValue Lo, Hi;
29385     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
29386     EVT LoVT, HiVT;
29387     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
29388     Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
29389     Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
29390     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29391     Results.push_back(Res);
29392     return;
29393   }
29394   case X86ISD::STRICT_CVTPH2PS: {
29395     EVT VT = N->getValueType(0);
29396     SDValue Lo, Hi;
29397     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
29398     EVT LoVT, HiVT;
29399     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
29400     Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
29401                      {N->getOperand(0), Lo});
29402     Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
29403                      {N->getOperand(0), Hi});
29404     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
29405                                 Lo.getValue(1), Hi.getValue(1));
29406     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29407     Results.push_back(Res);
29408     Results.push_back(Chain);
29409     return;
29410   }
29411   case ISD::CTPOP: {
29412     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
29413     // Use a v2i64 if possible.
29414     bool NoImplicitFloatOps =
29415         DAG.getMachineFunction().getFunction().hasFnAttribute(
29416             Attribute::NoImplicitFloat);
29417     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
29418       SDValue Wide =
29419           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
29420       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
29421       // Bit count should fit in 32-bits, extract it as that and then zero
29422       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
29423       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
29424       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
29425                          DAG.getIntPtrConstant(0, dl));
29426       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
29427       Results.push_back(Wide);
29428     }
29429     return;
29430   }
29431   case ISD::MUL: {
29432     EVT VT = N->getValueType(0);
29433     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29434            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
29435     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
29436     // elements are needed.
29437     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
29438     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
29439     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
29440     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
29441     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
29442     unsigned NumConcats = 16 / VT.getVectorNumElements();
29443     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
29444     ConcatOps[0] = Res;
29445     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
29446     Results.push_back(Res);
29447     return;
29448   }
29449   case X86ISD::VPMADDWD:
29450   case X86ISD::AVG: {
29451     // Legalize types for X86ISD::AVG/VPMADDWD by widening.
29452     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
29453 
29454     EVT VT = N->getValueType(0);
29455     EVT InVT = N->getOperand(0).getValueType();
29456     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
29457            "Expected a VT that divides into 128 bits.");
29458     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29459            "Unexpected type action!");
29460     unsigned NumConcat = 128 / InVT.getSizeInBits();
29461 
29462     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
29463                                     InVT.getVectorElementType(),
29464                                     NumConcat * InVT.getVectorNumElements());
29465     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
29466                                   VT.getVectorElementType(),
29467                                   NumConcat * VT.getVectorNumElements());
29468 
29469     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
29470     Ops[0] = N->getOperand(0);
29471     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
29472     Ops[0] = N->getOperand(1);
29473     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
29474 
29475     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
29476     Results.push_back(Res);
29477     return;
29478   }
29479   case ISD::ABS: {
29480     assert(N->getValueType(0) == MVT::i64 &&
29481            "Unexpected type (!= i64) on ABS.");
29482     MVT HalfT = MVT::i32;
29483     SDValue Lo, Hi, Tmp;
29484     SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
29485 
29486     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
29487                      DAG.getConstant(0, dl, HalfT));
29488     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
29489                      DAG.getConstant(1, dl, HalfT));
29490     Tmp = DAG.getNode(
29491         ISD::SRA, dl, HalfT, Hi,
29492         DAG.getShiftAmountConstant(HalfT.getSizeInBits() - 1, HalfT, dl));
29493     Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
29494     Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
29495                      SDValue(Lo.getNode(), 1));
29496     Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
29497     Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
29498     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi));
29499     return;
29500   }
29501   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
29502   case X86ISD::FMINC:
29503   case X86ISD::FMIN:
29504   case X86ISD::FMAXC:
29505   case X86ISD::FMAX: {
29506     EVT VT = N->getValueType(0);
29507     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
29508     SDValue UNDEF = DAG.getUNDEF(VT);
29509     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
29510                               N->getOperand(0), UNDEF);
29511     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
29512                               N->getOperand(1), UNDEF);
29513     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
29514     return;
29515   }
29516   case ISD::SDIV:
29517   case ISD::UDIV:
29518   case ISD::SREM:
29519   case ISD::UREM: {
29520     EVT VT = N->getValueType(0);
29521     if (VT.isVector()) {
29522       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29523              "Unexpected type action!");
29524       // If this RHS is a constant splat vector we can widen this and let
29525       // division/remainder by constant optimize it.
29526       // TODO: Can we do something for non-splat?
29527       APInt SplatVal;
29528       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
29529         unsigned NumConcats = 128 / VT.getSizeInBits();
29530         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
29531         Ops0[0] = N->getOperand(0);
29532         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
29533         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
29534         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
29535         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
29536         Results.push_back(Res);
29537       }
29538       return;
29539     }
29540 
29541     LLVM_FALLTHROUGH;
29542   }
29543   case ISD::SDIVREM:
29544   case ISD::UDIVREM: {
29545     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
29546     Results.push_back(V);
29547     return;
29548   }
29549   case ISD::TRUNCATE: {
29550     MVT VT = N->getSimpleValueType(0);
29551     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
29552       return;
29553 
29554     // The generic legalizer will try to widen the input type to the same
29555     // number of elements as the widened result type. But this isn't always
29556     // the best thing so do some custom legalization to avoid some cases.
29557     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
29558     SDValue In = N->getOperand(0);
29559     EVT InVT = In.getValueType();
29560 
29561     unsigned InBits = InVT.getSizeInBits();
29562     if (128 % InBits == 0) {
29563       // 128 bit and smaller inputs should avoid truncate all together and
29564       // just use a build_vector that will become a shuffle.
29565       // TODO: Widen and use a shuffle directly?
29566       MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
29567       EVT EltVT = VT.getVectorElementType();
29568       unsigned WidenNumElts = WidenVT.getVectorNumElements();
29569       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
29570       // Use the original element count so we don't do more scalar opts than
29571       // necessary.
29572       unsigned MinElts = VT.getVectorNumElements();
29573       for (unsigned i=0; i < MinElts; ++i) {
29574         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
29575                                   DAG.getIntPtrConstant(i, dl));
29576         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
29577       }
29578       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
29579       return;
29580     }
29581     // With AVX512 there are some cases that can use a target specific
29582     // truncate node to go from 256/512 to less than 128 with zeros in the
29583     // upper elements of the 128 bit result.
29584     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
29585       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
29586       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
29587         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
29588         return;
29589       }
29590       // There's one case we can widen to 512 bits and use VTRUNC.
29591       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
29592         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
29593                          DAG.getUNDEF(MVT::v4i64));
29594         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
29595         return;
29596       }
29597     }
29598     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
29599         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
29600         isTypeLegal(MVT::v4i64)) {
29601       // Input needs to be split and output needs to widened. Let's use two
29602       // VTRUNCs, and shuffle their results together into the wider type.
29603       SDValue Lo, Hi;
29604       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
29605 
29606       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
29607       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
29608       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
29609                                          { 0,  1,  2,  3, 16, 17, 18, 19,
29610                                           -1, -1, -1, -1, -1, -1, -1, -1 });
29611       Results.push_back(Res);
29612       return;
29613     }
29614 
29615     return;
29616   }
29617   case ISD::ANY_EXTEND:
29618     // Right now, only MVT::v8i8 has Custom action for an illegal type.
29619     // It's intended to custom handle the input type.
29620     assert(N->getValueType(0) == MVT::v8i8 &&
29621            "Do not know how to legalize this Node");
29622     return;
29623   case ISD::SIGN_EXTEND:
29624   case ISD::ZERO_EXTEND: {
29625     EVT VT = N->getValueType(0);
29626     SDValue In = N->getOperand(0);
29627     EVT InVT = In.getValueType();
29628     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
29629         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
29630       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
29631              "Unexpected type action!");
29632       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
29633       // Custom split this so we can extend i8/i16->i32 invec. This is better
29634       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
29635       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
29636       // we allow the sra from the extend to i32 to be shared by the split.
29637       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
29638 
29639       // Fill a vector with sign bits for each element.
29640       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
29641       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
29642 
29643       // Create an unpackl and unpackh to interleave the sign bits then bitcast
29644       // to v2i64.
29645       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
29646                                         {0, 4, 1, 5});
29647       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
29648       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
29649                                         {2, 6, 3, 7});
29650       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
29651 
29652       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29653       Results.push_back(Res);
29654       return;
29655     }
29656 
29657     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
29658       if (!InVT.is128BitVector()) {
29659         // Not a 128 bit vector, but maybe type legalization will promote
29660         // it to 128 bits.
29661         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
29662           return;
29663         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
29664         if (!InVT.is128BitVector())
29665           return;
29666 
29667         // Promote the input to 128 bits. Type legalization will turn this into
29668         // zext_inreg/sext_inreg.
29669         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
29670       }
29671 
29672       // Perform custom splitting instead of the two stage extend we would get
29673       // by default.
29674       EVT LoVT, HiVT;
29675       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
29676       assert(isTypeLegal(LoVT) && "Split VT not legal?");
29677 
29678       SDValue Lo = getExtendInVec(N->getOpcode(), dl, LoVT, In, DAG);
29679 
29680       // We need to shift the input over by half the number of elements.
29681       unsigned NumElts = InVT.getVectorNumElements();
29682       unsigned HalfNumElts = NumElts / 2;
29683       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
29684       for (unsigned i = 0; i != HalfNumElts; ++i)
29685         ShufMask[i] = i + HalfNumElts;
29686 
29687       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
29688       Hi = getExtendInVec(N->getOpcode(), dl, HiVT, Hi, DAG);
29689 
29690       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29691       Results.push_back(Res);
29692     }
29693     return;
29694   }
29695   case ISD::FP_TO_SINT:
29696   case ISD::STRICT_FP_TO_SINT:
29697   case ISD::FP_TO_UINT:
29698   case ISD::STRICT_FP_TO_UINT: {
29699     bool IsStrict = N->isStrictFPOpcode();
29700     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
29701                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
29702     EVT VT = N->getValueType(0);
29703     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
29704     EVT SrcVT = Src.getValueType();
29705 
29706     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
29707       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29708              "Unexpected type action!");
29709 
29710       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
29711       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
29712       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
29713                                        VT.getVectorNumElements());
29714       SDValue Res;
29715       SDValue Chain;
29716       if (IsStrict) {
29717         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
29718                           {N->getOperand(0), Src});
29719         Chain = Res.getValue(1);
29720       } else
29721         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
29722 
29723       // Preserve what we know about the size of the original result. Except
29724       // when the result is v2i32 since we can't widen the assert.
29725       if (PromoteVT != MVT::v2i32)
29726         Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext,
29727                           dl, PromoteVT, Res,
29728                           DAG.getValueType(VT.getVectorElementType()));
29729 
29730       // Truncate back to the original width.
29731       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
29732 
29733       // Now widen to 128 bits.
29734       unsigned NumConcats = 128 / VT.getSizeInBits();
29735       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
29736                                       VT.getVectorNumElements() * NumConcats);
29737       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
29738       ConcatOps[0] = Res;
29739       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
29740       Results.push_back(Res);
29741       if (IsStrict)
29742         Results.push_back(Chain);
29743       return;
29744     }
29745 
29746 
29747     if (VT == MVT::v2i32) {
29748       assert((IsSigned || Subtarget.hasAVX512()) &&
29749              "Can only handle signed conversion without AVX512");
29750       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
29751       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
29752              "Unexpected type action!");
29753       if (Src.getValueType() == MVT::v2f64) {
29754         unsigned Opc;
29755         if (IsStrict)
29756           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
29757         else
29758           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
29759 
29760         // If we have VLX we can emit a target specific FP_TO_UINT node,.
29761         if (!IsSigned && !Subtarget.hasVLX()) {
29762           // Otherwise we can defer to the generic legalizer which will widen
29763           // the input as well. This will be further widened during op
29764           // legalization to v8i32<-v8f64.
29765           // For strict nodes we'll need to widen ourselves.
29766           // FIXME: Fix the type legalizer to safely widen strict nodes?
29767           if (!IsStrict)
29768             return;
29769           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
29770                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
29771           Opc = N->getOpcode();
29772         }
29773         SDValue Res;
29774         SDValue Chain;
29775         if (IsStrict) {
29776           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
29777                             {N->getOperand(0), Src});
29778           Chain = Res.getValue(1);
29779         } else {
29780           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
29781         }
29782         Results.push_back(Res);
29783         if (IsStrict)
29784           Results.push_back(Chain);
29785         return;
29786       }
29787 
29788       // Custom widen strict v2f32->v2i32 by padding with zeros.
29789       // FIXME: Should generic type legalizer do this?
29790       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
29791         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
29792                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
29793         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
29794                                   {N->getOperand(0), Src});
29795         Results.push_back(Res);
29796         Results.push_back(Res.getValue(1));
29797         return;
29798       }
29799 
29800       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
29801       // so early out here.
29802       return;
29803     }
29804 
29805     assert(!VT.isVector() && "Vectors should have been handled above!");
29806 
29807     if (Subtarget.hasDQI() && VT == MVT::i64 &&
29808         (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
29809       assert(!Subtarget.is64Bit() && "i64 should be legal");
29810       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
29811       // If we use a 128-bit result we might need to use a target specific node.
29812       unsigned SrcElts =
29813           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
29814       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
29815       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
29816       unsigned Opc = N->getOpcode();
29817       if (NumElts != SrcElts) {
29818         if (IsStrict)
29819           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
29820         else
29821           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
29822       }
29823 
29824       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
29825       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
29826                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
29827                                 ZeroIdx);
29828       SDValue Chain;
29829       if (IsStrict) {
29830         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
29831         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
29832         Chain = Res.getValue(1);
29833       } else
29834         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
29835       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
29836       Results.push_back(Res);
29837       if (IsStrict)
29838         Results.push_back(Chain);
29839       return;
29840     }
29841 
29842     SDValue Chain;
29843     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
29844       Results.push_back(V);
29845       if (IsStrict)
29846         Results.push_back(Chain);
29847     }
29848     return;
29849   }
29850   case ISD::LRINT:
29851   case ISD::LLRINT: {
29852     if (SDValue V = LRINT_LLRINTHelper(N, DAG))
29853       Results.push_back(V);
29854     return;
29855   }
29856 
29857   case ISD::SINT_TO_FP:
29858   case ISD::STRICT_SINT_TO_FP:
29859   case ISD::UINT_TO_FP:
29860   case ISD::STRICT_UINT_TO_FP: {
29861     bool IsStrict = N->isStrictFPOpcode();
29862     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
29863                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
29864     EVT VT = N->getValueType(0);
29865     if (VT != MVT::v2f32)
29866       return;
29867     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
29868     EVT SrcVT = Src.getValueType();
29869     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
29870       if (IsStrict) {
29871         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
29872                                 : X86ISD::STRICT_CVTUI2P;
29873         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
29874                                   {N->getOperand(0), Src});
29875         Results.push_back(Res);
29876         Results.push_back(Res.getValue(1));
29877       } else {
29878         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
29879         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
29880       }
29881       return;
29882     }
29883     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
29884         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
29885       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
29886       SDValue One  = DAG.getConstant(1, dl, SrcVT);
29887       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
29888                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
29889                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
29890       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
29891       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
29892       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
29893       for (int i = 0; i != 2; ++i) {
29894         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
29895                                   SignSrc, DAG.getIntPtrConstant(i, dl));
29896         if (IsStrict)
29897           SignCvts[i] =
29898               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
29899                           {N->getOperand(0), Elt});
29900         else
29901           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
29902       };
29903       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
29904       SDValue Slow, Chain;
29905       if (IsStrict) {
29906         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
29907                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
29908         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
29909                            {Chain, SignCvt, SignCvt});
29910         Chain = Slow.getValue(1);
29911       } else {
29912         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
29913       }
29914       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
29915       IsNeg =
29916           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
29917       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
29918       Results.push_back(Cvt);
29919       if (IsStrict)
29920         Results.push_back(Chain);
29921       return;
29922     }
29923 
29924     if (SrcVT != MVT::v2i32)
29925       return;
29926 
29927     if (IsSigned || Subtarget.hasAVX512()) {
29928       if (!IsStrict)
29929         return;
29930 
29931       // Custom widen strict v2i32->v2f32 to avoid scalarization.
29932       // FIXME: Should generic type legalizer do this?
29933       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
29934                         DAG.getConstant(0, dl, MVT::v2i32));
29935       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
29936                                 {N->getOperand(0), Src});
29937       Results.push_back(Res);
29938       Results.push_back(Res.getValue(1));
29939       return;
29940     }
29941 
29942     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
29943     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
29944     SDValue VBias =
29945         DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
29946     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
29947                              DAG.getBitcast(MVT::v2i64, VBias));
29948     Or = DAG.getBitcast(MVT::v2f64, Or);
29949     if (IsStrict) {
29950       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
29951                                 {N->getOperand(0), Or, VBias});
29952       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
29953                                 {MVT::v4f32, MVT::Other},
29954                                 {Sub.getValue(1), Sub});
29955       Results.push_back(Res);
29956       Results.push_back(Res.getValue(1));
29957     } else {
29958       // TODO: Are there any fast-math-flags to propagate here?
29959       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
29960       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
29961     }
29962     return;
29963   }
29964   case ISD::STRICT_FP_ROUND:
29965   case ISD::FP_ROUND: {
29966     bool IsStrict = N->isStrictFPOpcode();
29967     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
29968     if (!isTypeLegal(Src.getValueType()))
29969       return;
29970     SDValue V;
29971     if (IsStrict)
29972       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {MVT::v4f32, MVT::Other},
29973                       {N->getOperand(0), N->getOperand(1)});
29974     else
29975       V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
29976     Results.push_back(V);
29977     if (IsStrict)
29978       Results.push_back(V.getValue(1));
29979     return;
29980   }
29981   case ISD::FP_EXTEND:
29982   case ISD::STRICT_FP_EXTEND: {
29983     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
29984     // No other ValueType for FP_EXTEND should reach this point.
29985     assert(N->getValueType(0) == MVT::v2f32 &&
29986            "Do not know how to legalize this Node");
29987     return;
29988   }
29989   case ISD::INTRINSIC_W_CHAIN: {
29990     unsigned IntNo = N->getConstantOperandVal(1);
29991     switch (IntNo) {
29992     default : llvm_unreachable("Do not know how to custom type "
29993                                "legalize this intrinsic operation!");
29994     case Intrinsic::x86_rdtsc:
29995       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
29996                                      Results);
29997     case Intrinsic::x86_rdtscp:
29998       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
29999                                      Results);
30000     case Intrinsic::x86_rdpmc:
30001       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
30002                                   Results);
30003       return;
30004     case Intrinsic::x86_xgetbv:
30005       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
30006                                   Results);
30007       return;
30008     }
30009   }
30010   case ISD::READCYCLECOUNTER: {
30011     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
30012   }
30013   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
30014     EVT T = N->getValueType(0);
30015     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
30016     bool Regs64bit = T == MVT::i128;
30017     assert((!Regs64bit || Subtarget.hasCmpxchg16b()) &&
30018            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
30019     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
30020     SDValue cpInL, cpInH;
30021     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
30022                         DAG.getConstant(0, dl, HalfT));
30023     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
30024                         DAG.getConstant(1, dl, HalfT));
30025     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
30026                              Regs64bit ? X86::RAX : X86::EAX,
30027                              cpInL, SDValue());
30028     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
30029                              Regs64bit ? X86::RDX : X86::EDX,
30030                              cpInH, cpInL.getValue(1));
30031     SDValue swapInL, swapInH;
30032     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
30033                           DAG.getConstant(0, dl, HalfT));
30034     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
30035                           DAG.getConstant(1, dl, HalfT));
30036     swapInH =
30037         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
30038                          swapInH, cpInH.getValue(1));
30039     // If the current function needs the base pointer, RBX,
30040     // we shouldn't use cmpxchg directly.
30041     // Indeed the lowering of that instruction will clobber
30042     // that register and since RBX will be a reserved register
30043     // the register allocator will not make sure its value will
30044     // be properly saved and restored around this live-range.
30045     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
30046     SDValue Result;
30047     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
30048     Register BasePtr = TRI->getBaseRegister();
30049     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
30050     if (TRI->hasBasePointer(DAG.getMachineFunction()) &&
30051         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
30052       // ISel prefers the LCMPXCHG64 variant.
30053       // If that assert breaks, that means it is not the case anymore,
30054       // and we need to teach LCMPXCHG8_SAVE_EBX_DAG how to save RBX,
30055       // not just EBX. This is a matter of accepting i64 input for that
30056       // pseudo, and restoring into the register of the right wide
30057       // in expand pseudo. Everything else should just work.
30058       assert(((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) &&
30059              "Saving only half of the RBX");
30060       unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_SAVE_RBX_DAG
30061                                   : X86ISD::LCMPXCHG8_SAVE_EBX_DAG;
30062       SDValue RBXSave = DAG.getCopyFromReg(swapInH.getValue(0), dl,
30063                                            Regs64bit ? X86::RBX : X86::EBX,
30064                                            HalfT, swapInH.getValue(1));
30065       SDValue Ops[] = {/*Chain*/ RBXSave.getValue(1), N->getOperand(1), swapInL,
30066                        RBXSave,
30067                        /*Glue*/ RBXSave.getValue(2)};
30068       Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
30069     } else {
30070       unsigned Opcode =
30071           Regs64bit ? X86ISD::LCMPXCHG16_DAG : X86ISD::LCMPXCHG8_DAG;
30072       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl,
30073                                  Regs64bit ? X86::RBX : X86::EBX, swapInL,
30074                                  swapInH.getValue(1));
30075       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
30076                        swapInL.getValue(1)};
30077       Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
30078     }
30079     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
30080                                         Regs64bit ? X86::RAX : X86::EAX,
30081                                         HalfT, Result.getValue(1));
30082     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
30083                                         Regs64bit ? X86::RDX : X86::EDX,
30084                                         HalfT, cpOutL.getValue(2));
30085     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
30086 
30087     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
30088                                         MVT::i32, cpOutH.getValue(2));
30089     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
30090     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
30091 
30092     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
30093     Results.push_back(Success);
30094     Results.push_back(EFLAGS.getValue(1));
30095     return;
30096   }
30097   case ISD::ATOMIC_LOAD: {
30098     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
30099     bool NoImplicitFloatOps =
30100         DAG.getMachineFunction().getFunction().hasFnAttribute(
30101             Attribute::NoImplicitFloat);
30102     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
30103       auto *Node = cast<AtomicSDNode>(N);
30104       if (Subtarget.hasSSE1()) {
30105         // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
30106         // Then extract the lower 64-bits.
30107         MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
30108         SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
30109         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
30110         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
30111                                              MVT::i64, Node->getMemOperand());
30112         if (Subtarget.hasSSE2()) {
30113           SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
30114                                     DAG.getIntPtrConstant(0, dl));
30115           Results.push_back(Res);
30116           Results.push_back(Ld.getValue(1));
30117           return;
30118         }
30119         // We use an alternative sequence for SSE1 that extracts as v2f32 and
30120         // then casts to i64. This avoids a 128-bit stack temporary being
30121         // created by type legalization if we were to cast v4f32->v2i64.
30122         SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
30123                                   DAG.getIntPtrConstant(0, dl));
30124         Res = DAG.getBitcast(MVT::i64, Res);
30125         Results.push_back(Res);
30126         Results.push_back(Ld.getValue(1));
30127         return;
30128       }
30129       if (Subtarget.hasX87()) {
30130         // First load this into an 80-bit X87 register. This will put the whole
30131         // integer into the significand.
30132         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
30133         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
30134         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
30135                                                  dl, Tys, Ops, MVT::i64,
30136                                                  Node->getMemOperand());
30137         SDValue Chain = Result.getValue(1);
30138 
30139         // Now store the X87 register to a stack temporary and convert to i64.
30140         // This store is not atomic and doesn't need to be.
30141         // FIXME: We don't need a stack temporary if the result of the load
30142         // is already being stored. We could just directly store there.
30143         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
30144         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
30145         MachinePointerInfo MPI =
30146             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
30147         SDValue StoreOps[] = { Chain, Result, StackPtr };
30148         Chain = DAG.getMemIntrinsicNode(
30149             X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
30150             MPI, None /*Align*/, MachineMemOperand::MOStore);
30151 
30152         // Finally load the value back from the stack temporary and return it.
30153         // This load is not atomic and doesn't need to be.
30154         // This load will be further type legalized.
30155         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
30156         Results.push_back(Result);
30157         Results.push_back(Result.getValue(1));
30158         return;
30159       }
30160     }
30161     // TODO: Use MOVLPS when SSE1 is available?
30162     // Delegate to generic TypeLegalization. Situations we can really handle
30163     // should have already been dealt with by AtomicExpandPass.cpp.
30164     break;
30165   }
30166   case ISD::ATOMIC_SWAP:
30167   case ISD::ATOMIC_LOAD_ADD:
30168   case ISD::ATOMIC_LOAD_SUB:
30169   case ISD::ATOMIC_LOAD_AND:
30170   case ISD::ATOMIC_LOAD_OR:
30171   case ISD::ATOMIC_LOAD_XOR:
30172   case ISD::ATOMIC_LOAD_NAND:
30173   case ISD::ATOMIC_LOAD_MIN:
30174   case ISD::ATOMIC_LOAD_MAX:
30175   case ISD::ATOMIC_LOAD_UMIN:
30176   case ISD::ATOMIC_LOAD_UMAX:
30177     // Delegate to generic TypeLegalization. Situations we can really handle
30178     // should have already been dealt with by AtomicExpandPass.cpp.
30179     break;
30180 
30181   case ISD::BITCAST: {
30182     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30183     EVT DstVT = N->getValueType(0);
30184     EVT SrcVT = N->getOperand(0).getValueType();
30185 
30186     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
30187     // we can split using the k-register rather than memory.
30188     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
30189       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
30190       SDValue Lo, Hi;
30191       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
30192       Lo = DAG.getBitcast(MVT::i32, Lo);
30193       Hi = DAG.getBitcast(MVT::i32, Hi);
30194       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
30195       Results.push_back(Res);
30196       return;
30197     }
30198 
30199     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
30200       // FIXME: Use v4f32 for SSE1?
30201       assert(Subtarget.hasSSE2() && "Requires SSE2");
30202       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
30203              "Unexpected type action!");
30204       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
30205       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
30206                                 N->getOperand(0));
30207       Res = DAG.getBitcast(WideVT, Res);
30208       Results.push_back(Res);
30209       return;
30210     }
30211 
30212     return;
30213   }
30214   case ISD::MGATHER: {
30215     EVT VT = N->getValueType(0);
30216     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
30217         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
30218       auto *Gather = cast<MaskedGatherSDNode>(N);
30219       SDValue Index = Gather->getIndex();
30220       if (Index.getValueType() != MVT::v2i64)
30221         return;
30222       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30223              "Unexpected type action!");
30224       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
30225       SDValue Mask = Gather->getMask();
30226       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
30227       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
30228                                      Gather->getPassThru(),
30229                                      DAG.getUNDEF(VT));
30230       if (!Subtarget.hasVLX()) {
30231         // We need to widen the mask, but the instruction will only use 2
30232         // of its elements. So we can use undef.
30233         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
30234                            DAG.getUNDEF(MVT::v2i1));
30235         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
30236       }
30237       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
30238                         Gather->getBasePtr(), Index, Gather->getScale() };
30239       SDValue Res = DAG.getMemIntrinsicNode(
30240           X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
30241           Gather->getMemoryVT(), Gather->getMemOperand());
30242       Results.push_back(Res);
30243       Results.push_back(Res.getValue(1));
30244       return;
30245     }
30246     return;
30247   }
30248   case ISD::LOAD: {
30249     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
30250     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
30251     // cast since type legalization will try to use an i64 load.
30252     MVT VT = N->getSimpleValueType(0);
30253     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
30254     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30255            "Unexpected type action!");
30256     if (!ISD::isNON_EXTLoad(N))
30257       return;
30258     auto *Ld = cast<LoadSDNode>(N);
30259     if (Subtarget.hasSSE2()) {
30260       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
30261       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
30262                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
30263                                 Ld->getMemOperand()->getFlags());
30264       SDValue Chain = Res.getValue(1);
30265       MVT VecVT = MVT::getVectorVT(LdVT, 2);
30266       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
30267       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
30268       Res = DAG.getBitcast(WideVT, Res);
30269       Results.push_back(Res);
30270       Results.push_back(Chain);
30271       return;
30272     }
30273     assert(Subtarget.hasSSE1() && "Expected SSE");
30274     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
30275     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
30276     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
30277                                           MVT::i64, Ld->getMemOperand());
30278     Results.push_back(Res);
30279     Results.push_back(Res.getValue(1));
30280     return;
30281   }
30282   case ISD::ADDRSPACECAST: {
30283     SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
30284     Results.push_back(V);
30285     return;
30286   }
30287   }
30288 }
30289 
getTargetNodeName(unsigned Opcode) const30290 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
30291   switch ((X86ISD::NodeType)Opcode) {
30292   case X86ISD::FIRST_NUMBER:       break;
30293 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
30294   NODE_NAME_CASE(BSF)
30295   NODE_NAME_CASE(BSR)
30296   NODE_NAME_CASE(FSHL)
30297   NODE_NAME_CASE(FSHR)
30298   NODE_NAME_CASE(FAND)
30299   NODE_NAME_CASE(FANDN)
30300   NODE_NAME_CASE(FOR)
30301   NODE_NAME_CASE(FXOR)
30302   NODE_NAME_CASE(FILD)
30303   NODE_NAME_CASE(FIST)
30304   NODE_NAME_CASE(FP_TO_INT_IN_MEM)
30305   NODE_NAME_CASE(FLD)
30306   NODE_NAME_CASE(FST)
30307   NODE_NAME_CASE(CALL)
30308   NODE_NAME_CASE(BT)
30309   NODE_NAME_CASE(CMP)
30310   NODE_NAME_CASE(FCMP)
30311   NODE_NAME_CASE(STRICT_FCMP)
30312   NODE_NAME_CASE(STRICT_FCMPS)
30313   NODE_NAME_CASE(COMI)
30314   NODE_NAME_CASE(UCOMI)
30315   NODE_NAME_CASE(CMPM)
30316   NODE_NAME_CASE(STRICT_CMPM)
30317   NODE_NAME_CASE(CMPM_SAE)
30318   NODE_NAME_CASE(SETCC)
30319   NODE_NAME_CASE(SETCC_CARRY)
30320   NODE_NAME_CASE(FSETCC)
30321   NODE_NAME_CASE(FSETCCM)
30322   NODE_NAME_CASE(FSETCCM_SAE)
30323   NODE_NAME_CASE(CMOV)
30324   NODE_NAME_CASE(BRCOND)
30325   NODE_NAME_CASE(RET_FLAG)
30326   NODE_NAME_CASE(IRET)
30327   NODE_NAME_CASE(REP_STOS)
30328   NODE_NAME_CASE(REP_MOVS)
30329   NODE_NAME_CASE(GlobalBaseReg)
30330   NODE_NAME_CASE(Wrapper)
30331   NODE_NAME_CASE(WrapperRIP)
30332   NODE_NAME_CASE(MOVQ2DQ)
30333   NODE_NAME_CASE(MOVDQ2Q)
30334   NODE_NAME_CASE(MMX_MOVD2W)
30335   NODE_NAME_CASE(MMX_MOVW2D)
30336   NODE_NAME_CASE(PEXTRB)
30337   NODE_NAME_CASE(PEXTRW)
30338   NODE_NAME_CASE(INSERTPS)
30339   NODE_NAME_CASE(PINSRB)
30340   NODE_NAME_CASE(PINSRW)
30341   NODE_NAME_CASE(PSHUFB)
30342   NODE_NAME_CASE(ANDNP)
30343   NODE_NAME_CASE(BLENDI)
30344   NODE_NAME_CASE(BLENDV)
30345   NODE_NAME_CASE(HADD)
30346   NODE_NAME_CASE(HSUB)
30347   NODE_NAME_CASE(FHADD)
30348   NODE_NAME_CASE(FHSUB)
30349   NODE_NAME_CASE(CONFLICT)
30350   NODE_NAME_CASE(FMAX)
30351   NODE_NAME_CASE(FMAXS)
30352   NODE_NAME_CASE(FMAX_SAE)
30353   NODE_NAME_CASE(FMAXS_SAE)
30354   NODE_NAME_CASE(FMIN)
30355   NODE_NAME_CASE(FMINS)
30356   NODE_NAME_CASE(FMIN_SAE)
30357   NODE_NAME_CASE(FMINS_SAE)
30358   NODE_NAME_CASE(FMAXC)
30359   NODE_NAME_CASE(FMINC)
30360   NODE_NAME_CASE(FRSQRT)
30361   NODE_NAME_CASE(FRCP)
30362   NODE_NAME_CASE(EXTRQI)
30363   NODE_NAME_CASE(INSERTQI)
30364   NODE_NAME_CASE(TLSADDR)
30365   NODE_NAME_CASE(TLSBASEADDR)
30366   NODE_NAME_CASE(TLSCALL)
30367   NODE_NAME_CASE(EH_SJLJ_SETJMP)
30368   NODE_NAME_CASE(EH_SJLJ_LONGJMP)
30369   NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
30370   NODE_NAME_CASE(EH_RETURN)
30371   NODE_NAME_CASE(TC_RETURN)
30372   NODE_NAME_CASE(FNSTCW16m)
30373   NODE_NAME_CASE(LCMPXCHG_DAG)
30374   NODE_NAME_CASE(LCMPXCHG8_DAG)
30375   NODE_NAME_CASE(LCMPXCHG16_DAG)
30376   NODE_NAME_CASE(LCMPXCHG8_SAVE_EBX_DAG)
30377   NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
30378   NODE_NAME_CASE(LADD)
30379   NODE_NAME_CASE(LSUB)
30380   NODE_NAME_CASE(LOR)
30381   NODE_NAME_CASE(LXOR)
30382   NODE_NAME_CASE(LAND)
30383   NODE_NAME_CASE(VZEXT_MOVL)
30384   NODE_NAME_CASE(VZEXT_LOAD)
30385   NODE_NAME_CASE(VEXTRACT_STORE)
30386   NODE_NAME_CASE(VTRUNC)
30387   NODE_NAME_CASE(VTRUNCS)
30388   NODE_NAME_CASE(VTRUNCUS)
30389   NODE_NAME_CASE(VMTRUNC)
30390   NODE_NAME_CASE(VMTRUNCS)
30391   NODE_NAME_CASE(VMTRUNCUS)
30392   NODE_NAME_CASE(VTRUNCSTORES)
30393   NODE_NAME_CASE(VTRUNCSTOREUS)
30394   NODE_NAME_CASE(VMTRUNCSTORES)
30395   NODE_NAME_CASE(VMTRUNCSTOREUS)
30396   NODE_NAME_CASE(VFPEXT)
30397   NODE_NAME_CASE(STRICT_VFPEXT)
30398   NODE_NAME_CASE(VFPEXT_SAE)
30399   NODE_NAME_CASE(VFPEXTS)
30400   NODE_NAME_CASE(VFPEXTS_SAE)
30401   NODE_NAME_CASE(VFPROUND)
30402   NODE_NAME_CASE(STRICT_VFPROUND)
30403   NODE_NAME_CASE(VMFPROUND)
30404   NODE_NAME_CASE(VFPROUND_RND)
30405   NODE_NAME_CASE(VFPROUNDS)
30406   NODE_NAME_CASE(VFPROUNDS_RND)
30407   NODE_NAME_CASE(VSHLDQ)
30408   NODE_NAME_CASE(VSRLDQ)
30409   NODE_NAME_CASE(VSHL)
30410   NODE_NAME_CASE(VSRL)
30411   NODE_NAME_CASE(VSRA)
30412   NODE_NAME_CASE(VSHLI)
30413   NODE_NAME_CASE(VSRLI)
30414   NODE_NAME_CASE(VSRAI)
30415   NODE_NAME_CASE(VSHLV)
30416   NODE_NAME_CASE(VSRLV)
30417   NODE_NAME_CASE(VSRAV)
30418   NODE_NAME_CASE(VROTLI)
30419   NODE_NAME_CASE(VROTRI)
30420   NODE_NAME_CASE(VPPERM)
30421   NODE_NAME_CASE(CMPP)
30422   NODE_NAME_CASE(STRICT_CMPP)
30423   NODE_NAME_CASE(PCMPEQ)
30424   NODE_NAME_CASE(PCMPGT)
30425   NODE_NAME_CASE(PHMINPOS)
30426   NODE_NAME_CASE(ADD)
30427   NODE_NAME_CASE(SUB)
30428   NODE_NAME_CASE(ADC)
30429   NODE_NAME_CASE(SBB)
30430   NODE_NAME_CASE(SMUL)
30431   NODE_NAME_CASE(UMUL)
30432   NODE_NAME_CASE(OR)
30433   NODE_NAME_CASE(XOR)
30434   NODE_NAME_CASE(AND)
30435   NODE_NAME_CASE(BEXTR)
30436   NODE_NAME_CASE(BZHI)
30437   NODE_NAME_CASE(PDEP)
30438   NODE_NAME_CASE(PEXT)
30439   NODE_NAME_CASE(MUL_IMM)
30440   NODE_NAME_CASE(MOVMSK)
30441   NODE_NAME_CASE(PTEST)
30442   NODE_NAME_CASE(TESTP)
30443   NODE_NAME_CASE(KORTEST)
30444   NODE_NAME_CASE(KTEST)
30445   NODE_NAME_CASE(KADD)
30446   NODE_NAME_CASE(KSHIFTL)
30447   NODE_NAME_CASE(KSHIFTR)
30448   NODE_NAME_CASE(PACKSS)
30449   NODE_NAME_CASE(PACKUS)
30450   NODE_NAME_CASE(PALIGNR)
30451   NODE_NAME_CASE(VALIGN)
30452   NODE_NAME_CASE(VSHLD)
30453   NODE_NAME_CASE(VSHRD)
30454   NODE_NAME_CASE(VSHLDV)
30455   NODE_NAME_CASE(VSHRDV)
30456   NODE_NAME_CASE(PSHUFD)
30457   NODE_NAME_CASE(PSHUFHW)
30458   NODE_NAME_CASE(PSHUFLW)
30459   NODE_NAME_CASE(SHUFP)
30460   NODE_NAME_CASE(SHUF128)
30461   NODE_NAME_CASE(MOVLHPS)
30462   NODE_NAME_CASE(MOVHLPS)
30463   NODE_NAME_CASE(MOVDDUP)
30464   NODE_NAME_CASE(MOVSHDUP)
30465   NODE_NAME_CASE(MOVSLDUP)
30466   NODE_NAME_CASE(MOVSD)
30467   NODE_NAME_CASE(MOVSS)
30468   NODE_NAME_CASE(UNPCKL)
30469   NODE_NAME_CASE(UNPCKH)
30470   NODE_NAME_CASE(VBROADCAST)
30471   NODE_NAME_CASE(VBROADCAST_LOAD)
30472   NODE_NAME_CASE(VBROADCASTM)
30473   NODE_NAME_CASE(SUBV_BROADCAST)
30474   NODE_NAME_CASE(VPERMILPV)
30475   NODE_NAME_CASE(VPERMILPI)
30476   NODE_NAME_CASE(VPERM2X128)
30477   NODE_NAME_CASE(VPERMV)
30478   NODE_NAME_CASE(VPERMV3)
30479   NODE_NAME_CASE(VPERMI)
30480   NODE_NAME_CASE(VPTERNLOG)
30481   NODE_NAME_CASE(VFIXUPIMM)
30482   NODE_NAME_CASE(VFIXUPIMM_SAE)
30483   NODE_NAME_CASE(VFIXUPIMMS)
30484   NODE_NAME_CASE(VFIXUPIMMS_SAE)
30485   NODE_NAME_CASE(VRANGE)
30486   NODE_NAME_CASE(VRANGE_SAE)
30487   NODE_NAME_CASE(VRANGES)
30488   NODE_NAME_CASE(VRANGES_SAE)
30489   NODE_NAME_CASE(PMULUDQ)
30490   NODE_NAME_CASE(PMULDQ)
30491   NODE_NAME_CASE(PSADBW)
30492   NODE_NAME_CASE(DBPSADBW)
30493   NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
30494   NODE_NAME_CASE(VAARG_64)
30495   NODE_NAME_CASE(WIN_ALLOCA)
30496   NODE_NAME_CASE(MEMBARRIER)
30497   NODE_NAME_CASE(MFENCE)
30498   NODE_NAME_CASE(SEG_ALLOCA)
30499   NODE_NAME_CASE(PROBED_ALLOCA)
30500   NODE_NAME_CASE(RDRAND)
30501   NODE_NAME_CASE(RDSEED)
30502   NODE_NAME_CASE(RDPKRU)
30503   NODE_NAME_CASE(WRPKRU)
30504   NODE_NAME_CASE(VPMADDUBSW)
30505   NODE_NAME_CASE(VPMADDWD)
30506   NODE_NAME_CASE(VPSHA)
30507   NODE_NAME_CASE(VPSHL)
30508   NODE_NAME_CASE(VPCOM)
30509   NODE_NAME_CASE(VPCOMU)
30510   NODE_NAME_CASE(VPERMIL2)
30511   NODE_NAME_CASE(FMSUB)
30512   NODE_NAME_CASE(STRICT_FMSUB)
30513   NODE_NAME_CASE(FNMADD)
30514   NODE_NAME_CASE(STRICT_FNMADD)
30515   NODE_NAME_CASE(FNMSUB)
30516   NODE_NAME_CASE(STRICT_FNMSUB)
30517   NODE_NAME_CASE(FMADDSUB)
30518   NODE_NAME_CASE(FMSUBADD)
30519   NODE_NAME_CASE(FMADD_RND)
30520   NODE_NAME_CASE(FNMADD_RND)
30521   NODE_NAME_CASE(FMSUB_RND)
30522   NODE_NAME_CASE(FNMSUB_RND)
30523   NODE_NAME_CASE(FMADDSUB_RND)
30524   NODE_NAME_CASE(FMSUBADD_RND)
30525   NODE_NAME_CASE(VPMADD52H)
30526   NODE_NAME_CASE(VPMADD52L)
30527   NODE_NAME_CASE(VRNDSCALE)
30528   NODE_NAME_CASE(STRICT_VRNDSCALE)
30529   NODE_NAME_CASE(VRNDSCALE_SAE)
30530   NODE_NAME_CASE(VRNDSCALES)
30531   NODE_NAME_CASE(VRNDSCALES_SAE)
30532   NODE_NAME_CASE(VREDUCE)
30533   NODE_NAME_CASE(VREDUCE_SAE)
30534   NODE_NAME_CASE(VREDUCES)
30535   NODE_NAME_CASE(VREDUCES_SAE)
30536   NODE_NAME_CASE(VGETMANT)
30537   NODE_NAME_CASE(VGETMANT_SAE)
30538   NODE_NAME_CASE(VGETMANTS)
30539   NODE_NAME_CASE(VGETMANTS_SAE)
30540   NODE_NAME_CASE(PCMPESTR)
30541   NODE_NAME_CASE(PCMPISTR)
30542   NODE_NAME_CASE(XTEST)
30543   NODE_NAME_CASE(COMPRESS)
30544   NODE_NAME_CASE(EXPAND)
30545   NODE_NAME_CASE(SELECTS)
30546   NODE_NAME_CASE(ADDSUB)
30547   NODE_NAME_CASE(RCP14)
30548   NODE_NAME_CASE(RCP14S)
30549   NODE_NAME_CASE(RCP28)
30550   NODE_NAME_CASE(RCP28_SAE)
30551   NODE_NAME_CASE(RCP28S)
30552   NODE_NAME_CASE(RCP28S_SAE)
30553   NODE_NAME_CASE(EXP2)
30554   NODE_NAME_CASE(EXP2_SAE)
30555   NODE_NAME_CASE(RSQRT14)
30556   NODE_NAME_CASE(RSQRT14S)
30557   NODE_NAME_CASE(RSQRT28)
30558   NODE_NAME_CASE(RSQRT28_SAE)
30559   NODE_NAME_CASE(RSQRT28S)
30560   NODE_NAME_CASE(RSQRT28S_SAE)
30561   NODE_NAME_CASE(FADD_RND)
30562   NODE_NAME_CASE(FADDS)
30563   NODE_NAME_CASE(FADDS_RND)
30564   NODE_NAME_CASE(FSUB_RND)
30565   NODE_NAME_CASE(FSUBS)
30566   NODE_NAME_CASE(FSUBS_RND)
30567   NODE_NAME_CASE(FMUL_RND)
30568   NODE_NAME_CASE(FMULS)
30569   NODE_NAME_CASE(FMULS_RND)
30570   NODE_NAME_CASE(FDIV_RND)
30571   NODE_NAME_CASE(FDIVS)
30572   NODE_NAME_CASE(FDIVS_RND)
30573   NODE_NAME_CASE(FSQRT_RND)
30574   NODE_NAME_CASE(FSQRTS)
30575   NODE_NAME_CASE(FSQRTS_RND)
30576   NODE_NAME_CASE(FGETEXP)
30577   NODE_NAME_CASE(FGETEXP_SAE)
30578   NODE_NAME_CASE(FGETEXPS)
30579   NODE_NAME_CASE(FGETEXPS_SAE)
30580   NODE_NAME_CASE(SCALEF)
30581   NODE_NAME_CASE(SCALEF_RND)
30582   NODE_NAME_CASE(SCALEFS)
30583   NODE_NAME_CASE(SCALEFS_RND)
30584   NODE_NAME_CASE(AVG)
30585   NODE_NAME_CASE(MULHRS)
30586   NODE_NAME_CASE(SINT_TO_FP_RND)
30587   NODE_NAME_CASE(UINT_TO_FP_RND)
30588   NODE_NAME_CASE(CVTTP2SI)
30589   NODE_NAME_CASE(CVTTP2UI)
30590   NODE_NAME_CASE(STRICT_CVTTP2SI)
30591   NODE_NAME_CASE(STRICT_CVTTP2UI)
30592   NODE_NAME_CASE(MCVTTP2SI)
30593   NODE_NAME_CASE(MCVTTP2UI)
30594   NODE_NAME_CASE(CVTTP2SI_SAE)
30595   NODE_NAME_CASE(CVTTP2UI_SAE)
30596   NODE_NAME_CASE(CVTTS2SI)
30597   NODE_NAME_CASE(CVTTS2UI)
30598   NODE_NAME_CASE(CVTTS2SI_SAE)
30599   NODE_NAME_CASE(CVTTS2UI_SAE)
30600   NODE_NAME_CASE(CVTSI2P)
30601   NODE_NAME_CASE(CVTUI2P)
30602   NODE_NAME_CASE(STRICT_CVTSI2P)
30603   NODE_NAME_CASE(STRICT_CVTUI2P)
30604   NODE_NAME_CASE(MCVTSI2P)
30605   NODE_NAME_CASE(MCVTUI2P)
30606   NODE_NAME_CASE(VFPCLASS)
30607   NODE_NAME_CASE(VFPCLASSS)
30608   NODE_NAME_CASE(MULTISHIFT)
30609   NODE_NAME_CASE(SCALAR_SINT_TO_FP)
30610   NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
30611   NODE_NAME_CASE(SCALAR_UINT_TO_FP)
30612   NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
30613   NODE_NAME_CASE(CVTPS2PH)
30614   NODE_NAME_CASE(STRICT_CVTPS2PH)
30615   NODE_NAME_CASE(MCVTPS2PH)
30616   NODE_NAME_CASE(CVTPH2PS)
30617   NODE_NAME_CASE(STRICT_CVTPH2PS)
30618   NODE_NAME_CASE(CVTPH2PS_SAE)
30619   NODE_NAME_CASE(CVTP2SI)
30620   NODE_NAME_CASE(CVTP2UI)
30621   NODE_NAME_CASE(MCVTP2SI)
30622   NODE_NAME_CASE(MCVTP2UI)
30623   NODE_NAME_CASE(CVTP2SI_RND)
30624   NODE_NAME_CASE(CVTP2UI_RND)
30625   NODE_NAME_CASE(CVTS2SI)
30626   NODE_NAME_CASE(CVTS2UI)
30627   NODE_NAME_CASE(CVTS2SI_RND)
30628   NODE_NAME_CASE(CVTS2UI_RND)
30629   NODE_NAME_CASE(CVTNE2PS2BF16)
30630   NODE_NAME_CASE(CVTNEPS2BF16)
30631   NODE_NAME_CASE(MCVTNEPS2BF16)
30632   NODE_NAME_CASE(DPBF16PS)
30633   NODE_NAME_CASE(LWPINS)
30634   NODE_NAME_CASE(MGATHER)
30635   NODE_NAME_CASE(MSCATTER)
30636   NODE_NAME_CASE(VPDPBUSD)
30637   NODE_NAME_CASE(VPDPBUSDS)
30638   NODE_NAME_CASE(VPDPWSSD)
30639   NODE_NAME_CASE(VPDPWSSDS)
30640   NODE_NAME_CASE(VPSHUFBITQMB)
30641   NODE_NAME_CASE(GF2P8MULB)
30642   NODE_NAME_CASE(GF2P8AFFINEQB)
30643   NODE_NAME_CASE(GF2P8AFFINEINVQB)
30644   NODE_NAME_CASE(NT_CALL)
30645   NODE_NAME_CASE(NT_BRIND)
30646   NODE_NAME_CASE(UMWAIT)
30647   NODE_NAME_CASE(TPAUSE)
30648   NODE_NAME_CASE(ENQCMD)
30649   NODE_NAME_CASE(ENQCMDS)
30650   NODE_NAME_CASE(VP2INTERSECT)
30651   }
30652   return nullptr;
30653 #undef NODE_NAME_CASE
30654 }
30655 
30656 /// Return true if the addressing mode represented by AM is legal for this
30657 /// target, for a load/store of the specified type.
isLegalAddressingMode(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS,Instruction * I) const30658 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
30659                                               const AddrMode &AM, Type *Ty,
30660                                               unsigned AS,
30661                                               Instruction *I) const {
30662   // X86 supports extremely general addressing modes.
30663   CodeModel::Model M = getTargetMachine().getCodeModel();
30664 
30665   // X86 allows a sign-extended 32-bit immediate field as a displacement.
30666   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
30667     return false;
30668 
30669   if (AM.BaseGV) {
30670     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
30671 
30672     // If a reference to this global requires an extra load, we can't fold it.
30673     if (isGlobalStubReference(GVFlags))
30674       return false;
30675 
30676     // If BaseGV requires a register for the PIC base, we cannot also have a
30677     // BaseReg specified.
30678     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
30679       return false;
30680 
30681     // If lower 4G is not available, then we must use rip-relative addressing.
30682     if ((M != CodeModel::Small || isPositionIndependent()) &&
30683         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
30684       return false;
30685   }
30686 
30687   switch (AM.Scale) {
30688   case 0:
30689   case 1:
30690   case 2:
30691   case 4:
30692   case 8:
30693     // These scales always work.
30694     break;
30695   case 3:
30696   case 5:
30697   case 9:
30698     // These scales are formed with basereg+scalereg.  Only accept if there is
30699     // no basereg yet.
30700     if (AM.HasBaseReg)
30701       return false;
30702     break;
30703   default:  // Other stuff never works.
30704     return false;
30705   }
30706 
30707   return true;
30708 }
30709 
isVectorShiftByScalarCheap(Type * Ty) const30710 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
30711   unsigned Bits = Ty->getScalarSizeInBits();
30712 
30713   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
30714   // particularly cheaper than those without.
30715   if (Bits == 8)
30716     return false;
30717 
30718   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
30719   // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
30720   if (Subtarget.hasXOP() &&
30721       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
30722     return false;
30723 
30724   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
30725   // shifts just as cheap as scalar ones.
30726   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
30727     return false;
30728 
30729   // AVX512BW has shifts such as vpsllvw.
30730   if (Subtarget.hasBWI() && Bits == 16)
30731       return false;
30732 
30733   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
30734   // fully general vector.
30735   return true;
30736 }
30737 
isBinOp(unsigned Opcode) const30738 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
30739   switch (Opcode) {
30740   // These are non-commutative binops.
30741   // TODO: Add more X86ISD opcodes once we have test coverage.
30742   case X86ISD::ANDNP:
30743   case X86ISD::PCMPGT:
30744   case X86ISD::FMAX:
30745   case X86ISD::FMIN:
30746   case X86ISD::FANDN:
30747     return true;
30748   }
30749 
30750   return TargetLoweringBase::isBinOp(Opcode);
30751 }
30752 
isCommutativeBinOp(unsigned Opcode) const30753 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
30754   switch (Opcode) {
30755   // TODO: Add more X86ISD opcodes once we have test coverage.
30756   case X86ISD::PCMPEQ:
30757   case X86ISD::PMULDQ:
30758   case X86ISD::PMULUDQ:
30759   case X86ISD::FMAXC:
30760   case X86ISD::FMINC:
30761   case X86ISD::FAND:
30762   case X86ISD::FOR:
30763   case X86ISD::FXOR:
30764     return true;
30765   }
30766 
30767   return TargetLoweringBase::isCommutativeBinOp(Opcode);
30768 }
30769 
isTruncateFree(Type * Ty1,Type * Ty2) const30770 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
30771   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
30772     return false;
30773   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
30774   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
30775   return NumBits1 > NumBits2;
30776 }
30777 
allowTruncateForTailCall(Type * Ty1,Type * Ty2) const30778 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
30779   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
30780     return false;
30781 
30782   if (!isTypeLegal(EVT::getEVT(Ty1)))
30783     return false;
30784 
30785   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
30786 
30787   // Assuming the caller doesn't have a zeroext or signext return parameter,
30788   // truncation all the way down to i1 is valid.
30789   return true;
30790 }
30791 
isLegalICmpImmediate(int64_t Imm) const30792 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
30793   return isInt<32>(Imm);
30794 }
30795 
isLegalAddImmediate(int64_t Imm) const30796 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
30797   // Can also use sub to handle negated immediates.
30798   return isInt<32>(Imm);
30799 }
30800 
isLegalStoreImmediate(int64_t Imm) const30801 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
30802   return isInt<32>(Imm);
30803 }
30804 
isTruncateFree(EVT VT1,EVT VT2) const30805 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
30806   if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
30807     return false;
30808   unsigned NumBits1 = VT1.getSizeInBits();
30809   unsigned NumBits2 = VT2.getSizeInBits();
30810   return NumBits1 > NumBits2;
30811 }
30812 
isZExtFree(Type * Ty1,Type * Ty2) const30813 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
30814   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
30815   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
30816 }
30817 
isZExtFree(EVT VT1,EVT VT2) const30818 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
30819   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
30820   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
30821 }
30822 
isZExtFree(SDValue Val,EVT VT2) const30823 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
30824   EVT VT1 = Val.getValueType();
30825   if (isZExtFree(VT1, VT2))
30826     return true;
30827 
30828   if (Val.getOpcode() != ISD::LOAD)
30829     return false;
30830 
30831   if (!VT1.isSimple() || !VT1.isInteger() ||
30832       !VT2.isSimple() || !VT2.isInteger())
30833     return false;
30834 
30835   switch (VT1.getSimpleVT().SimpleTy) {
30836   default: break;
30837   case MVT::i8:
30838   case MVT::i16:
30839   case MVT::i32:
30840     // X86 has 8, 16, and 32-bit zero-extending loads.
30841     return true;
30842   }
30843 
30844   return false;
30845 }
30846 
shouldSinkOperands(Instruction * I,SmallVectorImpl<Use * > & Ops) const30847 bool X86TargetLowering::shouldSinkOperands(Instruction *I,
30848                                            SmallVectorImpl<Use *> &Ops) const {
30849   // A uniform shift amount in a vector shift or funnel shift may be much
30850   // cheaper than a generic variable vector shift, so make that pattern visible
30851   // to SDAG by sinking the shuffle instruction next to the shift.
30852   int ShiftAmountOpNum = -1;
30853   if (I->isShift())
30854     ShiftAmountOpNum = 1;
30855   else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
30856     if (II->getIntrinsicID() == Intrinsic::fshl ||
30857         II->getIntrinsicID() == Intrinsic::fshr)
30858       ShiftAmountOpNum = 2;
30859   }
30860 
30861   if (ShiftAmountOpNum == -1)
30862     return false;
30863 
30864   auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
30865   if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
30866       isVectorShiftByScalarCheap(I->getType())) {
30867     Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
30868     return true;
30869   }
30870 
30871   return false;
30872 }
30873 
shouldConvertPhiType(Type * From,Type * To) const30874 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
30875   if (!Subtarget.is64Bit())
30876     return false;
30877   return TargetLowering::shouldConvertPhiType(From, To);
30878 }
30879 
isVectorLoadExtDesirable(SDValue ExtVal) const30880 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
30881   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
30882     return false;
30883 
30884   EVT SrcVT = ExtVal.getOperand(0).getValueType();
30885 
30886   // There is no extending load for vXi1.
30887   if (SrcVT.getScalarType() == MVT::i1)
30888     return false;
30889 
30890   return true;
30891 }
30892 
isFMAFasterThanFMulAndFAdd(const MachineFunction & MF,EVT VT) const30893 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
30894                                                    EVT VT) const {
30895   if (!Subtarget.hasAnyFMA())
30896     return false;
30897 
30898   VT = VT.getScalarType();
30899 
30900   if (!VT.isSimple())
30901     return false;
30902 
30903   switch (VT.getSimpleVT().SimpleTy) {
30904   case MVT::f32:
30905   case MVT::f64:
30906     return true;
30907   default:
30908     break;
30909   }
30910 
30911   return false;
30912 }
30913 
isNarrowingProfitable(EVT VT1,EVT VT2) const30914 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
30915   // i16 instructions are longer (0x66 prefix) and potentially slower.
30916   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
30917 }
30918 
30919 /// Targets can use this to indicate that they only support *some*
30920 /// VECTOR_SHUFFLE operations, those with specific masks.
30921 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
30922 /// are assumed to be legal.
isShuffleMaskLegal(ArrayRef<int> Mask,EVT VT) const30923 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
30924   if (!VT.isSimple())
30925     return false;
30926 
30927   // Not for i1 vectors
30928   if (VT.getSimpleVT().getScalarType() == MVT::i1)
30929     return false;
30930 
30931   // Very little shuffling can be done for 64-bit vectors right now.
30932   if (VT.getSimpleVT().getSizeInBits() == 64)
30933     return false;
30934 
30935   // We only care that the types being shuffled are legal. The lowering can
30936   // handle any possible shuffle mask that results.
30937   return isTypeLegal(VT.getSimpleVT());
30938 }
30939 
isVectorClearMaskLegal(ArrayRef<int> Mask,EVT VT) const30940 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
30941                                                EVT VT) const {
30942   // Don't convert an 'and' into a shuffle that we don't directly support.
30943   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
30944   if (!Subtarget.hasAVX2())
30945     if (VT == MVT::v32i8 || VT == MVT::v16i16)
30946       return false;
30947 
30948   // Just delegate to the generic legality, clear masks aren't special.
30949   return isShuffleMaskLegal(Mask, VT);
30950 }
30951 
areJTsAllowed(const Function * Fn) const30952 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
30953   // If the subtarget is using thunks, we need to not generate jump tables.
30954   if (Subtarget.useIndirectThunkBranches())
30955     return false;
30956 
30957   // Otherwise, fallback on the generic logic.
30958   return TargetLowering::areJTsAllowed(Fn);
30959 }
30960 
30961 //===----------------------------------------------------------------------===//
30962 //                           X86 Scheduler Hooks
30963 //===----------------------------------------------------------------------===//
30964 
30965 /// Utility function to emit xbegin specifying the start of an RTM region.
emitXBegin(MachineInstr & MI,MachineBasicBlock * MBB,const TargetInstrInfo * TII)30966 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
30967                                      const TargetInstrInfo *TII) {
30968   DebugLoc DL = MI.getDebugLoc();
30969 
30970   const BasicBlock *BB = MBB->getBasicBlock();
30971   MachineFunction::iterator I = ++MBB->getIterator();
30972 
30973   // For the v = xbegin(), we generate
30974   //
30975   // thisMBB:
30976   //  xbegin sinkMBB
30977   //
30978   // mainMBB:
30979   //  s0 = -1
30980   //
30981   // fallBB:
30982   //  eax = # XABORT_DEF
30983   //  s1 = eax
30984   //
30985   // sinkMBB:
30986   //  v = phi(s0/mainBB, s1/fallBB)
30987 
30988   MachineBasicBlock *thisMBB = MBB;
30989   MachineFunction *MF = MBB->getParent();
30990   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
30991   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
30992   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
30993   MF->insert(I, mainMBB);
30994   MF->insert(I, fallMBB);
30995   MF->insert(I, sinkMBB);
30996 
30997   // Transfer the remainder of BB and its successor edges to sinkMBB.
30998   sinkMBB->splice(sinkMBB->begin(), MBB,
30999                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
31000   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
31001 
31002   MachineRegisterInfo &MRI = MF->getRegInfo();
31003   Register DstReg = MI.getOperand(0).getReg();
31004   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
31005   Register mainDstReg = MRI.createVirtualRegister(RC);
31006   Register fallDstReg = MRI.createVirtualRegister(RC);
31007 
31008   // thisMBB:
31009   //  xbegin fallMBB
31010   //  # fallthrough to mainMBB
31011   //  # abortion to fallMBB
31012   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
31013   thisMBB->addSuccessor(mainMBB);
31014   thisMBB->addSuccessor(fallMBB);
31015 
31016   // mainMBB:
31017   //  mainDstReg := -1
31018   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
31019   BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
31020   mainMBB->addSuccessor(sinkMBB);
31021 
31022   // fallMBB:
31023   //  ; pseudo instruction to model hardware's definition from XABORT
31024   //  EAX := XABORT_DEF
31025   //  fallDstReg := EAX
31026   BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
31027   BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
31028       .addReg(X86::EAX);
31029   fallMBB->addSuccessor(sinkMBB);
31030 
31031   // sinkMBB:
31032   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
31033   BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
31034       .addReg(mainDstReg).addMBB(mainMBB)
31035       .addReg(fallDstReg).addMBB(fallMBB);
31036 
31037   MI.eraseFromParent();
31038   return sinkMBB;
31039 }
31040 
31041 
31042 
31043 MachineBasicBlock *
EmitVAARG64WithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const31044 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr &MI,
31045                                                  MachineBasicBlock *MBB) const {
31046   // Emit va_arg instruction on X86-64.
31047 
31048   // Operands to this pseudo-instruction:
31049   // 0  ) Output        : destination address (reg)
31050   // 1-5) Input         : va_list address (addr, i64mem)
31051   // 6  ) ArgSize       : Size (in bytes) of vararg type
31052   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
31053   // 8  ) Align         : Alignment of type
31054   // 9  ) EFLAGS (implicit-def)
31055 
31056   assert(MI.getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
31057   static_assert(X86::AddrNumOperands == 5,
31058                 "VAARG_64 assumes 5 address operands");
31059 
31060   Register DestReg = MI.getOperand(0).getReg();
31061   MachineOperand &Base = MI.getOperand(1);
31062   MachineOperand &Scale = MI.getOperand(2);
31063   MachineOperand &Index = MI.getOperand(3);
31064   MachineOperand &Disp = MI.getOperand(4);
31065   MachineOperand &Segment = MI.getOperand(5);
31066   unsigned ArgSize = MI.getOperand(6).getImm();
31067   unsigned ArgMode = MI.getOperand(7).getImm();
31068   Align Alignment = Align(MI.getOperand(8).getImm());
31069 
31070   MachineFunction *MF = MBB->getParent();
31071 
31072   // Memory Reference
31073   assert(MI.hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
31074 
31075   MachineMemOperand *OldMMO = MI.memoperands().front();
31076 
31077   // Clone the MMO into two separate MMOs for loading and storing
31078   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
31079       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
31080   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
31081       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
31082 
31083   // Machine Information
31084   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31085   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
31086   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
31087   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
31088   DebugLoc DL = MI.getDebugLoc();
31089 
31090   // struct va_list {
31091   //   i32   gp_offset
31092   //   i32   fp_offset
31093   //   i64   overflow_area (address)
31094   //   i64   reg_save_area (address)
31095   // }
31096   // sizeof(va_list) = 24
31097   // alignment(va_list) = 8
31098 
31099   unsigned TotalNumIntRegs = 6;
31100   unsigned TotalNumXMMRegs = 8;
31101   bool UseGPOffset = (ArgMode == 1);
31102   bool UseFPOffset = (ArgMode == 2);
31103   unsigned MaxOffset = TotalNumIntRegs * 8 +
31104                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
31105 
31106   /* Align ArgSize to a multiple of 8 */
31107   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
31108   bool NeedsAlign = (Alignment > 8);
31109 
31110   MachineBasicBlock *thisMBB = MBB;
31111   MachineBasicBlock *overflowMBB;
31112   MachineBasicBlock *offsetMBB;
31113   MachineBasicBlock *endMBB;
31114 
31115   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
31116   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
31117   unsigned OffsetReg = 0;
31118 
31119   if (!UseGPOffset && !UseFPOffset) {
31120     // If we only pull from the overflow region, we don't create a branch.
31121     // We don't need to alter control flow.
31122     OffsetDestReg = 0; // unused
31123     OverflowDestReg = DestReg;
31124 
31125     offsetMBB = nullptr;
31126     overflowMBB = thisMBB;
31127     endMBB = thisMBB;
31128   } else {
31129     // First emit code to check if gp_offset (or fp_offset) is below the bound.
31130     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
31131     // If not, pull from overflow_area. (branch to overflowMBB)
31132     //
31133     //       thisMBB
31134     //         |     .
31135     //         |        .
31136     //     offsetMBB   overflowMBB
31137     //         |        .
31138     //         |     .
31139     //        endMBB
31140 
31141     // Registers for the PHI in endMBB
31142     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
31143     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
31144 
31145     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
31146     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31147     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31148     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31149 
31150     MachineFunction::iterator MBBIter = ++MBB->getIterator();
31151 
31152     // Insert the new basic blocks
31153     MF->insert(MBBIter, offsetMBB);
31154     MF->insert(MBBIter, overflowMBB);
31155     MF->insert(MBBIter, endMBB);
31156 
31157     // Transfer the remainder of MBB and its successor edges to endMBB.
31158     endMBB->splice(endMBB->begin(), thisMBB,
31159                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
31160     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
31161 
31162     // Make offsetMBB and overflowMBB successors of thisMBB
31163     thisMBB->addSuccessor(offsetMBB);
31164     thisMBB->addSuccessor(overflowMBB);
31165 
31166     // endMBB is a successor of both offsetMBB and overflowMBB
31167     offsetMBB->addSuccessor(endMBB);
31168     overflowMBB->addSuccessor(endMBB);
31169 
31170     // Load the offset value into a register
31171     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
31172     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
31173         .add(Base)
31174         .add(Scale)
31175         .add(Index)
31176         .addDisp(Disp, UseFPOffset ? 4 : 0)
31177         .add(Segment)
31178         .setMemRefs(LoadOnlyMMO);
31179 
31180     // Check if there is enough room left to pull this argument.
31181     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
31182       .addReg(OffsetReg)
31183       .addImm(MaxOffset + 8 - ArgSizeA8);
31184 
31185     // Branch to "overflowMBB" if offset >= max
31186     // Fall through to "offsetMBB" otherwise
31187     BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
31188       .addMBB(overflowMBB).addImm(X86::COND_AE);
31189   }
31190 
31191   // In offsetMBB, emit code to use the reg_save_area.
31192   if (offsetMBB) {
31193     assert(OffsetReg != 0);
31194 
31195     // Read the reg_save_area address.
31196     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
31197     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
31198         .add(Base)
31199         .add(Scale)
31200         .add(Index)
31201         .addDisp(Disp, 16)
31202         .add(Segment)
31203         .setMemRefs(LoadOnlyMMO);
31204 
31205     // Zero-extend the offset
31206     Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
31207     BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
31208         .addImm(0)
31209         .addReg(OffsetReg)
31210         .addImm(X86::sub_32bit);
31211 
31212     // Add the offset to the reg_save_area to get the final address.
31213     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
31214       .addReg(OffsetReg64)
31215       .addReg(RegSaveReg);
31216 
31217     // Compute the offset for the next argument
31218     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
31219     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
31220       .addReg(OffsetReg)
31221       .addImm(UseFPOffset ? 16 : 8);
31222 
31223     // Store it back into the va_list.
31224     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
31225         .add(Base)
31226         .add(Scale)
31227         .add(Index)
31228         .addDisp(Disp, UseFPOffset ? 4 : 0)
31229         .add(Segment)
31230         .addReg(NextOffsetReg)
31231         .setMemRefs(StoreOnlyMMO);
31232 
31233     // Jump to endMBB
31234     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
31235       .addMBB(endMBB);
31236   }
31237 
31238   //
31239   // Emit code to use overflow area
31240   //
31241 
31242   // Load the overflow_area address into a register.
31243   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
31244   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
31245       .add(Base)
31246       .add(Scale)
31247       .add(Index)
31248       .addDisp(Disp, 8)
31249       .add(Segment)
31250       .setMemRefs(LoadOnlyMMO);
31251 
31252   // If we need to align it, do so. Otherwise, just copy the address
31253   // to OverflowDestReg.
31254   if (NeedsAlign) {
31255     // Align the overflow address
31256     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
31257 
31258     // aligned_addr = (addr + (align-1)) & ~(align-1)
31259     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
31260         .addReg(OverflowAddrReg)
31261         .addImm(Alignment.value() - 1);
31262 
31263     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
31264         .addReg(TmpReg)
31265         .addImm(~(uint64_t)(Alignment.value() - 1));
31266   } else {
31267     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
31268       .addReg(OverflowAddrReg);
31269   }
31270 
31271   // Compute the next overflow address after this argument.
31272   // (the overflow address should be kept 8-byte aligned)
31273   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
31274   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
31275     .addReg(OverflowDestReg)
31276     .addImm(ArgSizeA8);
31277 
31278   // Store the new overflow address.
31279   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
31280       .add(Base)
31281       .add(Scale)
31282       .add(Index)
31283       .addDisp(Disp, 8)
31284       .add(Segment)
31285       .addReg(NextAddrReg)
31286       .setMemRefs(StoreOnlyMMO);
31287 
31288   // If we branched, emit the PHI to the front of endMBB.
31289   if (offsetMBB) {
31290     BuildMI(*endMBB, endMBB->begin(), DL,
31291             TII->get(X86::PHI), DestReg)
31292       .addReg(OffsetDestReg).addMBB(offsetMBB)
31293       .addReg(OverflowDestReg).addMBB(overflowMBB);
31294   }
31295 
31296   // Erase the pseudo instruction
31297   MI.eraseFromParent();
31298 
31299   return endMBB;
31300 }
31301 
EmitVAStartSaveXMMRegsWithCustomInserter(MachineInstr & MI,MachineBasicBlock * MBB) const31302 MachineBasicBlock *X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
31303     MachineInstr &MI, MachineBasicBlock *MBB) const {
31304   // Emit code to save XMM registers to the stack. The ABI says that the
31305   // number of registers to save is given in %al, so it's theoretically
31306   // possible to do an indirect jump trick to avoid saving all of them,
31307   // however this code takes a simpler approach and just executes all
31308   // of the stores if %al is non-zero. It's less code, and it's probably
31309   // easier on the hardware branch predictor, and stores aren't all that
31310   // expensive anyway.
31311 
31312   // Create the new basic blocks. One block contains all the XMM stores,
31313   // and one block is the final destination regardless of whether any
31314   // stores were performed.
31315   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
31316   MachineFunction *F = MBB->getParent();
31317   MachineFunction::iterator MBBIter = ++MBB->getIterator();
31318   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
31319   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
31320   F->insert(MBBIter, XMMSaveMBB);
31321   F->insert(MBBIter, EndMBB);
31322 
31323   // Transfer the remainder of MBB and its successor edges to EndMBB.
31324   EndMBB->splice(EndMBB->begin(), MBB,
31325                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
31326   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
31327 
31328   // The original block will now fall through to the XMM save block.
31329   MBB->addSuccessor(XMMSaveMBB);
31330   // The XMMSaveMBB will fall through to the end block.
31331   XMMSaveMBB->addSuccessor(EndMBB);
31332 
31333   // Now add the instructions.
31334   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31335   DebugLoc DL = MI.getDebugLoc();
31336 
31337   Register CountReg = MI.getOperand(0).getReg();
31338   int64_t RegSaveFrameIndex = MI.getOperand(1).getImm();
31339   int64_t VarArgsFPOffset = MI.getOperand(2).getImm();
31340 
31341   if (!Subtarget.isCallingConvWin64(F->getFunction().getCallingConv())) {
31342     // If %al is 0, branch around the XMM save block.
31343     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
31344     BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(EndMBB).addImm(X86::COND_E);
31345     MBB->addSuccessor(EndMBB);
31346   }
31347 
31348   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
31349   // that was just emitted, but clearly shouldn't be "saved".
31350   assert((MI.getNumOperands() <= 3 ||
31351           !MI.getOperand(MI.getNumOperands() - 1).isReg() ||
31352           MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) &&
31353          "Expected last argument to be EFLAGS");
31354   unsigned MOVOpc = Subtarget.hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
31355   // In the XMM save block, save all the XMM argument registers.
31356   for (int i = 3, e = MI.getNumOperands() - 1; i != e; ++i) {
31357     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
31358     MachineMemOperand *MMO = F->getMachineMemOperand(
31359         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
31360         MachineMemOperand::MOStore,
31361         /*Size=*/16, Align(16));
31362     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
31363         .addFrameIndex(RegSaveFrameIndex)
31364         .addImm(/*Scale=*/1)
31365         .addReg(/*IndexReg=*/0)
31366         .addImm(/*Disp=*/Offset)
31367         .addReg(/*Segment=*/0)
31368         .addReg(MI.getOperand(i).getReg())
31369         .addMemOperand(MMO);
31370   }
31371 
31372   MI.eraseFromParent(); // The pseudo instruction is gone now.
31373 
31374   return EndMBB;
31375 }
31376 
31377 // The EFLAGS operand of SelectItr might be missing a kill marker
31378 // because there were multiple uses of EFLAGS, and ISel didn't know
31379 // which to mark. Figure out whether SelectItr should have had a
31380 // kill marker, and set it if it should. Returns the correct kill
31381 // marker value.
checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,MachineBasicBlock * BB,const TargetRegisterInfo * TRI)31382 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
31383                                      MachineBasicBlock* BB,
31384                                      const TargetRegisterInfo* TRI) {
31385   // Scan forward through BB for a use/def of EFLAGS.
31386   MachineBasicBlock::iterator miI(std::next(SelectItr));
31387   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
31388     const MachineInstr& mi = *miI;
31389     if (mi.readsRegister(X86::EFLAGS))
31390       return false;
31391     if (mi.definesRegister(X86::EFLAGS))
31392       break; // Should have kill-flag - update below.
31393   }
31394 
31395   // If we hit the end of the block, check whether EFLAGS is live into a
31396   // successor.
31397   if (miI == BB->end()) {
31398     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
31399                                           sEnd = BB->succ_end();
31400          sItr != sEnd; ++sItr) {
31401       MachineBasicBlock* succ = *sItr;
31402       if (succ->isLiveIn(X86::EFLAGS))
31403         return false;
31404     }
31405   }
31406 
31407   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
31408   // out. SelectMI should have a kill flag on EFLAGS.
31409   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
31410   return true;
31411 }
31412 
31413 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
31414 // together with other CMOV pseudo-opcodes into a single basic-block with
31415 // conditional jump around it.
isCMOVPseudo(MachineInstr & MI)31416 static bool isCMOVPseudo(MachineInstr &MI) {
31417   switch (MI.getOpcode()) {
31418   case X86::CMOV_FR32:
31419   case X86::CMOV_FR32X:
31420   case X86::CMOV_FR64:
31421   case X86::CMOV_FR64X:
31422   case X86::CMOV_GR8:
31423   case X86::CMOV_GR16:
31424   case X86::CMOV_GR32:
31425   case X86::CMOV_RFP32:
31426   case X86::CMOV_RFP64:
31427   case X86::CMOV_RFP80:
31428   case X86::CMOV_VR64:
31429   case X86::CMOV_VR128:
31430   case X86::CMOV_VR128X:
31431   case X86::CMOV_VR256:
31432   case X86::CMOV_VR256X:
31433   case X86::CMOV_VR512:
31434   case X86::CMOV_VK1:
31435   case X86::CMOV_VK2:
31436   case X86::CMOV_VK4:
31437   case X86::CMOV_VK8:
31438   case X86::CMOV_VK16:
31439   case X86::CMOV_VK32:
31440   case X86::CMOV_VK64:
31441     return true;
31442 
31443   default:
31444     return false;
31445   }
31446 }
31447 
31448 // Helper function, which inserts PHI functions into SinkMBB:
31449 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
31450 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
31451 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
31452 // the last PHI function inserted.
createPHIsForCMOVsInSinkBB(MachineBasicBlock::iterator MIItBegin,MachineBasicBlock::iterator MIItEnd,MachineBasicBlock * TrueMBB,MachineBasicBlock * FalseMBB,MachineBasicBlock * SinkMBB)31453 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
31454     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
31455     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
31456     MachineBasicBlock *SinkMBB) {
31457   MachineFunction *MF = TrueMBB->getParent();
31458   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
31459   DebugLoc DL = MIItBegin->getDebugLoc();
31460 
31461   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
31462   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
31463 
31464   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
31465 
31466   // As we are creating the PHIs, we have to be careful if there is more than
31467   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
31468   // PHIs have to reference the individual true/false inputs from earlier PHIs.
31469   // That also means that PHI construction must work forward from earlier to
31470   // later, and that the code must maintain a mapping from earlier PHI's
31471   // destination registers, and the registers that went into the PHI.
31472   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
31473   MachineInstrBuilder MIB;
31474 
31475   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
31476     Register DestReg = MIIt->getOperand(0).getReg();
31477     Register Op1Reg = MIIt->getOperand(1).getReg();
31478     Register Op2Reg = MIIt->getOperand(2).getReg();
31479 
31480     // If this CMOV we are generating is the opposite condition from
31481     // the jump we generated, then we have to swap the operands for the
31482     // PHI that is going to be generated.
31483     if (MIIt->getOperand(3).getImm() == OppCC)
31484       std::swap(Op1Reg, Op2Reg);
31485 
31486     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
31487       Op1Reg = RegRewriteTable[Op1Reg].first;
31488 
31489     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
31490       Op2Reg = RegRewriteTable[Op2Reg].second;
31491 
31492     MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
31493               .addReg(Op1Reg)
31494               .addMBB(FalseMBB)
31495               .addReg(Op2Reg)
31496               .addMBB(TrueMBB);
31497 
31498     // Add this PHI to the rewrite table.
31499     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
31500   }
31501 
31502   return MIB;
31503 }
31504 
31505 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
31506 MachineBasicBlock *
EmitLoweredCascadedSelect(MachineInstr & FirstCMOV,MachineInstr & SecondCascadedCMOV,MachineBasicBlock * ThisMBB) const31507 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
31508                                              MachineInstr &SecondCascadedCMOV,
31509                                              MachineBasicBlock *ThisMBB) const {
31510   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31511   DebugLoc DL = FirstCMOV.getDebugLoc();
31512 
31513   // We lower cascaded CMOVs such as
31514   //
31515   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
31516   //
31517   // to two successive branches.
31518   //
31519   // Without this, we would add a PHI between the two jumps, which ends up
31520   // creating a few copies all around. For instance, for
31521   //
31522   //    (sitofp (zext (fcmp une)))
31523   //
31524   // we would generate:
31525   //
31526   //         ucomiss %xmm1, %xmm0
31527   //         movss  <1.0f>, %xmm0
31528   //         movaps  %xmm0, %xmm1
31529   //         jne     .LBB5_2
31530   //         xorps   %xmm1, %xmm1
31531   // .LBB5_2:
31532   //         jp      .LBB5_4
31533   //         movaps  %xmm1, %xmm0
31534   // .LBB5_4:
31535   //         retq
31536   //
31537   // because this custom-inserter would have generated:
31538   //
31539   //   A
31540   //   | \
31541   //   |  B
31542   //   | /
31543   //   C
31544   //   | \
31545   //   |  D
31546   //   | /
31547   //   E
31548   //
31549   // A: X = ...; Y = ...
31550   // B: empty
31551   // C: Z = PHI [X, A], [Y, B]
31552   // D: empty
31553   // E: PHI [X, C], [Z, D]
31554   //
31555   // If we lower both CMOVs in a single step, we can instead generate:
31556   //
31557   //   A
31558   //   | \
31559   //   |  C
31560   //   | /|
31561   //   |/ |
31562   //   |  |
31563   //   |  D
31564   //   | /
31565   //   E
31566   //
31567   // A: X = ...; Y = ...
31568   // D: empty
31569   // E: PHI [X, A], [X, C], [Y, D]
31570   //
31571   // Which, in our sitofp/fcmp example, gives us something like:
31572   //
31573   //         ucomiss %xmm1, %xmm0
31574   //         movss  <1.0f>, %xmm0
31575   //         jne     .LBB5_4
31576   //         jp      .LBB5_4
31577   //         xorps   %xmm0, %xmm0
31578   // .LBB5_4:
31579   //         retq
31580   //
31581 
31582   // We lower cascaded CMOV into two successive branches to the same block.
31583   // EFLAGS is used by both, so mark it as live in the second.
31584   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
31585   MachineFunction *F = ThisMBB->getParent();
31586   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
31587   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
31588   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
31589 
31590   MachineFunction::iterator It = ++ThisMBB->getIterator();
31591   F->insert(It, FirstInsertedMBB);
31592   F->insert(It, SecondInsertedMBB);
31593   F->insert(It, SinkMBB);
31594 
31595   // For a cascaded CMOV, we lower it to two successive branches to
31596   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
31597   // the FirstInsertedMBB.
31598   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
31599 
31600   // If the EFLAGS register isn't dead in the terminator, then claim that it's
31601   // live into the sink and copy blocks.
31602   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
31603   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
31604       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
31605     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
31606     SinkMBB->addLiveIn(X86::EFLAGS);
31607   }
31608 
31609   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
31610   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
31611                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
31612                   ThisMBB->end());
31613   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
31614 
31615   // Fallthrough block for ThisMBB.
31616   ThisMBB->addSuccessor(FirstInsertedMBB);
31617   // The true block target of the first branch is always SinkMBB.
31618   ThisMBB->addSuccessor(SinkMBB);
31619   // Fallthrough block for FirstInsertedMBB.
31620   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
31621   // The true block for the branch of FirstInsertedMBB.
31622   FirstInsertedMBB->addSuccessor(SinkMBB);
31623   // This is fallthrough.
31624   SecondInsertedMBB->addSuccessor(SinkMBB);
31625 
31626   // Create the conditional branch instructions.
31627   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
31628   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
31629 
31630   X86::CondCode SecondCC =
31631       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
31632   BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
31633 
31634   //  SinkMBB:
31635   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
31636   Register DestReg = FirstCMOV.getOperand(0).getReg();
31637   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
31638   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
31639   MachineInstrBuilder MIB =
31640       BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
31641           .addReg(Op1Reg)
31642           .addMBB(SecondInsertedMBB)
31643           .addReg(Op2Reg)
31644           .addMBB(ThisMBB);
31645 
31646   // The second SecondInsertedMBB provides the same incoming value as the
31647   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
31648   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
31649   // Copy the PHI result to the register defined by the second CMOV.
31650   BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
31651           TII->get(TargetOpcode::COPY),
31652           SecondCascadedCMOV.getOperand(0).getReg())
31653       .addReg(FirstCMOV.getOperand(0).getReg());
31654 
31655   // Now remove the CMOVs.
31656   FirstCMOV.eraseFromParent();
31657   SecondCascadedCMOV.eraseFromParent();
31658 
31659   return SinkMBB;
31660 }
31661 
31662 MachineBasicBlock *
EmitLoweredSelect(MachineInstr & MI,MachineBasicBlock * ThisMBB) const31663 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
31664                                      MachineBasicBlock *ThisMBB) const {
31665   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31666   DebugLoc DL = MI.getDebugLoc();
31667 
31668   // To "insert" a SELECT_CC instruction, we actually have to insert the
31669   // diamond control-flow pattern.  The incoming instruction knows the
31670   // destination vreg to set, the condition code register to branch on, the
31671   // true/false values to select between and a branch opcode to use.
31672 
31673   //  ThisMBB:
31674   //  ...
31675   //   TrueVal = ...
31676   //   cmpTY ccX, r1, r2
31677   //   bCC copy1MBB
31678   //   fallthrough --> FalseMBB
31679 
31680   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
31681   // as described above, by inserting a BB, and then making a PHI at the join
31682   // point to select the true and false operands of the CMOV in the PHI.
31683   //
31684   // The code also handles two different cases of multiple CMOV opcodes
31685   // in a row.
31686   //
31687   // Case 1:
31688   // In this case, there are multiple CMOVs in a row, all which are based on
31689   // the same condition setting (or the exact opposite condition setting).
31690   // In this case we can lower all the CMOVs using a single inserted BB, and
31691   // then make a number of PHIs at the join point to model the CMOVs. The only
31692   // trickiness here, is that in a case like:
31693   //
31694   // t2 = CMOV cond1 t1, f1
31695   // t3 = CMOV cond1 t2, f2
31696   //
31697   // when rewriting this into PHIs, we have to perform some renaming on the
31698   // temps since you cannot have a PHI operand refer to a PHI result earlier
31699   // in the same block.  The "simple" but wrong lowering would be:
31700   //
31701   // t2 = PHI t1(BB1), f1(BB2)
31702   // t3 = PHI t2(BB1), f2(BB2)
31703   //
31704   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
31705   // renaming is to note that on the path through BB1, t2 is really just a
31706   // copy of t1, and do that renaming, properly generating:
31707   //
31708   // t2 = PHI t1(BB1), f1(BB2)
31709   // t3 = PHI t1(BB1), f2(BB2)
31710   //
31711   // Case 2:
31712   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
31713   // function - EmitLoweredCascadedSelect.
31714 
31715   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
31716   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
31717   MachineInstr *LastCMOV = &MI;
31718   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
31719 
31720   // Check for case 1, where there are multiple CMOVs with the same condition
31721   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
31722   // number of jumps the most.
31723 
31724   if (isCMOVPseudo(MI)) {
31725     // See if we have a string of CMOVS with the same condition. Skip over
31726     // intervening debug insts.
31727     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
31728            (NextMIIt->getOperand(3).getImm() == CC ||
31729             NextMIIt->getOperand(3).getImm() == OppCC)) {
31730       LastCMOV = &*NextMIIt;
31731       NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
31732     }
31733   }
31734 
31735   // This checks for case 2, but only do this if we didn't already find
31736   // case 1, as indicated by LastCMOV == MI.
31737   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
31738       NextMIIt->getOpcode() == MI.getOpcode() &&
31739       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
31740       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
31741       NextMIIt->getOperand(1).isKill()) {
31742     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
31743   }
31744 
31745   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
31746   MachineFunction *F = ThisMBB->getParent();
31747   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
31748   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
31749 
31750   MachineFunction::iterator It = ++ThisMBB->getIterator();
31751   F->insert(It, FalseMBB);
31752   F->insert(It, SinkMBB);
31753 
31754   // If the EFLAGS register isn't dead in the terminator, then claim that it's
31755   // live into the sink and copy blocks.
31756   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
31757   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
31758       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
31759     FalseMBB->addLiveIn(X86::EFLAGS);
31760     SinkMBB->addLiveIn(X86::EFLAGS);
31761   }
31762 
31763   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
31764   auto DbgEnd = MachineBasicBlock::iterator(LastCMOV);
31765   auto DbgIt = MachineBasicBlock::iterator(MI);
31766   while (DbgIt != DbgEnd) {
31767     auto Next = std::next(DbgIt);
31768     if (DbgIt->isDebugInstr())
31769       SinkMBB->push_back(DbgIt->removeFromParent());
31770     DbgIt = Next;
31771   }
31772 
31773   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
31774   SinkMBB->splice(SinkMBB->end(), ThisMBB,
31775                   std::next(MachineBasicBlock::iterator(LastCMOV)),
31776                   ThisMBB->end());
31777   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
31778 
31779   // Fallthrough block for ThisMBB.
31780   ThisMBB->addSuccessor(FalseMBB);
31781   // The true block target of the first (or only) branch is always a SinkMBB.
31782   ThisMBB->addSuccessor(SinkMBB);
31783   // Fallthrough block for FalseMBB.
31784   FalseMBB->addSuccessor(SinkMBB);
31785 
31786   // Create the conditional branch instruction.
31787   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
31788 
31789   //  SinkMBB:
31790   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
31791   //  ...
31792   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
31793   MachineBasicBlock::iterator MIItEnd =
31794       std::next(MachineBasicBlock::iterator(LastCMOV));
31795   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
31796 
31797   // Now remove the CMOV(s).
31798   ThisMBB->erase(MIItBegin, MIItEnd);
31799 
31800   return SinkMBB;
31801 }
31802 
getSUBriOpcode(bool IsLP64,int64_t Imm)31803 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
31804   if (IsLP64) {
31805     if (isInt<8>(Imm))
31806       return X86::SUB64ri8;
31807     return X86::SUB64ri32;
31808   } else {
31809     if (isInt<8>(Imm))
31810       return X86::SUB32ri8;
31811     return X86::SUB32ri;
31812   }
31813 }
31814 
31815 MachineBasicBlock *
EmitLoweredProbedAlloca(MachineInstr & MI,MachineBasicBlock * MBB) const31816 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
31817                                            MachineBasicBlock *MBB) const {
31818   MachineFunction *MF = MBB->getParent();
31819   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31820   const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
31821   DebugLoc DL = MI.getDebugLoc();
31822   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
31823 
31824   const unsigned ProbeSize = getStackProbeSize(*MF);
31825 
31826   MachineRegisterInfo &MRI = MF->getRegInfo();
31827   MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31828   MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31829   MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31830 
31831   MachineFunction::iterator MBBIter = ++MBB->getIterator();
31832   MF->insert(MBBIter, testMBB);
31833   MF->insert(MBBIter, blockMBB);
31834   MF->insert(MBBIter, tailMBB);
31835 
31836   Register sizeVReg = MI.getOperand(1).getReg();
31837 
31838   Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
31839 
31840   Register TmpStackPtr = MRI.createVirtualRegister(
31841       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
31842   Register FinalStackPtr = MRI.createVirtualRegister(
31843       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
31844 
31845   BuildMI(*MBB, {MI}, DL, TII->get(TargetOpcode::COPY), TmpStackPtr)
31846       .addReg(physSPReg);
31847   {
31848     const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
31849     BuildMI(*MBB, {MI}, DL, TII->get(Opc), FinalStackPtr)
31850         .addReg(TmpStackPtr)
31851         .addReg(sizeVReg);
31852   }
31853 
31854   // test rsp size
31855 
31856   BuildMI(testMBB, DL,
31857           TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
31858       .addReg(FinalStackPtr)
31859       .addReg(physSPReg);
31860 
31861   BuildMI(testMBB, DL, TII->get(X86::JCC_1))
31862       .addMBB(tailMBB)
31863       .addImm(X86::COND_L);
31864   testMBB->addSuccessor(blockMBB);
31865   testMBB->addSuccessor(tailMBB);
31866 
31867   // Touch the block then extend it. This is done on the opposite side of
31868   // static probe where we allocate then touch, to avoid the need of probing the
31869   // tail of the static alloca. Possible scenarios are:
31870   //
31871   //       + ---- <- ------------ <- ------------- <- ------------ +
31872   //       |                                                       |
31873   // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
31874   //                                                               |                                                               |
31875   //                                                               + <- ----------- <- ------------ <- ----------- <- ------------ +
31876   //
31877   // The property we want to enforce is to never have more than [page alloc] between two probes.
31878 
31879   const unsigned MovMIOpc =
31880       TFI.Uses64BitFramePtr ? X86::MOV64mi32 : X86::MOV32mi;
31881   addRegOffset(BuildMI(blockMBB, DL, TII->get(MovMIOpc)), physSPReg, false, 0)
31882       .addImm(0);
31883 
31884   BuildMI(blockMBB, DL,
31885           TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr, ProbeSize)), physSPReg)
31886       .addReg(physSPReg)
31887       .addImm(ProbeSize);
31888 
31889 
31890   BuildMI(blockMBB, DL, TII->get(X86::JMP_1)).addMBB(testMBB);
31891   blockMBB->addSuccessor(testMBB);
31892 
31893   // Replace original instruction by the expected stack ptr
31894   BuildMI(tailMBB, DL, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
31895       .addReg(FinalStackPtr);
31896 
31897   tailMBB->splice(tailMBB->end(), MBB,
31898                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
31899   tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
31900   MBB->addSuccessor(testMBB);
31901 
31902   // Delete the original pseudo instruction.
31903   MI.eraseFromParent();
31904 
31905   // And we're done.
31906   return tailMBB;
31907 }
31908 
31909 MachineBasicBlock *
EmitLoweredSegAlloca(MachineInstr & MI,MachineBasicBlock * BB) const31910 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
31911                                         MachineBasicBlock *BB) const {
31912   MachineFunction *MF = BB->getParent();
31913   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31914   DebugLoc DL = MI.getDebugLoc();
31915   const BasicBlock *LLVM_BB = BB->getBasicBlock();
31916 
31917   assert(MF->shouldSplitStack());
31918 
31919   const bool Is64Bit = Subtarget.is64Bit();
31920   const bool IsLP64 = Subtarget.isTarget64BitLP64();
31921 
31922   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
31923   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
31924 
31925   // BB:
31926   //  ... [Till the alloca]
31927   // If stacklet is not large enough, jump to mallocMBB
31928   //
31929   // bumpMBB:
31930   //  Allocate by subtracting from RSP
31931   //  Jump to continueMBB
31932   //
31933   // mallocMBB:
31934   //  Allocate by call to runtime
31935   //
31936   // continueMBB:
31937   //  ...
31938   //  [rest of original BB]
31939   //
31940 
31941   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31942   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31943   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31944 
31945   MachineRegisterInfo &MRI = MF->getRegInfo();
31946   const TargetRegisterClass *AddrRegClass =
31947       getRegClassFor(getPointerTy(MF->getDataLayout()));
31948 
31949   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
31950            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
31951            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
31952            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
31953            sizeVReg = MI.getOperand(1).getReg(),
31954            physSPReg =
31955                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
31956 
31957   MachineFunction::iterator MBBIter = ++BB->getIterator();
31958 
31959   MF->insert(MBBIter, bumpMBB);
31960   MF->insert(MBBIter, mallocMBB);
31961   MF->insert(MBBIter, continueMBB);
31962 
31963   continueMBB->splice(continueMBB->begin(), BB,
31964                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
31965   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
31966 
31967   // Add code to the main basic block to check if the stack limit has been hit,
31968   // and if so, jump to mallocMBB otherwise to bumpMBB.
31969   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
31970   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
31971     .addReg(tmpSPVReg).addReg(sizeVReg);
31972   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
31973     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
31974     .addReg(SPLimitVReg);
31975   BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
31976 
31977   // bumpMBB simply decreases the stack pointer, since we know the current
31978   // stacklet has enough space.
31979   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
31980     .addReg(SPLimitVReg);
31981   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
31982     .addReg(SPLimitVReg);
31983   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
31984 
31985   // Calls into a routine in libgcc to allocate more space from the heap.
31986   const uint32_t *RegMask =
31987       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
31988   if (IsLP64) {
31989     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
31990       .addReg(sizeVReg);
31991     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
31992       .addExternalSymbol("__morestack_allocate_stack_space")
31993       .addRegMask(RegMask)
31994       .addReg(X86::RDI, RegState::Implicit)
31995       .addReg(X86::RAX, RegState::ImplicitDefine);
31996   } else if (Is64Bit) {
31997     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
31998       .addReg(sizeVReg);
31999     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
32000       .addExternalSymbol("__morestack_allocate_stack_space")
32001       .addRegMask(RegMask)
32002       .addReg(X86::EDI, RegState::Implicit)
32003       .addReg(X86::EAX, RegState::ImplicitDefine);
32004   } else {
32005     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
32006       .addImm(12);
32007     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
32008     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
32009       .addExternalSymbol("__morestack_allocate_stack_space")
32010       .addRegMask(RegMask)
32011       .addReg(X86::EAX, RegState::ImplicitDefine);
32012   }
32013 
32014   if (!Is64Bit)
32015     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
32016       .addImm(16);
32017 
32018   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
32019     .addReg(IsLP64 ? X86::RAX : X86::EAX);
32020   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
32021 
32022   // Set up the CFG correctly.
32023   BB->addSuccessor(bumpMBB);
32024   BB->addSuccessor(mallocMBB);
32025   mallocMBB->addSuccessor(continueMBB);
32026   bumpMBB->addSuccessor(continueMBB);
32027 
32028   // Take care of the PHI nodes.
32029   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
32030           MI.getOperand(0).getReg())
32031       .addReg(mallocPtrVReg)
32032       .addMBB(mallocMBB)
32033       .addReg(bumpSPPtrVReg)
32034       .addMBB(bumpMBB);
32035 
32036   // Delete the original pseudo instruction.
32037   MI.eraseFromParent();
32038 
32039   // And we're done.
32040   return continueMBB;
32041 }
32042 
32043 MachineBasicBlock *
EmitLoweredCatchRet(MachineInstr & MI,MachineBasicBlock * BB) const32044 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
32045                                        MachineBasicBlock *BB) const {
32046   MachineFunction *MF = BB->getParent();
32047   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
32048   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
32049   DebugLoc DL = MI.getDebugLoc();
32050 
32051   assert(!isAsynchronousEHPersonality(
32052              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
32053          "SEH does not use catchret!");
32054 
32055   // Only 32-bit EH needs to worry about manually restoring stack pointers.
32056   if (!Subtarget.is32Bit())
32057     return BB;
32058 
32059   // C++ EH creates a new target block to hold the restore code, and wires up
32060   // the new block to the return destination with a normal JMP_4.
32061   MachineBasicBlock *RestoreMBB =
32062       MF->CreateMachineBasicBlock(BB->getBasicBlock());
32063   assert(BB->succ_size() == 1);
32064   MF->insert(std::next(BB->getIterator()), RestoreMBB);
32065   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
32066   BB->addSuccessor(RestoreMBB);
32067   MI.getOperand(0).setMBB(RestoreMBB);
32068 
32069   // Marking this as an EH pad but not a funclet entry block causes PEI to
32070   // restore stack pointers in the block.
32071   RestoreMBB->setIsEHPad(true);
32072 
32073   auto RestoreMBBI = RestoreMBB->begin();
32074   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
32075   return BB;
32076 }
32077 
32078 MachineBasicBlock *
EmitLoweredTLSAddr(MachineInstr & MI,MachineBasicBlock * BB) const32079 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
32080                                       MachineBasicBlock *BB) const {
32081   // So, here we replace TLSADDR with the sequence:
32082   // adjust_stackdown -> TLSADDR -> adjust_stackup.
32083   // We need this because TLSADDR is lowered into calls
32084   // inside MC, therefore without the two markers shrink-wrapping
32085   // may push the prologue/epilogue pass them.
32086   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
32087   DebugLoc DL = MI.getDebugLoc();
32088   MachineFunction &MF = *BB->getParent();
32089 
32090   // Emit CALLSEQ_START right before the instruction.
32091   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
32092   MachineInstrBuilder CallseqStart =
32093     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
32094   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
32095 
32096   // Emit CALLSEQ_END right after the instruction.
32097   // We don't call erase from parent because we want to keep the
32098   // original instruction around.
32099   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
32100   MachineInstrBuilder CallseqEnd =
32101     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
32102   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
32103 
32104   return BB;
32105 }
32106 
32107 MachineBasicBlock *
EmitLoweredTLSCall(MachineInstr & MI,MachineBasicBlock * BB) const32108 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
32109                                       MachineBasicBlock *BB) const {
32110   // This is pretty easy.  We're taking the value that we received from
32111   // our load from the relocation, sticking it in either RDI (x86-64)
32112   // or EAX and doing an indirect call.  The return value will then
32113   // be in the normal return register.
32114   MachineFunction *F = BB->getParent();
32115   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32116   DebugLoc DL = MI.getDebugLoc();
32117 
32118   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
32119   assert(MI.getOperand(3).isGlobal() && "This should be a global");
32120 
32121   // Get a register mask for the lowered call.
32122   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
32123   // proper register mask.
32124   const uint32_t *RegMask =
32125       Subtarget.is64Bit() ?
32126       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
32127       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
32128   if (Subtarget.is64Bit()) {
32129     MachineInstrBuilder MIB =
32130         BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
32131             .addReg(X86::RIP)
32132             .addImm(0)
32133             .addReg(0)
32134             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
32135                               MI.getOperand(3).getTargetFlags())
32136             .addReg(0);
32137     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
32138     addDirectMem(MIB, X86::RDI);
32139     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
32140   } else if (!isPositionIndependent()) {
32141     MachineInstrBuilder MIB =
32142         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
32143             .addReg(0)
32144             .addImm(0)
32145             .addReg(0)
32146             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
32147                               MI.getOperand(3).getTargetFlags())
32148             .addReg(0);
32149     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
32150     addDirectMem(MIB, X86::EAX);
32151     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
32152   } else {
32153     MachineInstrBuilder MIB =
32154         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
32155             .addReg(TII->getGlobalBaseReg(F))
32156             .addImm(0)
32157             .addReg(0)
32158             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
32159                               MI.getOperand(3).getTargetFlags())
32160             .addReg(0);
32161     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
32162     addDirectMem(MIB, X86::EAX);
32163     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
32164   }
32165 
32166   MI.eraseFromParent(); // The pseudo instruction is gone now.
32167   return BB;
32168 }
32169 
getOpcodeForIndirectThunk(unsigned RPOpc)32170 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
32171   switch (RPOpc) {
32172   case X86::INDIRECT_THUNK_CALL32:
32173     return X86::CALLpcrel32;
32174   case X86::INDIRECT_THUNK_CALL64:
32175     return X86::CALL64pcrel32;
32176   case X86::INDIRECT_THUNK_TCRETURN32:
32177     return X86::TCRETURNdi;
32178   case X86::INDIRECT_THUNK_TCRETURN64:
32179     return X86::TCRETURNdi64;
32180   }
32181   llvm_unreachable("not indirect thunk opcode");
32182 }
32183 
getIndirectThunkSymbol(const X86Subtarget & Subtarget,unsigned Reg)32184 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
32185                                           unsigned Reg) {
32186   if (Subtarget.useRetpolineExternalThunk()) {
32187     // When using an external thunk for retpolines, we pick names that match the
32188     // names GCC happens to use as well. This helps simplify the implementation
32189     // of the thunks for kernels where they have no easy ability to create
32190     // aliases and are doing non-trivial configuration of the thunk's body. For
32191     // example, the Linux kernel will do boot-time hot patching of the thunk
32192     // bodies and cannot easily export aliases of these to loaded modules.
32193     //
32194     // Note that at any point in the future, we may need to change the semantics
32195     // of how we implement retpolines and at that time will likely change the
32196     // name of the called thunk. Essentially, there is no hard guarantee that
32197     // LLVM will generate calls to specific thunks, we merely make a best-effort
32198     // attempt to help out kernels and other systems where duplicating the
32199     // thunks is costly.
32200     switch (Reg) {
32201     case X86::EAX:
32202       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32203       return "__x86_indirect_thunk_eax";
32204     case X86::ECX:
32205       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32206       return "__x86_indirect_thunk_ecx";
32207     case X86::EDX:
32208       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32209       return "__x86_indirect_thunk_edx";
32210     case X86::EDI:
32211       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32212       return "__x86_indirect_thunk_edi";
32213     case X86::R11:
32214       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
32215       return "__x86_indirect_thunk_r11";
32216     }
32217     llvm_unreachable("unexpected reg for external indirect thunk");
32218   }
32219 
32220   if (Subtarget.useRetpolineIndirectCalls() ||
32221       Subtarget.useRetpolineIndirectBranches()) {
32222     // When targeting an internal COMDAT thunk use an LLVM-specific name.
32223     switch (Reg) {
32224     case X86::EAX:
32225       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32226       return "__llvm_retpoline_eax";
32227     case X86::ECX:
32228       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32229       return "__llvm_retpoline_ecx";
32230     case X86::EDX:
32231       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32232       return "__llvm_retpoline_edx";
32233     case X86::EDI:
32234       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32235       return "__llvm_retpoline_edi";
32236     case X86::R11:
32237       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
32238       return "__llvm_retpoline_r11";
32239     }
32240     llvm_unreachable("unexpected reg for retpoline");
32241   }
32242 
32243   if (Subtarget.useLVIControlFlowIntegrity()) {
32244     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
32245     return "__llvm_lvi_thunk_r11";
32246   }
32247   llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
32248 }
32249 
32250 MachineBasicBlock *
EmitLoweredIndirectThunk(MachineInstr & MI,MachineBasicBlock * BB) const32251 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
32252                                             MachineBasicBlock *BB) const {
32253   // Copy the virtual register into the R11 physical register and
32254   // call the retpoline thunk.
32255   DebugLoc DL = MI.getDebugLoc();
32256   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32257   Register CalleeVReg = MI.getOperand(0).getReg();
32258   unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
32259 
32260   // Find an available scratch register to hold the callee. On 64-bit, we can
32261   // just use R11, but we scan for uses anyway to ensure we don't generate
32262   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
32263   // already a register use operand to the call to hold the callee. If none
32264   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
32265   // register and ESI is the base pointer to realigned stack frames with VLAs.
32266   SmallVector<unsigned, 3> AvailableRegs;
32267   if (Subtarget.is64Bit())
32268     AvailableRegs.push_back(X86::R11);
32269   else
32270     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
32271 
32272   // Zero out any registers that are already used.
32273   for (const auto &MO : MI.operands()) {
32274     if (MO.isReg() && MO.isUse())
32275       for (unsigned &Reg : AvailableRegs)
32276         if (Reg == MO.getReg())
32277           Reg = 0;
32278   }
32279 
32280   // Choose the first remaining non-zero available register.
32281   unsigned AvailableReg = 0;
32282   for (unsigned MaybeReg : AvailableRegs) {
32283     if (MaybeReg) {
32284       AvailableReg = MaybeReg;
32285       break;
32286     }
32287   }
32288   if (!AvailableReg)
32289     report_fatal_error("calling convention incompatible with retpoline, no "
32290                        "available registers");
32291 
32292   const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
32293 
32294   BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
32295       .addReg(CalleeVReg);
32296   MI.getOperand(0).ChangeToES(Symbol);
32297   MI.setDesc(TII->get(Opc));
32298   MachineInstrBuilder(*BB->getParent(), &MI)
32299       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
32300   return BB;
32301 }
32302 
32303 /// SetJmp implies future control flow change upon calling the corresponding
32304 /// LongJmp.
32305 /// Instead of using the 'return' instruction, the long jump fixes the stack and
32306 /// performs an indirect branch. To do so it uses the registers that were stored
32307 /// in the jump buffer (when calling SetJmp).
32308 /// In case the shadow stack is enabled we need to fix it as well, because some
32309 /// return addresses will be skipped.
32310 /// The function will save the SSP for future fixing in the function
32311 /// emitLongJmpShadowStackFix.
32312 /// \sa emitLongJmpShadowStackFix
32313 /// \param [in] MI The temporary Machine Instruction for the builtin.
32314 /// \param [in] MBB The Machine Basic Block that will be modified.
emitSetJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const32315 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
32316                                                  MachineBasicBlock *MBB) const {
32317   DebugLoc DL = MI.getDebugLoc();
32318   MachineFunction *MF = MBB->getParent();
32319   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32320   MachineRegisterInfo &MRI = MF->getRegInfo();
32321   MachineInstrBuilder MIB;
32322 
32323   // Memory Reference.
32324   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
32325                                            MI.memoperands_end());
32326 
32327   // Initialize a register with zero.
32328   MVT PVT = getPointerTy(MF->getDataLayout());
32329   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
32330   Register ZReg = MRI.createVirtualRegister(PtrRC);
32331   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
32332   BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
32333       .addDef(ZReg)
32334       .addReg(ZReg, RegState::Undef)
32335       .addReg(ZReg, RegState::Undef);
32336 
32337   // Read the current SSP Register value to the zeroed register.
32338   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
32339   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
32340   BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
32341 
32342   // Write the SSP register value to offset 3 in input memory buffer.
32343   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
32344   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
32345   const int64_t SSPOffset = 3 * PVT.getStoreSize();
32346   const unsigned MemOpndSlot = 1;
32347   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
32348     if (i == X86::AddrDisp)
32349       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
32350     else
32351       MIB.add(MI.getOperand(MemOpndSlot + i));
32352   }
32353   MIB.addReg(SSPCopyReg);
32354   MIB.setMemRefs(MMOs);
32355 }
32356 
32357 MachineBasicBlock *
emitEHSjLjSetJmp(MachineInstr & MI,MachineBasicBlock * MBB) const32358 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
32359                                     MachineBasicBlock *MBB) const {
32360   DebugLoc DL = MI.getDebugLoc();
32361   MachineFunction *MF = MBB->getParent();
32362   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32363   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
32364   MachineRegisterInfo &MRI = MF->getRegInfo();
32365 
32366   const BasicBlock *BB = MBB->getBasicBlock();
32367   MachineFunction::iterator I = ++MBB->getIterator();
32368 
32369   // Memory Reference
32370   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
32371                                            MI.memoperands_end());
32372 
32373   unsigned DstReg;
32374   unsigned MemOpndSlot = 0;
32375 
32376   unsigned CurOp = 0;
32377 
32378   DstReg = MI.getOperand(CurOp++).getReg();
32379   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
32380   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
32381   (void)TRI;
32382   Register mainDstReg = MRI.createVirtualRegister(RC);
32383   Register restoreDstReg = MRI.createVirtualRegister(RC);
32384 
32385   MemOpndSlot = CurOp;
32386 
32387   MVT PVT = getPointerTy(MF->getDataLayout());
32388   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
32389          "Invalid Pointer Size!");
32390 
32391   // For v = setjmp(buf), we generate
32392   //
32393   // thisMBB:
32394   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
32395   //  SjLjSetup restoreMBB
32396   //
32397   // mainMBB:
32398   //  v_main = 0
32399   //
32400   // sinkMBB:
32401   //  v = phi(main, restore)
32402   //
32403   // restoreMBB:
32404   //  if base pointer being used, load it from frame
32405   //  v_restore = 1
32406 
32407   MachineBasicBlock *thisMBB = MBB;
32408   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
32409   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
32410   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
32411   MF->insert(I, mainMBB);
32412   MF->insert(I, sinkMBB);
32413   MF->push_back(restoreMBB);
32414   restoreMBB->setHasAddressTaken();
32415 
32416   MachineInstrBuilder MIB;
32417 
32418   // Transfer the remainder of BB and its successor edges to sinkMBB.
32419   sinkMBB->splice(sinkMBB->begin(), MBB,
32420                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
32421   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
32422 
32423   // thisMBB:
32424   unsigned PtrStoreOpc = 0;
32425   unsigned LabelReg = 0;
32426   const int64_t LabelOffset = 1 * PVT.getStoreSize();
32427   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
32428                      !isPositionIndependent();
32429 
32430   // Prepare IP either in reg or imm.
32431   if (!UseImmLabel) {
32432     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
32433     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
32434     LabelReg = MRI.createVirtualRegister(PtrRC);
32435     if (Subtarget.is64Bit()) {
32436       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
32437               .addReg(X86::RIP)
32438               .addImm(0)
32439               .addReg(0)
32440               .addMBB(restoreMBB)
32441               .addReg(0);
32442     } else {
32443       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
32444       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
32445               .addReg(XII->getGlobalBaseReg(MF))
32446               .addImm(0)
32447               .addReg(0)
32448               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
32449               .addReg(0);
32450     }
32451   } else
32452     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
32453   // Store IP
32454   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
32455   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
32456     if (i == X86::AddrDisp)
32457       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
32458     else
32459       MIB.add(MI.getOperand(MemOpndSlot + i));
32460   }
32461   if (!UseImmLabel)
32462     MIB.addReg(LabelReg);
32463   else
32464     MIB.addMBB(restoreMBB);
32465   MIB.setMemRefs(MMOs);
32466 
32467   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
32468     emitSetJmpShadowStackFix(MI, thisMBB);
32469   }
32470 
32471   // Setup
32472   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
32473           .addMBB(restoreMBB);
32474 
32475   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
32476   MIB.addRegMask(RegInfo->getNoPreservedMask());
32477   thisMBB->addSuccessor(mainMBB);
32478   thisMBB->addSuccessor(restoreMBB);
32479 
32480   // mainMBB:
32481   //  EAX = 0
32482   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
32483   mainMBB->addSuccessor(sinkMBB);
32484 
32485   // sinkMBB:
32486   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
32487           TII->get(X86::PHI), DstReg)
32488     .addReg(mainDstReg).addMBB(mainMBB)
32489     .addReg(restoreDstReg).addMBB(restoreMBB);
32490 
32491   // restoreMBB:
32492   if (RegInfo->hasBasePointer(*MF)) {
32493     const bool Uses64BitFramePtr =
32494         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
32495     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
32496     X86FI->setRestoreBasePointer(MF);
32497     Register FramePtr = RegInfo->getFrameRegister(*MF);
32498     Register BasePtr = RegInfo->getBaseRegister();
32499     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
32500     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
32501                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
32502       .setMIFlag(MachineInstr::FrameSetup);
32503   }
32504   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
32505   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
32506   restoreMBB->addSuccessor(sinkMBB);
32507 
32508   MI.eraseFromParent();
32509   return sinkMBB;
32510 }
32511 
32512 /// Fix the shadow stack using the previously saved SSP pointer.
32513 /// \sa emitSetJmpShadowStackFix
32514 /// \param [in] MI The temporary Machine Instruction for the builtin.
32515 /// \param [in] MBB The Machine Basic Block that will be modified.
32516 /// \return The sink MBB that will perform the future indirect branch.
32517 MachineBasicBlock *
emitLongJmpShadowStackFix(MachineInstr & MI,MachineBasicBlock * MBB) const32518 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
32519                                              MachineBasicBlock *MBB) const {
32520   DebugLoc DL = MI.getDebugLoc();
32521   MachineFunction *MF = MBB->getParent();
32522   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32523   MachineRegisterInfo &MRI = MF->getRegInfo();
32524 
32525   // Memory Reference
32526   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
32527                                            MI.memoperands_end());
32528 
32529   MVT PVT = getPointerTy(MF->getDataLayout());
32530   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
32531 
32532   // checkSspMBB:
32533   //         xor vreg1, vreg1
32534   //         rdssp vreg1
32535   //         test vreg1, vreg1
32536   //         je sinkMBB   # Jump if Shadow Stack is not supported
32537   // fallMBB:
32538   //         mov buf+24/12(%rip), vreg2
32539   //         sub vreg1, vreg2
32540   //         jbe sinkMBB  # No need to fix the Shadow Stack
32541   // fixShadowMBB:
32542   //         shr 3/2, vreg2
32543   //         incssp vreg2  # fix the SSP according to the lower 8 bits
32544   //         shr 8, vreg2
32545   //         je sinkMBB
32546   // fixShadowLoopPrepareMBB:
32547   //         shl vreg2
32548   //         mov 128, vreg3
32549   // fixShadowLoopMBB:
32550   //         incssp vreg3
32551   //         dec vreg2
32552   //         jne fixShadowLoopMBB # Iterate until you finish fixing
32553   //                              # the Shadow Stack
32554   // sinkMBB:
32555 
32556   MachineFunction::iterator I = ++MBB->getIterator();
32557   const BasicBlock *BB = MBB->getBasicBlock();
32558 
32559   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
32560   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
32561   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
32562   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
32563   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
32564   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
32565   MF->insert(I, checkSspMBB);
32566   MF->insert(I, fallMBB);
32567   MF->insert(I, fixShadowMBB);
32568   MF->insert(I, fixShadowLoopPrepareMBB);
32569   MF->insert(I, fixShadowLoopMBB);
32570   MF->insert(I, sinkMBB);
32571 
32572   // Transfer the remainder of BB and its successor edges to sinkMBB.
32573   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
32574                   MBB->end());
32575   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
32576 
32577   MBB->addSuccessor(checkSspMBB);
32578 
32579   // Initialize a register with zero.
32580   Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
32581   BuildMI(checkSspMBB, DL, TII->get(X86::MOV32r0), ZReg);
32582 
32583   if (PVT == MVT::i64) {
32584     Register TmpZReg = MRI.createVirtualRegister(PtrRC);
32585     BuildMI(checkSspMBB, DL, TII->get(X86::SUBREG_TO_REG), TmpZReg)
32586       .addImm(0)
32587       .addReg(ZReg)
32588       .addImm(X86::sub_32bit);
32589     ZReg = TmpZReg;
32590   }
32591 
32592   // Read the current SSP Register value to the zeroed register.
32593   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
32594   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
32595   BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
32596 
32597   // Check whether the result of the SSP register is zero and jump directly
32598   // to the sink.
32599   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
32600   BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
32601       .addReg(SSPCopyReg)
32602       .addReg(SSPCopyReg);
32603   BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
32604   checkSspMBB->addSuccessor(sinkMBB);
32605   checkSspMBB->addSuccessor(fallMBB);
32606 
32607   // Reload the previously saved SSP register value.
32608   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
32609   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
32610   const int64_t SPPOffset = 3 * PVT.getStoreSize();
32611   MachineInstrBuilder MIB =
32612       BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
32613   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
32614     const MachineOperand &MO = MI.getOperand(i);
32615     if (i == X86::AddrDisp)
32616       MIB.addDisp(MO, SPPOffset);
32617     else if (MO.isReg()) // Don't add the whole operand, we don't want to
32618                          // preserve kill flags.
32619       MIB.addReg(MO.getReg());
32620     else
32621       MIB.add(MO);
32622   }
32623   MIB.setMemRefs(MMOs);
32624 
32625   // Subtract the current SSP from the previous SSP.
32626   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
32627   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
32628   BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
32629       .addReg(PrevSSPReg)
32630       .addReg(SSPCopyReg);
32631 
32632   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
32633   BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
32634   fallMBB->addSuccessor(sinkMBB);
32635   fallMBB->addSuccessor(fixShadowMBB);
32636 
32637   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
32638   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
32639   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
32640   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
32641   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
32642       .addReg(SspSubReg)
32643       .addImm(Offset);
32644 
32645   // Increase SSP when looking only on the lower 8 bits of the delta.
32646   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
32647   BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
32648 
32649   // Reset the lower 8 bits.
32650   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
32651   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
32652       .addReg(SspFirstShrReg)
32653       .addImm(8);
32654 
32655   // Jump if the result of the shift is zero.
32656   BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
32657   fixShadowMBB->addSuccessor(sinkMBB);
32658   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
32659 
32660   // Do a single shift left.
32661   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
32662   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
32663   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
32664       .addReg(SspSecondShrReg);
32665 
32666   // Save the value 128 to a register (will be used next with incssp).
32667   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
32668   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
32669   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
32670       .addImm(128);
32671   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
32672 
32673   // Since incssp only looks at the lower 8 bits, we might need to do several
32674   // iterations of incssp until we finish fixing the shadow stack.
32675   Register DecReg = MRI.createVirtualRegister(PtrRC);
32676   Register CounterReg = MRI.createVirtualRegister(PtrRC);
32677   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
32678       .addReg(SspAfterShlReg)
32679       .addMBB(fixShadowLoopPrepareMBB)
32680       .addReg(DecReg)
32681       .addMBB(fixShadowLoopMBB);
32682 
32683   // Every iteration we increase the SSP by 128.
32684   BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
32685 
32686   // Every iteration we decrement the counter by 1.
32687   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
32688   BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
32689 
32690   // Jump if the counter is not zero yet.
32691   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
32692   fixShadowLoopMBB->addSuccessor(sinkMBB);
32693   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
32694 
32695   return sinkMBB;
32696 }
32697 
32698 MachineBasicBlock *
emitEHSjLjLongJmp(MachineInstr & MI,MachineBasicBlock * MBB) const32699 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
32700                                      MachineBasicBlock *MBB) const {
32701   DebugLoc DL = MI.getDebugLoc();
32702   MachineFunction *MF = MBB->getParent();
32703   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32704   MachineRegisterInfo &MRI = MF->getRegInfo();
32705 
32706   // Memory Reference
32707   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
32708                                            MI.memoperands_end());
32709 
32710   MVT PVT = getPointerTy(MF->getDataLayout());
32711   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
32712          "Invalid Pointer Size!");
32713 
32714   const TargetRegisterClass *RC =
32715     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
32716   Register Tmp = MRI.createVirtualRegister(RC);
32717   // Since FP is only updated here but NOT referenced, it's treated as GPR.
32718   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
32719   Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
32720   Register SP = RegInfo->getStackRegister();
32721 
32722   MachineInstrBuilder MIB;
32723 
32724   const int64_t LabelOffset = 1 * PVT.getStoreSize();
32725   const int64_t SPOffset = 2 * PVT.getStoreSize();
32726 
32727   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
32728   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
32729 
32730   MachineBasicBlock *thisMBB = MBB;
32731 
32732   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
32733   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
32734     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
32735   }
32736 
32737   // Reload FP
32738   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
32739   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
32740     const MachineOperand &MO = MI.getOperand(i);
32741     if (MO.isReg()) // Don't add the whole operand, we don't want to
32742                     // preserve kill flags.
32743       MIB.addReg(MO.getReg());
32744     else
32745       MIB.add(MO);
32746   }
32747   MIB.setMemRefs(MMOs);
32748 
32749   // Reload IP
32750   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
32751   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
32752     const MachineOperand &MO = MI.getOperand(i);
32753     if (i == X86::AddrDisp)
32754       MIB.addDisp(MO, LabelOffset);
32755     else if (MO.isReg()) // Don't add the whole operand, we don't want to
32756                          // preserve kill flags.
32757       MIB.addReg(MO.getReg());
32758     else
32759       MIB.add(MO);
32760   }
32761   MIB.setMemRefs(MMOs);
32762 
32763   // Reload SP
32764   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
32765   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
32766     if (i == X86::AddrDisp)
32767       MIB.addDisp(MI.getOperand(i), SPOffset);
32768     else
32769       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
32770                                  // the last instruction of the expansion.
32771   }
32772   MIB.setMemRefs(MMOs);
32773 
32774   // Jump
32775   BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
32776 
32777   MI.eraseFromParent();
32778   return thisMBB;
32779 }
32780 
SetupEntryBlockForSjLj(MachineInstr & MI,MachineBasicBlock * MBB,MachineBasicBlock * DispatchBB,int FI) const32781 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
32782                                                MachineBasicBlock *MBB,
32783                                                MachineBasicBlock *DispatchBB,
32784                                                int FI) const {
32785   DebugLoc DL = MI.getDebugLoc();
32786   MachineFunction *MF = MBB->getParent();
32787   MachineRegisterInfo *MRI = &MF->getRegInfo();
32788   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32789 
32790   MVT PVT = getPointerTy(MF->getDataLayout());
32791   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
32792 
32793   unsigned Op = 0;
32794   unsigned VR = 0;
32795 
32796   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
32797                      !isPositionIndependent();
32798 
32799   if (UseImmLabel) {
32800     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
32801   } else {
32802     const TargetRegisterClass *TRC =
32803         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
32804     VR = MRI->createVirtualRegister(TRC);
32805     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
32806 
32807     if (Subtarget.is64Bit())
32808       BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
32809           .addReg(X86::RIP)
32810           .addImm(1)
32811           .addReg(0)
32812           .addMBB(DispatchBB)
32813           .addReg(0);
32814     else
32815       BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
32816           .addReg(0) /* TII->getGlobalBaseReg(MF) */
32817           .addImm(1)
32818           .addReg(0)
32819           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
32820           .addReg(0);
32821   }
32822 
32823   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
32824   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
32825   if (UseImmLabel)
32826     MIB.addMBB(DispatchBB);
32827   else
32828     MIB.addReg(VR);
32829 }
32830 
32831 MachineBasicBlock *
EmitSjLjDispatchBlock(MachineInstr & MI,MachineBasicBlock * BB) const32832 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
32833                                          MachineBasicBlock *BB) const {
32834   DebugLoc DL = MI.getDebugLoc();
32835   MachineFunction *MF = BB->getParent();
32836   MachineRegisterInfo *MRI = &MF->getRegInfo();
32837   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32838   int FI = MF->getFrameInfo().getFunctionContextIndex();
32839 
32840   // Get a mapping of the call site numbers to all of the landing pads they're
32841   // associated with.
32842   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
32843   unsigned MaxCSNum = 0;
32844   for (auto &MBB : *MF) {
32845     if (!MBB.isEHPad())
32846       continue;
32847 
32848     MCSymbol *Sym = nullptr;
32849     for (const auto &MI : MBB) {
32850       if (MI.isDebugInstr())
32851         continue;
32852 
32853       assert(MI.isEHLabel() && "expected EH_LABEL");
32854       Sym = MI.getOperand(0).getMCSymbol();
32855       break;
32856     }
32857 
32858     if (!MF->hasCallSiteLandingPad(Sym))
32859       continue;
32860 
32861     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
32862       CallSiteNumToLPad[CSI].push_back(&MBB);
32863       MaxCSNum = std::max(MaxCSNum, CSI);
32864     }
32865   }
32866 
32867   // Get an ordered list of the machine basic blocks for the jump table.
32868   std::vector<MachineBasicBlock *> LPadList;
32869   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
32870   LPadList.reserve(CallSiteNumToLPad.size());
32871 
32872   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
32873     for (auto &LP : CallSiteNumToLPad[CSI]) {
32874       LPadList.push_back(LP);
32875       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
32876     }
32877   }
32878 
32879   assert(!LPadList.empty() &&
32880          "No landing pad destinations for the dispatch jump table!");
32881 
32882   // Create the MBBs for the dispatch code.
32883 
32884   // Shove the dispatch's address into the return slot in the function context.
32885   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
32886   DispatchBB->setIsEHPad(true);
32887 
32888   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
32889   BuildMI(TrapBB, DL, TII->get(X86::TRAP));
32890   DispatchBB->addSuccessor(TrapBB);
32891 
32892   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
32893   DispatchBB->addSuccessor(DispContBB);
32894 
32895   // Insert MBBs.
32896   MF->push_back(DispatchBB);
32897   MF->push_back(DispContBB);
32898   MF->push_back(TrapBB);
32899 
32900   // Insert code into the entry block that creates and registers the function
32901   // context.
32902   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
32903 
32904   // Create the jump table and associated information
32905   unsigned JTE = getJumpTableEncoding();
32906   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
32907   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
32908 
32909   const X86RegisterInfo &RI = TII->getRegisterInfo();
32910   // Add a register mask with no preserved registers.  This results in all
32911   // registers being marked as clobbered.
32912   if (RI.hasBasePointer(*MF)) {
32913     const bool FPIs64Bit =
32914         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
32915     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
32916     MFI->setRestoreBasePointer(MF);
32917 
32918     Register FP = RI.getFrameRegister(*MF);
32919     Register BP = RI.getBaseRegister();
32920     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
32921     addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
32922                  MFI->getRestoreBasePointerOffset())
32923         .addRegMask(RI.getNoPreservedMask());
32924   } else {
32925     BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
32926         .addRegMask(RI.getNoPreservedMask());
32927   }
32928 
32929   // IReg is used as an index in a memory operand and therefore can't be SP
32930   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
32931   addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
32932                     Subtarget.is64Bit() ? 8 : 4);
32933   BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
32934       .addReg(IReg)
32935       .addImm(LPadList.size());
32936   BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
32937 
32938   if (Subtarget.is64Bit()) {
32939     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
32940     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
32941 
32942     // leaq .LJTI0_0(%rip), BReg
32943     BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
32944         .addReg(X86::RIP)
32945         .addImm(1)
32946         .addReg(0)
32947         .addJumpTableIndex(MJTI)
32948         .addReg(0);
32949     // movzx IReg64, IReg
32950     BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
32951         .addImm(0)
32952         .addReg(IReg)
32953         .addImm(X86::sub_32bit);
32954 
32955     switch (JTE) {
32956     case MachineJumpTableInfo::EK_BlockAddress:
32957       // jmpq *(BReg,IReg64,8)
32958       BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
32959           .addReg(BReg)
32960           .addImm(8)
32961           .addReg(IReg64)
32962           .addImm(0)
32963           .addReg(0);
32964       break;
32965     case MachineJumpTableInfo::EK_LabelDifference32: {
32966       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
32967       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
32968       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
32969 
32970       // movl (BReg,IReg64,4), OReg
32971       BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
32972           .addReg(BReg)
32973           .addImm(4)
32974           .addReg(IReg64)
32975           .addImm(0)
32976           .addReg(0);
32977       // movsx OReg64, OReg
32978       BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
32979       // addq BReg, OReg64, TReg
32980       BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
32981           .addReg(OReg64)
32982           .addReg(BReg);
32983       // jmpq *TReg
32984       BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
32985       break;
32986     }
32987     default:
32988       llvm_unreachable("Unexpected jump table encoding");
32989     }
32990   } else {
32991     // jmpl *.LJTI0_0(,IReg,4)
32992     BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
32993         .addReg(0)
32994         .addImm(4)
32995         .addReg(IReg)
32996         .addJumpTableIndex(MJTI)
32997         .addReg(0);
32998   }
32999 
33000   // Add the jump table entries as successors to the MBB.
33001   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
33002   for (auto &LP : LPadList)
33003     if (SeenMBBs.insert(LP).second)
33004       DispContBB->addSuccessor(LP);
33005 
33006   // N.B. the order the invoke BBs are processed in doesn't matter here.
33007   SmallVector<MachineBasicBlock *, 64> MBBLPads;
33008   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
33009   for (MachineBasicBlock *MBB : InvokeBBs) {
33010     // Remove the landing pad successor from the invoke block and replace it
33011     // with the new dispatch block.
33012     // Keep a copy of Successors since it's modified inside the loop.
33013     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
33014                                                    MBB->succ_rend());
33015     // FIXME: Avoid quadratic complexity.
33016     for (auto MBBS : Successors) {
33017       if (MBBS->isEHPad()) {
33018         MBB->removeSuccessor(MBBS);
33019         MBBLPads.push_back(MBBS);
33020       }
33021     }
33022 
33023     MBB->addSuccessor(DispatchBB);
33024 
33025     // Find the invoke call and mark all of the callee-saved registers as
33026     // 'implicit defined' so that they're spilled.  This prevents code from
33027     // moving instructions to before the EH block, where they will never be
33028     // executed.
33029     for (auto &II : reverse(*MBB)) {
33030       if (!II.isCall())
33031         continue;
33032 
33033       DenseMap<unsigned, bool> DefRegs;
33034       for (auto &MOp : II.operands())
33035         if (MOp.isReg())
33036           DefRegs[MOp.getReg()] = true;
33037 
33038       MachineInstrBuilder MIB(*MF, &II);
33039       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
33040         unsigned Reg = SavedRegs[RegIdx];
33041         if (!DefRegs[Reg])
33042           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
33043       }
33044 
33045       break;
33046     }
33047   }
33048 
33049   // Mark all former landing pads as non-landing pads.  The dispatch is the only
33050   // landing pad now.
33051   for (auto &LP : MBBLPads)
33052     LP->setIsEHPad(false);
33053 
33054   // The instruction is gone now.
33055   MI.eraseFromParent();
33056   return BB;
33057 }
33058 
33059 MachineBasicBlock *
EmitInstrWithCustomInserter(MachineInstr & MI,MachineBasicBlock * BB) const33060 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
33061                                                MachineBasicBlock *BB) const {
33062   MachineFunction *MF = BB->getParent();
33063   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33064   DebugLoc DL = MI.getDebugLoc();
33065 
33066   auto TMMImmToTMMReg = [](unsigned Imm) {
33067     assert (Imm < 8 && "Illegal tmm index");
33068     return X86::TMM0 + Imm;
33069   };
33070   switch (MI.getOpcode()) {
33071   default: llvm_unreachable("Unexpected instr type to insert");
33072   case X86::TLS_addr32:
33073   case X86::TLS_addr64:
33074   case X86::TLS_base_addr32:
33075   case X86::TLS_base_addr64:
33076     return EmitLoweredTLSAddr(MI, BB);
33077   case X86::INDIRECT_THUNK_CALL32:
33078   case X86::INDIRECT_THUNK_CALL64:
33079   case X86::INDIRECT_THUNK_TCRETURN32:
33080   case X86::INDIRECT_THUNK_TCRETURN64:
33081     return EmitLoweredIndirectThunk(MI, BB);
33082   case X86::CATCHRET:
33083     return EmitLoweredCatchRet(MI, BB);
33084   case X86::SEG_ALLOCA_32:
33085   case X86::SEG_ALLOCA_64:
33086     return EmitLoweredSegAlloca(MI, BB);
33087   case X86::PROBED_ALLOCA_32:
33088   case X86::PROBED_ALLOCA_64:
33089     return EmitLoweredProbedAlloca(MI, BB);
33090   case X86::TLSCall_32:
33091   case X86::TLSCall_64:
33092     return EmitLoweredTLSCall(MI, BB);
33093   case X86::CMOV_FR32:
33094   case X86::CMOV_FR32X:
33095   case X86::CMOV_FR64:
33096   case X86::CMOV_FR64X:
33097   case X86::CMOV_GR8:
33098   case X86::CMOV_GR16:
33099   case X86::CMOV_GR32:
33100   case X86::CMOV_RFP32:
33101   case X86::CMOV_RFP64:
33102   case X86::CMOV_RFP80:
33103   case X86::CMOV_VR64:
33104   case X86::CMOV_VR128:
33105   case X86::CMOV_VR128X:
33106   case X86::CMOV_VR256:
33107   case X86::CMOV_VR256X:
33108   case X86::CMOV_VR512:
33109   case X86::CMOV_VK1:
33110   case X86::CMOV_VK2:
33111   case X86::CMOV_VK4:
33112   case X86::CMOV_VK8:
33113   case X86::CMOV_VK16:
33114   case X86::CMOV_VK32:
33115   case X86::CMOV_VK64:
33116     return EmitLoweredSelect(MI, BB);
33117 
33118   case X86::RDFLAGS32:
33119   case X86::RDFLAGS64: {
33120     unsigned PushF =
33121         MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
33122     unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
33123     MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
33124     // Permit reads of the EFLAGS and DF registers without them being defined.
33125     // This intrinsic exists to read external processor state in flags, such as
33126     // the trap flag, interrupt flag, and direction flag, none of which are
33127     // modeled by the backend.
33128     assert(Push->getOperand(2).getReg() == X86::EFLAGS &&
33129            "Unexpected register in operand!");
33130     Push->getOperand(2).setIsUndef();
33131     assert(Push->getOperand(3).getReg() == X86::DF &&
33132            "Unexpected register in operand!");
33133     Push->getOperand(3).setIsUndef();
33134     BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
33135 
33136     MI.eraseFromParent(); // The pseudo is gone now.
33137     return BB;
33138   }
33139 
33140   case X86::WRFLAGS32:
33141   case X86::WRFLAGS64: {
33142     unsigned Push =
33143         MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
33144     unsigned PopF =
33145         MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
33146     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
33147     BuildMI(*BB, MI, DL, TII->get(PopF));
33148 
33149     MI.eraseFromParent(); // The pseudo is gone now.
33150     return BB;
33151   }
33152 
33153   case X86::FP32_TO_INT16_IN_MEM:
33154   case X86::FP32_TO_INT32_IN_MEM:
33155   case X86::FP32_TO_INT64_IN_MEM:
33156   case X86::FP64_TO_INT16_IN_MEM:
33157   case X86::FP64_TO_INT32_IN_MEM:
33158   case X86::FP64_TO_INT64_IN_MEM:
33159   case X86::FP80_TO_INT16_IN_MEM:
33160   case X86::FP80_TO_INT32_IN_MEM:
33161   case X86::FP80_TO_INT64_IN_MEM: {
33162     // Change the floating point control register to use "round towards zero"
33163     // mode when truncating to an integer value.
33164     int OrigCWFrameIdx =
33165         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
33166     addFrameReference(BuildMI(*BB, MI, DL,
33167                               TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
33168 
33169     // Load the old value of the control word...
33170     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
33171     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
33172                       OrigCWFrameIdx);
33173 
33174     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
33175     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
33176     BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
33177       .addReg(OldCW, RegState::Kill).addImm(0xC00);
33178 
33179     // Extract to 16 bits.
33180     Register NewCW16 =
33181         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
33182     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
33183       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
33184 
33185     // Prepare memory for FLDCW.
33186     int NewCWFrameIdx =
33187         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
33188     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
33189                       NewCWFrameIdx)
33190       .addReg(NewCW16, RegState::Kill);
33191 
33192     // Reload the modified control word now...
33193     addFrameReference(BuildMI(*BB, MI, DL,
33194                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
33195 
33196     // Get the X86 opcode to use.
33197     unsigned Opc;
33198     switch (MI.getOpcode()) {
33199     default: llvm_unreachable("illegal opcode!");
33200     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
33201     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
33202     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
33203     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
33204     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
33205     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
33206     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
33207     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
33208     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
33209     }
33210 
33211     X86AddressMode AM = getAddressFromInstr(&MI, 0);
33212     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
33213         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
33214 
33215     // Reload the original control word now.
33216     addFrameReference(BuildMI(*BB, MI, DL,
33217                               TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
33218 
33219     MI.eraseFromParent(); // The pseudo instruction is gone now.
33220     return BB;
33221   }
33222 
33223   // xbegin
33224   case X86::XBEGIN:
33225     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
33226 
33227   case X86::VASTART_SAVE_XMM_REGS:
33228     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
33229 
33230   case X86::VAARG_64:
33231     return EmitVAARG64WithCustomInserter(MI, BB);
33232 
33233   case X86::EH_SjLj_SetJmp32:
33234   case X86::EH_SjLj_SetJmp64:
33235     return emitEHSjLjSetJmp(MI, BB);
33236 
33237   case X86::EH_SjLj_LongJmp32:
33238   case X86::EH_SjLj_LongJmp64:
33239     return emitEHSjLjLongJmp(MI, BB);
33240 
33241   case X86::Int_eh_sjlj_setup_dispatch:
33242     return EmitSjLjDispatchBlock(MI, BB);
33243 
33244   case TargetOpcode::STATEPOINT:
33245     // As an implementation detail, STATEPOINT shares the STACKMAP format at
33246     // this point in the process.  We diverge later.
33247     return emitPatchPoint(MI, BB);
33248 
33249   case TargetOpcode::STACKMAP:
33250   case TargetOpcode::PATCHPOINT:
33251     return emitPatchPoint(MI, BB);
33252 
33253   case TargetOpcode::PATCHABLE_EVENT_CALL:
33254     return emitXRayCustomEvent(MI, BB);
33255 
33256   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
33257     return emitXRayTypedEvent(MI, BB);
33258 
33259   case X86::LCMPXCHG8B: {
33260     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
33261     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
33262     // requires a memory operand. If it happens that current architecture is
33263     // i686 and for current function we need a base pointer
33264     // - which is ESI for i686 - register allocator would not be able to
33265     // allocate registers for an address in form of X(%reg, %reg, Y)
33266     // - there never would be enough unreserved registers during regalloc
33267     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
33268     // We are giving a hand to register allocator by precomputing the address in
33269     // a new vreg using LEA.
33270 
33271     // If it is not i686 or there is no base pointer - nothing to do here.
33272     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
33273       return BB;
33274 
33275     // Even though this code does not necessarily needs the base pointer to
33276     // be ESI, we check for that. The reason: if this assert fails, there are
33277     // some changes happened in the compiler base pointer handling, which most
33278     // probably have to be addressed somehow here.
33279     assert(TRI->getBaseRegister() == X86::ESI &&
33280            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
33281            "base pointer in mind");
33282 
33283     MachineRegisterInfo &MRI = MF->getRegInfo();
33284     MVT SPTy = getPointerTy(MF->getDataLayout());
33285     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
33286     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
33287 
33288     X86AddressMode AM = getAddressFromInstr(&MI, 0);
33289     // Regalloc does not need any help when the memory operand of CMPXCHG8B
33290     // does not use index register.
33291     if (AM.IndexReg == X86::NoRegister)
33292       return BB;
33293 
33294     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
33295     // four operand definitions that are E[ABCD] registers. We skip them and
33296     // then insert the LEA.
33297     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
33298     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
33299                                    RMBBI->definesRegister(X86::EBX) ||
33300                                    RMBBI->definesRegister(X86::ECX) ||
33301                                    RMBBI->definesRegister(X86::EDX))) {
33302       ++RMBBI;
33303     }
33304     MachineBasicBlock::iterator MBBI(RMBBI);
33305     addFullAddress(
33306         BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
33307 
33308     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
33309 
33310     return BB;
33311   }
33312   case X86::LCMPXCHG16B:
33313     return BB;
33314   case X86::LCMPXCHG8B_SAVE_EBX:
33315   case X86::LCMPXCHG16B_SAVE_RBX: {
33316     unsigned BasePtr =
33317         MI.getOpcode() == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
33318     if (!BB->isLiveIn(BasePtr))
33319       BB->addLiveIn(BasePtr);
33320     return BB;
33321   }
33322   case TargetOpcode::PREALLOCATED_SETUP: {
33323     assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
33324     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
33325     MFI->setHasPreallocatedCall(true);
33326     int64_t PreallocatedId = MI.getOperand(0).getImm();
33327     size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
33328     assert(StackAdjustment != 0 && "0 stack adjustment");
33329     LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
33330                       << StackAdjustment << "\n");
33331     BuildMI(*BB, MI, DL, TII->get(X86::SUB32ri), X86::ESP)
33332         .addReg(X86::ESP)
33333         .addImm(StackAdjustment);
33334     MI.eraseFromParent();
33335     return BB;
33336   }
33337   case TargetOpcode::PREALLOCATED_ARG: {
33338     assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
33339     int64_t PreallocatedId = MI.getOperand(1).getImm();
33340     int64_t ArgIdx = MI.getOperand(2).getImm();
33341     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
33342     size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
33343     LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
33344                       << ", arg offset " << ArgOffset << "\n");
33345     // stack pointer + offset
33346     addRegOffset(
33347         BuildMI(*BB, MI, DL, TII->get(X86::LEA32r), MI.getOperand(0).getReg()),
33348         X86::ESP, false, ArgOffset);
33349     MI.eraseFromParent();
33350     return BB;
33351   }
33352   case X86::PTDPBSSD:
33353   case X86::PTDPBSUD:
33354   case X86::PTDPBUSD:
33355   case X86::PTDPBUUD:
33356   case X86::PTDPBF16PS: {
33357     const DebugLoc &DL = MI.getDebugLoc();
33358     unsigned Opc;
33359     switch (MI.getOpcode()) {
33360     case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
33361     case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
33362     case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
33363     case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
33364     case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
33365     }
33366 
33367     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
33368     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
33369     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
33370     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
33371     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
33372 
33373     MI.eraseFromParent(); // The pseudo is gone now.
33374     return BB;
33375   }
33376   case X86::PTILEZERO: {
33377     const DebugLoc &DL = MI.getDebugLoc();
33378     unsigned Imm = MI.getOperand(0).getImm();
33379     BuildMI(*BB, MI, DL, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
33380     MI.eraseFromParent(); // The pseudo is gone now.
33381     return BB;
33382   }
33383   case X86::PTILELOADD:
33384   case X86::PTILELOADDT1:
33385   case X86::PTILESTORED: {
33386     const DebugLoc &DL = MI.getDebugLoc();
33387     unsigned Opc;
33388     switch (MI.getOpcode()) {
33389     case X86::PTILELOADD:   Opc = X86::TILELOADD;   break;
33390     case X86::PTILELOADDT1: Opc = X86::TILELOADDT1; break;
33391     case X86::PTILESTORED:  Opc = X86::TILESTORED;  break;
33392     }
33393 
33394     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
33395     unsigned CurOp = 0;
33396     if (Opc != X86::TILESTORED)
33397       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
33398                  RegState::Define);
33399 
33400     MIB.add(MI.getOperand(CurOp++)); // base
33401     MIB.add(MI.getOperand(CurOp++)); // scale
33402     MIB.add(MI.getOperand(CurOp++)); // index -- stride
33403     MIB.add(MI.getOperand(CurOp++)); // displacement
33404     MIB.add(MI.getOperand(CurOp++)); // segment
33405 
33406     if (Opc == X86::TILESTORED)
33407       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
33408                  RegState::Undef);
33409 
33410     MI.eraseFromParent(); // The pseudo is gone now.
33411     return BB;
33412   }
33413   }
33414 }
33415 
33416 //===----------------------------------------------------------------------===//
33417 //                           X86 Optimization Hooks
33418 //===----------------------------------------------------------------------===//
33419 
33420 bool
targetShrinkDemandedConstant(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,TargetLoweringOpt & TLO) const33421 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
33422                                                 const APInt &DemandedBits,
33423                                                 const APInt &DemandedElts,
33424                                                 TargetLoweringOpt &TLO) const {
33425   EVT VT = Op.getValueType();
33426   unsigned Opcode = Op.getOpcode();
33427   unsigned EltSize = VT.getScalarSizeInBits();
33428 
33429   if (VT.isVector()) {
33430     // If the constant is only all signbits in the active bits, then we should
33431     // extend it to the entire constant to allow it act as a boolean constant
33432     // vector.
33433     auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
33434       if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
33435         return false;
33436       for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
33437         if (!DemandedElts[i] || V.getOperand(i).isUndef())
33438           continue;
33439         const APInt &Val = V.getConstantOperandAPInt(i);
33440         if (Val.getBitWidth() > Val.getNumSignBits() &&
33441             Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
33442           return true;
33443       }
33444       return false;
33445     };
33446     // For vectors - if we have a constant, then try to sign extend.
33447     // TODO: Handle AND/ANDN cases.
33448     unsigned ActiveBits = DemandedBits.getActiveBits();
33449     if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
33450         (Opcode == ISD::OR || Opcode == ISD::XOR) &&
33451         NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
33452       EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
33453       EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
33454                                     VT.getVectorNumElements());
33455       SDValue NewC =
33456           TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
33457                           Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
33458       SDValue NewOp =
33459           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
33460       return TLO.CombineTo(Op, NewOp);
33461     }
33462     return false;
33463   }
33464 
33465   // Only optimize Ands to prevent shrinking a constant that could be
33466   // matched by movzx.
33467   if (Opcode != ISD::AND)
33468     return false;
33469 
33470   // Make sure the RHS really is a constant.
33471   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
33472   if (!C)
33473     return false;
33474 
33475   const APInt &Mask = C->getAPIntValue();
33476 
33477   // Clear all non-demanded bits initially.
33478   APInt ShrunkMask = Mask & DemandedBits;
33479 
33480   // Find the width of the shrunk mask.
33481   unsigned Width = ShrunkMask.getActiveBits();
33482 
33483   // If the mask is all 0s there's nothing to do here.
33484   if (Width == 0)
33485     return false;
33486 
33487   // Find the next power of 2 width, rounding up to a byte.
33488   Width = PowerOf2Ceil(std::max(Width, 8U));
33489   // Truncate the width to size to handle illegal types.
33490   Width = std::min(Width, EltSize);
33491 
33492   // Calculate a possible zero extend mask for this constant.
33493   APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
33494 
33495   // If we aren't changing the mask, just return true to keep it and prevent
33496   // the caller from optimizing.
33497   if (ZeroExtendMask == Mask)
33498     return true;
33499 
33500   // Make sure the new mask can be represented by a combination of mask bits
33501   // and non-demanded bits.
33502   if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
33503     return false;
33504 
33505   // Replace the constant with the zero extend mask.
33506   SDLoc DL(Op);
33507   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
33508   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
33509   return TLO.CombineTo(Op, NewOp);
33510 }
33511 
computeKnownBitsForTargetNode(const SDValue Op,KnownBits & Known,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const33512 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
33513                                                       KnownBits &Known,
33514                                                       const APInt &DemandedElts,
33515                                                       const SelectionDAG &DAG,
33516                                                       unsigned Depth) const {
33517   unsigned BitWidth = Known.getBitWidth();
33518   unsigned NumElts = DemandedElts.getBitWidth();
33519   unsigned Opc = Op.getOpcode();
33520   EVT VT = Op.getValueType();
33521   assert((Opc >= ISD::BUILTIN_OP_END ||
33522           Opc == ISD::INTRINSIC_WO_CHAIN ||
33523           Opc == ISD::INTRINSIC_W_CHAIN ||
33524           Opc == ISD::INTRINSIC_VOID) &&
33525          "Should use MaskedValueIsZero if you don't know whether Op"
33526          " is a target node!");
33527 
33528   Known.resetAll();
33529   switch (Opc) {
33530   default: break;
33531   case X86ISD::SETCC:
33532     Known.Zero.setBitsFrom(1);
33533     break;
33534   case X86ISD::MOVMSK: {
33535     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
33536     Known.Zero.setBitsFrom(NumLoBits);
33537     break;
33538   }
33539   case X86ISD::PEXTRB:
33540   case X86ISD::PEXTRW: {
33541     SDValue Src = Op.getOperand(0);
33542     EVT SrcVT = Src.getValueType();
33543     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
33544                                             Op.getConstantOperandVal(1));
33545     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
33546     Known = Known.anyextOrTrunc(BitWidth);
33547     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
33548     break;
33549   }
33550   case X86ISD::VSRAI:
33551   case X86ISD::VSHLI:
33552   case X86ISD::VSRLI: {
33553     unsigned ShAmt = Op.getConstantOperandVal(1);
33554     if (ShAmt >= VT.getScalarSizeInBits()) {
33555       Known.setAllZero();
33556       break;
33557     }
33558 
33559     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
33560     if (Opc == X86ISD::VSHLI) {
33561       Known.Zero <<= ShAmt;
33562       Known.One <<= ShAmt;
33563       // Low bits are known zero.
33564       Known.Zero.setLowBits(ShAmt);
33565     } else if (Opc == X86ISD::VSRLI) {
33566       Known.Zero.lshrInPlace(ShAmt);
33567       Known.One.lshrInPlace(ShAmt);
33568       // High bits are known zero.
33569       Known.Zero.setHighBits(ShAmt);
33570     } else {
33571       Known.Zero.ashrInPlace(ShAmt);
33572       Known.One.ashrInPlace(ShAmt);
33573     }
33574     break;
33575   }
33576   case X86ISD::PACKUS: {
33577     // PACKUS is just a truncation if the upper half is zero.
33578     APInt DemandedLHS, DemandedRHS;
33579     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
33580 
33581     Known.One = APInt::getAllOnesValue(BitWidth * 2);
33582     Known.Zero = APInt::getAllOnesValue(BitWidth * 2);
33583 
33584     KnownBits Known2;
33585     if (!!DemandedLHS) {
33586       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
33587       Known.One &= Known2.One;
33588       Known.Zero &= Known2.Zero;
33589     }
33590     if (!!DemandedRHS) {
33591       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
33592       Known.One &= Known2.One;
33593       Known.Zero &= Known2.Zero;
33594     }
33595 
33596     if (Known.countMinLeadingZeros() < BitWidth)
33597       Known.resetAll();
33598     Known = Known.trunc(BitWidth);
33599     break;
33600   }
33601   case X86ISD::ANDNP: {
33602     KnownBits Known2;
33603     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
33604     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
33605 
33606     // ANDNP = (~X & Y);
33607     Known.One &= Known2.Zero;
33608     Known.Zero |= Known2.One;
33609     break;
33610   }
33611   case X86ISD::FOR: {
33612     KnownBits Known2;
33613     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
33614     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
33615 
33616     Known |= Known2;
33617     break;
33618   }
33619   case X86ISD::PSADBW: {
33620     assert(VT.getScalarType() == MVT::i64 &&
33621            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
33622            "Unexpected PSADBW types");
33623 
33624     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
33625     Known.Zero.setBitsFrom(16);
33626     break;
33627   }
33628   case X86ISD::CMOV: {
33629     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
33630     // If we don't know any bits, early out.
33631     if (Known.isUnknown())
33632       break;
33633     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
33634 
33635     // Only known if known in both the LHS and RHS.
33636     Known.One &= Known2.One;
33637     Known.Zero &= Known2.Zero;
33638     break;
33639   }
33640   case X86ISD::BEXTR: {
33641     SDValue Op0 = Op.getOperand(0);
33642     SDValue Op1 = Op.getOperand(1);
33643 
33644     if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
33645       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
33646       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
33647 
33648       // If the length is 0, the result is 0.
33649       if (Length == 0) {
33650         Known.setAllZero();
33651         break;
33652       }
33653 
33654       if ((Shift + Length) <= BitWidth) {
33655         Known = DAG.computeKnownBits(Op0, Depth + 1);
33656         Known = Known.extractBits(Length, Shift);
33657         Known = Known.zextOrTrunc(BitWidth);
33658       }
33659     }
33660     break;
33661   }
33662   case X86ISD::CVTSI2P:
33663   case X86ISD::CVTUI2P:
33664   case X86ISD::CVTP2SI:
33665   case X86ISD::CVTP2UI:
33666   case X86ISD::MCVTP2SI:
33667   case X86ISD::MCVTP2UI:
33668   case X86ISD::CVTTP2SI:
33669   case X86ISD::CVTTP2UI:
33670   case X86ISD::MCVTTP2SI:
33671   case X86ISD::MCVTTP2UI:
33672   case X86ISD::MCVTSI2P:
33673   case X86ISD::MCVTUI2P:
33674   case X86ISD::VFPROUND:
33675   case X86ISD::VMFPROUND:
33676   case X86ISD::CVTPS2PH:
33677   case X86ISD::MCVTPS2PH: {
33678     // Conversions - upper elements are known zero.
33679     EVT SrcVT = Op.getOperand(0).getValueType();
33680     if (SrcVT.isVector()) {
33681       unsigned NumSrcElts = SrcVT.getVectorNumElements();
33682       if (NumElts > NumSrcElts &&
33683           DemandedElts.countTrailingZeros() >= NumSrcElts)
33684         Known.setAllZero();
33685     }
33686     break;
33687   }
33688   case X86ISD::STRICT_CVTTP2SI:
33689   case X86ISD::STRICT_CVTTP2UI:
33690   case X86ISD::STRICT_CVTSI2P:
33691   case X86ISD::STRICT_CVTUI2P:
33692   case X86ISD::STRICT_VFPROUND:
33693   case X86ISD::STRICT_CVTPS2PH: {
33694     // Strict Conversions - upper elements are known zero.
33695     EVT SrcVT = Op.getOperand(1).getValueType();
33696     if (SrcVT.isVector()) {
33697       unsigned NumSrcElts = SrcVT.getVectorNumElements();
33698       if (NumElts > NumSrcElts &&
33699           DemandedElts.countTrailingZeros() >= NumSrcElts)
33700         Known.setAllZero();
33701     }
33702     break;
33703   }
33704   case X86ISD::MOVQ2DQ: {
33705     // Move from MMX to XMM. Upper half of XMM should be 0.
33706     if (DemandedElts.countTrailingZeros() >= (NumElts / 2))
33707       Known.setAllZero();
33708     break;
33709   }
33710   }
33711 
33712   // Handle target shuffles.
33713   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
33714   if (isTargetShuffle(Opc)) {
33715     bool IsUnary;
33716     SmallVector<int, 64> Mask;
33717     SmallVector<SDValue, 2> Ops;
33718     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
33719                              IsUnary)) {
33720       unsigned NumOps = Ops.size();
33721       unsigned NumElts = VT.getVectorNumElements();
33722       if (Mask.size() == NumElts) {
33723         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
33724         Known.Zero.setAllBits(); Known.One.setAllBits();
33725         for (unsigned i = 0; i != NumElts; ++i) {
33726           if (!DemandedElts[i])
33727             continue;
33728           int M = Mask[i];
33729           if (M == SM_SentinelUndef) {
33730             // For UNDEF elements, we don't know anything about the common state
33731             // of the shuffle result.
33732             Known.resetAll();
33733             break;
33734           } else if (M == SM_SentinelZero) {
33735             Known.One.clearAllBits();
33736             continue;
33737           }
33738           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
33739                  "Shuffle index out of range");
33740 
33741           unsigned OpIdx = (unsigned)M / NumElts;
33742           unsigned EltIdx = (unsigned)M % NumElts;
33743           if (Ops[OpIdx].getValueType() != VT) {
33744             // TODO - handle target shuffle ops with different value types.
33745             Known.resetAll();
33746             break;
33747           }
33748           DemandedOps[OpIdx].setBit(EltIdx);
33749         }
33750         // Known bits are the values that are shared by every demanded element.
33751         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
33752           if (!DemandedOps[i])
33753             continue;
33754           KnownBits Known2 =
33755               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
33756           Known.One &= Known2.One;
33757           Known.Zero &= Known2.Zero;
33758         }
33759       }
33760     }
33761   }
33762 }
33763 
ComputeNumSignBitsForTargetNode(SDValue Op,const APInt & DemandedElts,const SelectionDAG & DAG,unsigned Depth) const33764 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
33765     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
33766     unsigned Depth) const {
33767   EVT VT = Op.getValueType();
33768   unsigned VTBits = VT.getScalarSizeInBits();
33769   unsigned Opcode = Op.getOpcode();
33770   switch (Opcode) {
33771   case X86ISD::SETCC_CARRY:
33772     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
33773     return VTBits;
33774 
33775   case X86ISD::VTRUNC: {
33776     SDValue Src = Op.getOperand(0);
33777     MVT SrcVT = Src.getSimpleValueType();
33778     unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
33779     assert(VTBits < NumSrcBits && "Illegal truncation input type");
33780     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
33781     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
33782     if (Tmp > (NumSrcBits - VTBits))
33783       return Tmp - (NumSrcBits - VTBits);
33784     return 1;
33785   }
33786 
33787   case X86ISD::PACKSS: {
33788     // PACKSS is just a truncation if the sign bits extend to the packed size.
33789     APInt DemandedLHS, DemandedRHS;
33790     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
33791                         DemandedRHS);
33792 
33793     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
33794     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
33795     if (!!DemandedLHS)
33796       Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
33797     if (!!DemandedRHS)
33798       Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
33799     unsigned Tmp = std::min(Tmp0, Tmp1);
33800     if (Tmp > (SrcBits - VTBits))
33801       return Tmp - (SrcBits - VTBits);
33802     return 1;
33803   }
33804 
33805   case X86ISD::VSHLI: {
33806     SDValue Src = Op.getOperand(0);
33807     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
33808     if (ShiftVal.uge(VTBits))
33809       return VTBits; // Shifted all bits out --> zero.
33810     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
33811     if (ShiftVal.uge(Tmp))
33812       return 1; // Shifted all sign bits out --> unknown.
33813     return Tmp - ShiftVal.getZExtValue();
33814   }
33815 
33816   case X86ISD::VSRAI: {
33817     SDValue Src = Op.getOperand(0);
33818     APInt ShiftVal = Op.getConstantOperandAPInt(1);
33819     if (ShiftVal.uge(VTBits - 1))
33820       return VTBits; // Sign splat.
33821     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
33822     ShiftVal += Tmp;
33823     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
33824   }
33825 
33826   case X86ISD::PCMPGT:
33827   case X86ISD::PCMPEQ:
33828   case X86ISD::CMPP:
33829   case X86ISD::VPCOM:
33830   case X86ISD::VPCOMU:
33831     // Vector compares return zero/all-bits result values.
33832     return VTBits;
33833 
33834   case X86ISD::ANDNP: {
33835     unsigned Tmp0 =
33836         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
33837     if (Tmp0 == 1) return 1; // Early out.
33838     unsigned Tmp1 =
33839         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
33840     return std::min(Tmp0, Tmp1);
33841   }
33842 
33843   case X86ISD::CMOV: {
33844     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
33845     if (Tmp0 == 1) return 1;  // Early out.
33846     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
33847     return std::min(Tmp0, Tmp1);
33848   }
33849   }
33850 
33851   // Handle target shuffles.
33852   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
33853   if (isTargetShuffle(Opcode)) {
33854     bool IsUnary;
33855     SmallVector<int, 64> Mask;
33856     SmallVector<SDValue, 2> Ops;
33857     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
33858                              IsUnary)) {
33859       unsigned NumOps = Ops.size();
33860       unsigned NumElts = VT.getVectorNumElements();
33861       if (Mask.size() == NumElts) {
33862         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
33863         for (unsigned i = 0; i != NumElts; ++i) {
33864           if (!DemandedElts[i])
33865             continue;
33866           int M = Mask[i];
33867           if (M == SM_SentinelUndef) {
33868             // For UNDEF elements, we don't know anything about the common state
33869             // of the shuffle result.
33870             return 1;
33871           } else if (M == SM_SentinelZero) {
33872             // Zero = all sign bits.
33873             continue;
33874           }
33875           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
33876                  "Shuffle index out of range");
33877 
33878           unsigned OpIdx = (unsigned)M / NumElts;
33879           unsigned EltIdx = (unsigned)M % NumElts;
33880           if (Ops[OpIdx].getValueType() != VT) {
33881             // TODO - handle target shuffle ops with different value types.
33882             return 1;
33883           }
33884           DemandedOps[OpIdx].setBit(EltIdx);
33885         }
33886         unsigned Tmp0 = VTBits;
33887         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
33888           if (!DemandedOps[i])
33889             continue;
33890           unsigned Tmp1 =
33891               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
33892           Tmp0 = std::min(Tmp0, Tmp1);
33893         }
33894         return Tmp0;
33895       }
33896     }
33897   }
33898 
33899   // Fallback case.
33900   return 1;
33901 }
33902 
unwrapAddress(SDValue N) const33903 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
33904   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
33905     return N->getOperand(0);
33906   return N;
33907 }
33908 
33909 // Helper to look for a normal load that can be narrowed into a vzload with the
33910 // specified VT and memory VT. Returns SDValue() on failure.
narrowLoadToVZLoad(LoadSDNode * LN,MVT MemVT,MVT VT,SelectionDAG & DAG)33911 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
33912                                   SelectionDAG &DAG) {
33913   // Can't if the load is volatile or atomic.
33914   if (!LN->isSimple())
33915     return SDValue();
33916 
33917   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
33918   SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
33919   return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
33920                                  LN->getPointerInfo(), LN->getOriginalAlign(),
33921                                  LN->getMemOperand()->getFlags());
33922 }
33923 
33924 // Attempt to match a combined shuffle mask against supported unary shuffle
33925 // instructions.
33926 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryShuffle(MVT MaskVT,ArrayRef<int> Mask,bool AllowFloatDomain,bool AllowIntDomain,SDValue & V1,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & SrcVT,MVT & DstVT)33927 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
33928                               bool AllowFloatDomain, bool AllowIntDomain,
33929                               SDValue &V1, const SDLoc &DL, SelectionDAG &DAG,
33930                               const X86Subtarget &Subtarget, unsigned &Shuffle,
33931                               MVT &SrcVT, MVT &DstVT) {
33932   unsigned NumMaskElts = Mask.size();
33933   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
33934 
33935   // Match against a VZEXT_MOVL vXi32 zero-extending instruction.
33936   if (MaskEltSize == 32 && isUndefOrEqual(Mask[0], 0) &&
33937       isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) {
33938     Shuffle = X86ISD::VZEXT_MOVL;
33939     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
33940     return true;
33941   }
33942 
33943   // Match against a ANY/ZERO_EXTEND_VECTOR_INREG instruction.
33944   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
33945   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
33946                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
33947     unsigned MaxScale = 64 / MaskEltSize;
33948     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
33949       bool MatchAny = true;
33950       bool MatchZero = true;
33951       unsigned NumDstElts = NumMaskElts / Scale;
33952       for (unsigned i = 0; i != NumDstElts && (MatchAny || MatchZero); ++i) {
33953         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
33954           MatchAny = MatchZero = false;
33955           break;
33956         }
33957         MatchAny &= isUndefInRange(Mask, (i * Scale) + 1, Scale - 1);
33958         MatchZero &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
33959       }
33960       if (MatchAny || MatchZero) {
33961         assert(MatchZero && "Failed to match zext but matched aext?");
33962         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
33963         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
33964                                             MVT::getIntegerVT(MaskEltSize);
33965         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
33966 
33967         if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
33968           V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
33969 
33970         Shuffle = unsigned(MatchAny ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND);
33971         if (SrcVT.getVectorNumElements() != NumDstElts)
33972           Shuffle = getOpcode_EXTEND_VECTOR_INREG(Shuffle);
33973 
33974         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
33975         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
33976         return true;
33977       }
33978     }
33979   }
33980 
33981   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
33982   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2())) &&
33983       isUndefOrEqual(Mask[0], 0) &&
33984       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
33985     Shuffle = X86ISD::VZEXT_MOVL;
33986     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
33987     return true;
33988   }
33989 
33990   // Check if we have SSE3 which will let us use MOVDDUP etc. The
33991   // instructions are no slower than UNPCKLPD but has the option to
33992   // fold the input operand into even an unaligned memory load.
33993   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
33994     if (isTargetShuffleEquivalent(Mask, {0, 0})) {
33995       Shuffle = X86ISD::MOVDDUP;
33996       SrcVT = DstVT = MVT::v2f64;
33997       return true;
33998     }
33999     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
34000       Shuffle = X86ISD::MOVSLDUP;
34001       SrcVT = DstVT = MVT::v4f32;
34002       return true;
34003     }
34004     if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3})) {
34005       Shuffle = X86ISD::MOVSHDUP;
34006       SrcVT = DstVT = MVT::v4f32;
34007       return true;
34008     }
34009   }
34010 
34011   if (MaskVT.is256BitVector() && AllowFloatDomain) {
34012     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
34013     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
34014       Shuffle = X86ISD::MOVDDUP;
34015       SrcVT = DstVT = MVT::v4f64;
34016       return true;
34017     }
34018     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
34019       Shuffle = X86ISD::MOVSLDUP;
34020       SrcVT = DstVT = MVT::v8f32;
34021       return true;
34022     }
34023     if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3, 5, 5, 7, 7})) {
34024       Shuffle = X86ISD::MOVSHDUP;
34025       SrcVT = DstVT = MVT::v8f32;
34026       return true;
34027     }
34028   }
34029 
34030   if (MaskVT.is512BitVector() && AllowFloatDomain) {
34031     assert(Subtarget.hasAVX512() &&
34032            "AVX512 required for 512-bit vector shuffles");
34033     if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
34034       Shuffle = X86ISD::MOVDDUP;
34035       SrcVT = DstVT = MVT::v8f64;
34036       return true;
34037     }
34038     if (isTargetShuffleEquivalent(
34039             Mask, {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14})) {
34040       Shuffle = X86ISD::MOVSLDUP;
34041       SrcVT = DstVT = MVT::v16f32;
34042       return true;
34043     }
34044     if (isTargetShuffleEquivalent(
34045             Mask, {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15})) {
34046       Shuffle = X86ISD::MOVSHDUP;
34047       SrcVT = DstVT = MVT::v16f32;
34048       return true;
34049     }
34050   }
34051 
34052   return false;
34053 }
34054 
34055 // Attempt to match a combined shuffle mask against supported unary immediate
34056 // permute instructions.
34057 // TODO: Investigate sharing more of this with shuffle lowering.
matchUnaryPermuteShuffle(MVT MaskVT,ArrayRef<int> Mask,const APInt & Zeroable,bool AllowFloatDomain,bool AllowIntDomain,const X86Subtarget & Subtarget,unsigned & Shuffle,MVT & ShuffleVT,unsigned & PermuteImm)34058 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
34059                                      const APInt &Zeroable,
34060                                      bool AllowFloatDomain, bool AllowIntDomain,
34061                                      const X86Subtarget &Subtarget,
34062                                      unsigned &Shuffle, MVT &ShuffleVT,
34063                                      unsigned &PermuteImm) {
34064   unsigned NumMaskElts = Mask.size();
34065   unsigned InputSizeInBits = MaskVT.getSizeInBits();
34066   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
34067   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
34068   bool ContainsZeros = isAnyZero(Mask);
34069 
34070   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
34071   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
34072     // Check for lane crossing permutes.
34073     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
34074       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
34075       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
34076         Shuffle = X86ISD::VPERMI;
34077         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
34078         PermuteImm = getV4X86ShuffleImm(Mask);
34079         return true;
34080       }
34081       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
34082         SmallVector<int, 4> RepeatedMask;
34083         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
34084           Shuffle = X86ISD::VPERMI;
34085           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
34086           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
34087           return true;
34088         }
34089       }
34090     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
34091       // VPERMILPD can permute with a non-repeating shuffle.
34092       Shuffle = X86ISD::VPERMILPI;
34093       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
34094       PermuteImm = 0;
34095       for (int i = 0, e = Mask.size(); i != e; ++i) {
34096         int M = Mask[i];
34097         if (M == SM_SentinelUndef)
34098           continue;
34099         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
34100         PermuteImm |= (M & 1) << i;
34101       }
34102       return true;
34103     }
34104   }
34105 
34106   // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
34107   // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
34108   // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
34109   if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
34110       !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
34111     SmallVector<int, 4> RepeatedMask;
34112     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
34113       // Narrow the repeated mask to create 32-bit element permutes.
34114       SmallVector<int, 4> WordMask = RepeatedMask;
34115       if (MaskScalarSizeInBits == 64)
34116         narrowShuffleMaskElts(2, RepeatedMask, WordMask);
34117 
34118       Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
34119       ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
34120       ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
34121       PermuteImm = getV4X86ShuffleImm(WordMask);
34122       return true;
34123     }
34124   }
34125 
34126   // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
34127   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16) {
34128     SmallVector<int, 4> RepeatedMask;
34129     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
34130       ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
34131       ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
34132 
34133       // PSHUFLW: permute lower 4 elements only.
34134       if (isUndefOrInRange(LoMask, 0, 4) &&
34135           isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
34136         Shuffle = X86ISD::PSHUFLW;
34137         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
34138         PermuteImm = getV4X86ShuffleImm(LoMask);
34139         return true;
34140       }
34141 
34142       // PSHUFHW: permute upper 4 elements only.
34143       if (isUndefOrInRange(HiMask, 4, 8) &&
34144           isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
34145         // Offset the HiMask so that we can create the shuffle immediate.
34146         int OffsetHiMask[4];
34147         for (int i = 0; i != 4; ++i)
34148           OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
34149 
34150         Shuffle = X86ISD::PSHUFHW;
34151         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
34152         PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
34153         return true;
34154       }
34155     }
34156   }
34157 
34158   // Attempt to match against byte/bit shifts.
34159   if (AllowIntDomain &&
34160       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
34161        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
34162        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
34163     int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
34164                                        Mask, 0, Zeroable, Subtarget);
34165     if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
34166                          32 <= ShuffleVT.getScalarSizeInBits())) {
34167       PermuteImm = (unsigned)ShiftAmt;
34168       return true;
34169     }
34170   }
34171 
34172   // Attempt to match against bit rotates.
34173   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
34174       ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
34175        Subtarget.hasAVX512())) {
34176     int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
34177                                             Subtarget, Mask);
34178     if (0 < RotateAmt) {
34179       Shuffle = X86ISD::VROTLI;
34180       PermuteImm = (unsigned)RotateAmt;
34181       return true;
34182     }
34183   }
34184 
34185   return false;
34186 }
34187 
34188 // Attempt to match a combined unary shuffle mask against supported binary
34189 // shuffle instructions.
34190 // 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)34191 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
34192                                bool AllowFloatDomain, bool AllowIntDomain,
34193                                SDValue &V1, SDValue &V2, const SDLoc &DL,
34194                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
34195                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
34196                                bool IsUnary) {
34197   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
34198 
34199   if (MaskVT.is128BitVector()) {
34200     if (isTargetShuffleEquivalent(Mask, {0, 0}) && AllowFloatDomain) {
34201       V2 = V1;
34202       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
34203       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
34204       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
34205       return true;
34206     }
34207     if (isTargetShuffleEquivalent(Mask, {1, 1}) && AllowFloatDomain) {
34208       V2 = V1;
34209       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
34210       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
34211       return true;
34212     }
34213     if (isTargetShuffleEquivalent(Mask, {0, 3}) && Subtarget.hasSSE2() &&
34214         (AllowFloatDomain || !Subtarget.hasSSE41())) {
34215       std::swap(V1, V2);
34216       Shuffle = X86ISD::MOVSD;
34217       SrcVT = DstVT = MVT::v2f64;
34218       return true;
34219     }
34220     if (isTargetShuffleEquivalent(Mask, {4, 1, 2, 3}) &&
34221         (AllowFloatDomain || !Subtarget.hasSSE41())) {
34222       Shuffle = X86ISD::MOVSS;
34223       SrcVT = DstVT = MVT::v4f32;
34224       return true;
34225     }
34226   }
34227 
34228   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
34229   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
34230       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
34231       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
34232     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
34233                              Subtarget)) {
34234       DstVT = MaskVT;
34235       return true;
34236     }
34237   }
34238 
34239   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
34240   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
34241       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
34242       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
34243       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
34244       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
34245     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
34246                               Subtarget)) {
34247       SrcVT = DstVT = MaskVT;
34248       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
34249         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
34250       return true;
34251     }
34252   }
34253 
34254   return false;
34255 }
34256 
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)34257 static bool matchBinaryPermuteShuffle(
34258     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
34259     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
34260     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
34261     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
34262   unsigned NumMaskElts = Mask.size();
34263   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
34264 
34265   // Attempt to match against VALIGND/VALIGNQ rotate.
34266   if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
34267       ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
34268        (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
34269        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
34270     if (!isAnyZero(Mask)) {
34271       int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
34272       if (0 < Rotation) {
34273         Shuffle = X86ISD::VALIGN;
34274         if (EltSizeInBits == 64)
34275           ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
34276         else
34277           ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
34278         PermuteImm = Rotation;
34279         return true;
34280       }
34281     }
34282   }
34283 
34284   // Attempt to match against PALIGNR byte rotate.
34285   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
34286                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
34287                          (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
34288     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
34289     if (0 < ByteRotation) {
34290       Shuffle = X86ISD::PALIGNR;
34291       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
34292       PermuteImm = ByteRotation;
34293       return true;
34294     }
34295   }
34296 
34297   // Attempt to combine to X86ISD::BLENDI.
34298   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
34299                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
34300       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
34301     uint64_t BlendMask = 0;
34302     bool ForceV1Zero = false, ForceV2Zero = false;
34303     SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
34304     if (matchShuffleAsBlend(V1, V2, TargetMask, Zeroable, ForceV1Zero,
34305                             ForceV2Zero, BlendMask)) {
34306       if (MaskVT == MVT::v16i16) {
34307         // We can only use v16i16 PBLENDW if the lanes are repeated.
34308         SmallVector<int, 8> RepeatedMask;
34309         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
34310                                         RepeatedMask)) {
34311           assert(RepeatedMask.size() == 8 &&
34312                  "Repeated mask size doesn't match!");
34313           PermuteImm = 0;
34314           for (int i = 0; i < 8; ++i)
34315             if (RepeatedMask[i] >= 8)
34316               PermuteImm |= 1 << i;
34317           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
34318           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
34319           Shuffle = X86ISD::BLENDI;
34320           ShuffleVT = MaskVT;
34321           return true;
34322         }
34323       } else {
34324         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
34325         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
34326         PermuteImm = (unsigned)BlendMask;
34327         Shuffle = X86ISD::BLENDI;
34328         ShuffleVT = MaskVT;
34329         return true;
34330       }
34331     }
34332   }
34333 
34334   // Attempt to combine to INSERTPS, but only if it has elements that need to
34335   // be set to zero.
34336   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
34337       MaskVT.is128BitVector() && isAnyZero(Mask) &&
34338       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
34339     Shuffle = X86ISD::INSERTPS;
34340     ShuffleVT = MVT::v4f32;
34341     return true;
34342   }
34343 
34344   // Attempt to combine to SHUFPD.
34345   if (AllowFloatDomain && EltSizeInBits == 64 &&
34346       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
34347        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
34348        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
34349     bool ForceV1Zero = false, ForceV2Zero = false;
34350     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
34351                                PermuteImm, Mask, Zeroable)) {
34352       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
34353       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
34354       Shuffle = X86ISD::SHUFP;
34355       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
34356       return true;
34357     }
34358   }
34359 
34360   // Attempt to combine to SHUFPS.
34361   if (AllowFloatDomain && EltSizeInBits == 32 &&
34362       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
34363        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
34364        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
34365     SmallVector<int, 4> RepeatedMask;
34366     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
34367       // Match each half of the repeated mask, to determine if its just
34368       // referencing one of the vectors, is zeroable or entirely undef.
34369       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
34370         int M0 = RepeatedMask[Offset];
34371         int M1 = RepeatedMask[Offset + 1];
34372 
34373         if (isUndefInRange(RepeatedMask, Offset, 2)) {
34374           return DAG.getUNDEF(MaskVT);
34375         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
34376           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
34377           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
34378           return getZeroVector(MaskVT, Subtarget, DAG, DL);
34379         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
34380           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
34381           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
34382           return V1;
34383         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
34384           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
34385           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
34386           return V2;
34387         }
34388 
34389         return SDValue();
34390       };
34391 
34392       int ShufMask[4] = {-1, -1, -1, -1};
34393       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
34394       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
34395 
34396       if (Lo && Hi) {
34397         V1 = Lo;
34398         V2 = Hi;
34399         Shuffle = X86ISD::SHUFP;
34400         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
34401         PermuteImm = getV4X86ShuffleImm(ShufMask);
34402         return true;
34403       }
34404     }
34405   }
34406 
34407   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
34408   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
34409       MaskVT.is128BitVector() &&
34410       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
34411     Shuffle = X86ISD::INSERTPS;
34412     ShuffleVT = MVT::v4f32;
34413     return true;
34414   }
34415 
34416   return false;
34417 }
34418 
34419 static SDValue combineX86ShuffleChainWithExtract(
34420     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
34421     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
34422     const X86Subtarget &Subtarget);
34423 
34424 /// Combine an arbitrary chain of shuffles into a single instruction if
34425 /// possible.
34426 ///
34427 /// This is the leaf of the recursive combine below. When we have found some
34428 /// chain of single-use x86 shuffle instructions and accumulated the combined
34429 /// shuffle mask represented by them, this will try to pattern match that mask
34430 /// into either a single instruction if there is a special purpose instruction
34431 /// for this operation, or into a PSHUFB instruction which is a fully general
34432 /// 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 AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)34433 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
34434                                       ArrayRef<int> BaseMask, int Depth,
34435                                       bool HasVariableMask,
34436                                       bool AllowVariableMask, SelectionDAG &DAG,
34437                                       const X86Subtarget &Subtarget) {
34438   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
34439   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
34440          "Unexpected number of shuffle inputs!");
34441 
34442   // Find the inputs that enter the chain. Note that multiple uses are OK
34443   // here, we're not going to remove the operands we find.
34444   bool UnaryShuffle = (Inputs.size() == 1);
34445   SDValue V1 = peekThroughBitcasts(Inputs[0]);
34446   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
34447                              : peekThroughBitcasts(Inputs[1]));
34448 
34449   MVT VT1 = V1.getSimpleValueType();
34450   MVT VT2 = V2.getSimpleValueType();
34451   MVT RootVT = Root.getSimpleValueType();
34452   assert(VT1.getSizeInBits() == RootVT.getSizeInBits() &&
34453          VT2.getSizeInBits() == RootVT.getSizeInBits() &&
34454          "Vector size mismatch");
34455 
34456   SDLoc DL(Root);
34457   SDValue Res;
34458 
34459   unsigned NumBaseMaskElts = BaseMask.size();
34460   if (NumBaseMaskElts == 1) {
34461     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
34462     return DAG.getBitcast(RootVT, V1);
34463   }
34464 
34465   bool OptForSize = DAG.shouldOptForSize();
34466   unsigned RootSizeInBits = RootVT.getSizeInBits();
34467   unsigned NumRootElts = RootVT.getVectorNumElements();
34468   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
34469   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
34470                      (RootVT.isFloatingPoint() && Depth >= 1) ||
34471                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
34472 
34473   // Don't combine if we are a AVX512/EVEX target and the mask element size
34474   // is different from the root element size - this would prevent writemasks
34475   // from being reused.
34476   bool IsMaskedShuffle = false;
34477   if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
34478     if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
34479         Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
34480       IsMaskedShuffle = true;
34481     }
34482   }
34483 
34484   // If we are shuffling a broadcast (and not introducing zeros) then
34485   // we can just use the broadcast directly. This works for smaller broadcast
34486   // elements as well as they already repeat across each mask element
34487   if (UnaryShuffle && isTargetShuffleSplat(V1) && !isAnyZero(BaseMask) &&
34488       (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0) {
34489     return DAG.getBitcast(RootVT, V1);
34490   }
34491 
34492   // Attempt to match a subvector broadcast.
34493   // shuffle(insert_subvector(undef, sub, 0), undef, 0, 0, 0, 0)
34494   if (UnaryShuffle &&
34495       (BaseMaskEltSizeInBits == 128 || BaseMaskEltSizeInBits == 256)) {
34496     SmallVector<int, 64> BroadcastMask(NumBaseMaskElts, 0);
34497     if (isTargetShuffleEquivalent(BaseMask, BroadcastMask)) {
34498       SDValue Src = Inputs[0];
34499       if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
34500           Src.getOperand(0).isUndef() &&
34501           Src.getOperand(1).getValueSizeInBits() == BaseMaskEltSizeInBits &&
34502           MayFoldLoad(Src.getOperand(1)) && isNullConstant(Src.getOperand(2))) {
34503         return DAG.getBitcast(RootVT, DAG.getNode(X86ISD::SUBV_BROADCAST, DL,
34504                                                   Src.getValueType(),
34505                                                   Src.getOperand(1)));
34506       }
34507     }
34508   }
34509 
34510   // Handle 128/256-bit lane shuffles of 512-bit vectors.
34511   if (RootVT.is512BitVector() &&
34512       (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
34513     MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
34514 
34515     // If the upper subvectors are zeroable, then an extract+insert is more
34516     // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
34517     // to zero the upper subvectors.
34518     if (isUndefOrZeroInRange(BaseMask, 1, NumBaseMaskElts - 1)) {
34519       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
34520         return SDValue(); // Nothing to do!
34521       assert(isInRange(BaseMask[0], 0, NumBaseMaskElts) &&
34522              "Unexpected lane shuffle");
34523       Res = DAG.getBitcast(ShuffleVT, V1);
34524       unsigned SubIdx = BaseMask[0] * (8 / NumBaseMaskElts);
34525       bool UseZero = isAnyZero(BaseMask);
34526       Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
34527       Res = widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
34528       return DAG.getBitcast(RootVT, Res);
34529     }
34530 
34531     // Narrow shuffle mask to v4x128.
34532     SmallVector<int, 4> Mask;
34533     assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
34534     narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, BaseMask, Mask);
34535 
34536     // Try to lower to vshuf64x2/vshuf32x4.
34537     auto MatchSHUF128 = [](MVT ShuffleVT, const SDLoc &DL, ArrayRef<int> Mask,
34538                            SDValue V1, SDValue V2, SelectionDAG &DAG) {
34539       unsigned PermMask = 0;
34540       // Insure elements came from the same Op.
34541       SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
34542       for (int i = 0; i < 4; ++i) {
34543         assert(Mask[i] >= -1 && "Illegal shuffle sentinel value");
34544         if (Mask[i] < 0)
34545           continue;
34546 
34547         SDValue Op = Mask[i] >= 4 ? V2 : V1;
34548         unsigned OpIndex = i / 2;
34549         if (Ops[OpIndex].isUndef())
34550           Ops[OpIndex] = Op;
34551         else if (Ops[OpIndex] != Op)
34552           return SDValue();
34553 
34554         // Convert the 128-bit shuffle mask selection values into 128-bit
34555         // selection bits defined by a vshuf64x2 instruction's immediate control
34556         // byte.
34557         PermMask |= (Mask[i] % 4) << (i * 2);
34558       }
34559 
34560       return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
34561                          DAG.getBitcast(ShuffleVT, Ops[0]),
34562                          DAG.getBitcast(ShuffleVT, Ops[1]),
34563                          DAG.getTargetConstant(PermMask, DL, MVT::i8));
34564     };
34565 
34566     // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
34567     // doesn't work because our mask is for 128 bits and we don't have an MVT
34568     // to match that.
34569     bool PreferPERMQ =
34570         UnaryShuffle && isUndefOrInRange(Mask[0], 0, 2) &&
34571         isUndefOrInRange(Mask[1], 0, 2) && isUndefOrInRange(Mask[2], 2, 4) &&
34572         isUndefOrInRange(Mask[3], 2, 4) &&
34573         (Mask[0] < 0 || Mask[2] < 0 || Mask[0] == (Mask[2] % 2)) &&
34574         (Mask[1] < 0 || Mask[3] < 0 || Mask[1] == (Mask[3] % 2));
34575 
34576     if (!isAnyZero(Mask) && !PreferPERMQ) {
34577       if (SDValue V = MatchSHUF128(ShuffleVT, DL, Mask, V1, V2, DAG))
34578         return DAG.getBitcast(RootVT, V);
34579     }
34580   }
34581 
34582   // Handle 128-bit lane shuffles of 256-bit vectors.
34583   if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
34584     MVT ShuffleVT = (FloatDomain ? MVT::v4f64 : MVT::v4i64);
34585 
34586     // If the upper half is zeroable, then an extract+insert is more optimal
34587     // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
34588     // zero the upper half.
34589     if (isUndefOrZero(BaseMask[1])) {
34590       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
34591         return SDValue(); // Nothing to do!
34592       assert(isInRange(BaseMask[0], 0, 2) && "Unexpected lane shuffle");
34593       Res = DAG.getBitcast(ShuffleVT, V1);
34594       Res = extract128BitVector(Res, BaseMask[0] * 2, DAG, DL);
34595       Res = widenSubVector(Res, BaseMask[1] == SM_SentinelZero, Subtarget, DAG,
34596                            DL, 256);
34597       return DAG.getBitcast(RootVT, Res);
34598     }
34599 
34600     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
34601       return SDValue(); // Nothing to do!
34602 
34603     // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
34604     // we need to use the zeroing feature.
34605     // Prefer blends for sequential shuffles unless we are optimizing for size.
34606     if (UnaryShuffle &&
34607         !(Subtarget.hasAVX2() && isUndefOrInRange(BaseMask, 0, 2)) &&
34608         (OptForSize || !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0))) {
34609       unsigned PermMask = 0;
34610       PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
34611       PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
34612 
34613       Res = DAG.getBitcast(ShuffleVT, V1);
34614       Res = DAG.getNode(X86ISD::VPERM2X128, DL, ShuffleVT, Res,
34615                         DAG.getUNDEF(ShuffleVT),
34616                         DAG.getTargetConstant(PermMask, DL, MVT::i8));
34617       return DAG.getBitcast(RootVT, Res);
34618     }
34619 
34620     if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
34621       return SDValue(); // Nothing to do!
34622 
34623     // TODO - handle AVX512VL cases with X86ISD::SHUF128.
34624     if (!UnaryShuffle && !IsMaskedShuffle) {
34625       assert(llvm::all_of(BaseMask, [](int M) { return 0 <= M && M < 4; }) &&
34626              "Unexpected shuffle sentinel value");
34627       // Prefer blends to X86ISD::VPERM2X128.
34628       if (!((BaseMask[0] == 0 && BaseMask[1] == 3) ||
34629             (BaseMask[0] == 2 && BaseMask[1] == 1))) {
34630         unsigned PermMask = 0;
34631         PermMask |= ((BaseMask[0] & 3) << 0);
34632         PermMask |= ((BaseMask[1] & 3) << 4);
34633 
34634         Res = DAG.getNode(
34635             X86ISD::VPERM2X128, DL, ShuffleVT,
34636             DAG.getBitcast(ShuffleVT, isInRange(BaseMask[0], 0, 2) ? V1 : V2),
34637             DAG.getBitcast(ShuffleVT, isInRange(BaseMask[1], 0, 2) ? V1 : V2),
34638             DAG.getTargetConstant(PermMask, DL, MVT::i8));
34639         return DAG.getBitcast(RootVT, Res);
34640       }
34641     }
34642   }
34643 
34644   // For masks that have been widened to 128-bit elements or more,
34645   // narrow back down to 64-bit elements.
34646   SmallVector<int, 64> Mask;
34647   if (BaseMaskEltSizeInBits > 64) {
34648     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
34649     int MaskScale = BaseMaskEltSizeInBits / 64;
34650     narrowShuffleMaskElts(MaskScale, BaseMask, Mask);
34651   } else {
34652     Mask.assign(BaseMask.begin(), BaseMask.end());
34653   }
34654 
34655   // For masked shuffles, we're trying to match the root width for better
34656   // writemask folding, attempt to scale the mask.
34657   // TODO - variable shuffles might need this to be widened again.
34658   if (IsMaskedShuffle && NumRootElts > Mask.size()) {
34659     assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
34660     int MaskScale = NumRootElts / Mask.size();
34661     SmallVector<int, 64> ScaledMask;
34662     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
34663     Mask = std::move(ScaledMask);
34664   }
34665 
34666   unsigned NumMaskElts = Mask.size();
34667   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
34668 
34669   // Determine the effective mask value type.
34670   FloatDomain &= (32 <= MaskEltSizeInBits);
34671   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
34672                            : MVT::getIntegerVT(MaskEltSizeInBits);
34673   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
34674 
34675   // Only allow legal mask types.
34676   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
34677     return SDValue();
34678 
34679   // Attempt to match the mask against known shuffle patterns.
34680   MVT ShuffleSrcVT, ShuffleVT;
34681   unsigned Shuffle, PermuteImm;
34682 
34683   // Which shuffle domains are permitted?
34684   // Permit domain crossing at higher combine depths.
34685   // TODO: Should we indicate which domain is preferred if both are allowed?
34686   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
34687   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
34688                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
34689 
34690   // Determine zeroable mask elements.
34691   APInt KnownUndef, KnownZero;
34692   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
34693   APInt Zeroable = KnownUndef | KnownZero;
34694 
34695   if (UnaryShuffle) {
34696     // Attempt to match against broadcast-from-vector.
34697     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
34698     if ((Subtarget.hasAVX2() ||
34699          (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
34700         (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
34701       SmallVector<int, 64> BroadcastMask(NumMaskElts, 0);
34702       if (isTargetShuffleEquivalent(Mask, BroadcastMask)) {
34703         if (V1.getValueType() == MaskVT &&
34704             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
34705             MayFoldLoad(V1.getOperand(0))) {
34706           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
34707             return SDValue(); // Nothing to do!
34708           Res = V1.getOperand(0);
34709           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
34710           return DAG.getBitcast(RootVT, Res);
34711         }
34712         if (Subtarget.hasAVX2()) {
34713           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
34714             return SDValue(); // Nothing to do!
34715           Res = DAG.getBitcast(MaskVT, V1);
34716           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
34717           return DAG.getBitcast(RootVT, Res);
34718         }
34719       }
34720     }
34721 
34722     SDValue NewV1 = V1; // Save operand in case early exit happens.
34723     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
34724                           DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
34725                           ShuffleVT) &&
34726         (!IsMaskedShuffle ||
34727          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
34728       if (Depth == 0 && Root.getOpcode() == Shuffle)
34729         return SDValue(); // Nothing to do!
34730       Res = DAG.getBitcast(ShuffleSrcVT, NewV1);
34731       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
34732       return DAG.getBitcast(RootVT, Res);
34733     }
34734 
34735     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
34736                                  AllowIntDomain, Subtarget, Shuffle, ShuffleVT,
34737                                  PermuteImm) &&
34738         (!IsMaskedShuffle ||
34739          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
34740       if (Depth == 0 && Root.getOpcode() == Shuffle)
34741         return SDValue(); // Nothing to do!
34742       Res = DAG.getBitcast(ShuffleVT, V1);
34743       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
34744                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
34745       return DAG.getBitcast(RootVT, Res);
34746     }
34747   }
34748 
34749   // Attempt to combine to INSERTPS, but only if the inserted element has come
34750   // from a scalar.
34751   // TODO: Handle other insertions here as well?
34752   if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
34753       MaskEltSizeInBits == 32 && Subtarget.hasSSE41() &&
34754       !isTargetShuffleEquivalent(Mask, {4, 1, 2, 3})) {
34755     SDValue SrcV1 = V1, SrcV2 = V2;
34756     if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask, DAG) &&
34757         SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
34758       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
34759         return SDValue(); // Nothing to do!
34760       Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
34761                         DAG.getBitcast(MVT::v4f32, SrcV1),
34762                         DAG.getBitcast(MVT::v4f32, SrcV2),
34763                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
34764       return DAG.getBitcast(RootVT, Res);
34765     }
34766   }
34767 
34768   SDValue NewV1 = V1; // Save operands in case early exit happens.
34769   SDValue NewV2 = V2;
34770   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
34771                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
34772                          ShuffleVT, UnaryShuffle) &&
34773       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
34774     if (Depth == 0 && Root.getOpcode() == Shuffle)
34775       return SDValue(); // Nothing to do!
34776     NewV1 = DAG.getBitcast(ShuffleSrcVT, NewV1);
34777     NewV2 = DAG.getBitcast(ShuffleSrcVT, NewV2);
34778     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
34779     return DAG.getBitcast(RootVT, Res);
34780   }
34781 
34782   NewV1 = V1; // Save operands in case early exit happens.
34783   NewV2 = V2;
34784   if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
34785                                 AllowIntDomain, NewV1, NewV2, DL, DAG,
34786                                 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
34787       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
34788     if (Depth == 0 && Root.getOpcode() == Shuffle)
34789       return SDValue(); // Nothing to do!
34790     NewV1 = DAG.getBitcast(ShuffleVT, NewV1);
34791     NewV2 = DAG.getBitcast(ShuffleVT, NewV2);
34792     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
34793                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
34794     return DAG.getBitcast(RootVT, Res);
34795   }
34796 
34797   // Typically from here on, we need an integer version of MaskVT.
34798   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
34799   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
34800 
34801   // Annoyingly, SSE4A instructions don't map into the above match helpers.
34802   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
34803     uint64_t BitLen, BitIdx;
34804     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
34805                             Zeroable)) {
34806       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
34807         return SDValue(); // Nothing to do!
34808       V1 = DAG.getBitcast(IntMaskVT, V1);
34809       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
34810                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
34811                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
34812       return DAG.getBitcast(RootVT, Res);
34813     }
34814 
34815     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
34816       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
34817         return SDValue(); // Nothing to do!
34818       V1 = DAG.getBitcast(IntMaskVT, V1);
34819       V2 = DAG.getBitcast(IntMaskVT, V2);
34820       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
34821                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
34822                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
34823       return DAG.getBitcast(RootVT, Res);
34824     }
34825   }
34826 
34827   // Match shuffle against TRUNCATE patterns.
34828   if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
34829     // Match against a VTRUNC instruction, accounting for src/dst sizes.
34830     if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
34831                              Subtarget)) {
34832       bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
34833                         ShuffleSrcVT.getVectorNumElements();
34834       unsigned Opc =
34835           IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
34836       if (Depth == 0 && Root.getOpcode() == Opc)
34837         return SDValue(); // Nothing to do!
34838       V1 = DAG.getBitcast(ShuffleSrcVT, V1);
34839       Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
34840       if (ShuffleVT.getSizeInBits() < RootSizeInBits)
34841         Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
34842       return DAG.getBitcast(RootVT, Res);
34843     }
34844 
34845     // Do we need a more general binary truncation pattern?
34846     if (RootSizeInBits < 512 &&
34847         ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
34848          (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
34849         (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
34850         isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
34851       if (Depth == 0 && Root.getOpcode() == ISD::TRUNCATE)
34852         return SDValue(); // Nothing to do!
34853       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
34854       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
34855       V1 = DAG.getBitcast(ShuffleSrcVT, V1);
34856       V2 = DAG.getBitcast(ShuffleSrcVT, V2);
34857       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
34858       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
34859       Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
34860       Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
34861       return DAG.getBitcast(RootVT, Res);
34862     }
34863   }
34864 
34865   // Don't try to re-form single instruction chains under any circumstances now
34866   // that we've done encoding canonicalization for them.
34867   if (Depth < 1)
34868     return SDValue();
34869 
34870   // Depth threshold above which we can efficiently use variable mask shuffles.
34871   int VariableShuffleDepth = Subtarget.hasFastVariableShuffle() ? 1 : 2;
34872   AllowVariableMask &= (Depth >= VariableShuffleDepth) || HasVariableMask;
34873 
34874   bool MaskContainsZeros = isAnyZero(Mask);
34875 
34876   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
34877     // If we have a single input lane-crossing shuffle then lower to VPERMV.
34878     if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
34879         ((Subtarget.hasAVX2() &&
34880           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
34881          (Subtarget.hasAVX512() &&
34882           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
34883            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
34884          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
34885          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
34886          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
34887          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
34888       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
34889       Res = DAG.getBitcast(MaskVT, V1);
34890       Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
34891       return DAG.getBitcast(RootVT, Res);
34892     }
34893 
34894     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
34895     // vector as the second source.
34896     if (UnaryShuffle && AllowVariableMask &&
34897         ((Subtarget.hasAVX512() &&
34898           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
34899            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
34900          (Subtarget.hasVLX() &&
34901           (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
34902            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
34903          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
34904          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
34905          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
34906          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
34907       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
34908       for (unsigned i = 0; i != NumMaskElts; ++i)
34909         if (Mask[i] == SM_SentinelZero)
34910           Mask[i] = NumMaskElts + i;
34911 
34912       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
34913       Res = DAG.getBitcast(MaskVT, V1);
34914       SDValue Zero = getZeroVector(MaskVT, Subtarget, DAG, DL);
34915       Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, Res, VPermMask, Zero);
34916       return DAG.getBitcast(RootVT, Res);
34917     }
34918 
34919     // If that failed and either input is extracted then try to combine as a
34920     // shuffle with the larger type.
34921     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
34922             Inputs, Root, BaseMask, Depth, HasVariableMask, AllowVariableMask,
34923             DAG, Subtarget))
34924       return WideShuffle;
34925 
34926     // If we have a dual input lane-crossing shuffle then lower to VPERMV3.
34927     if (AllowVariableMask && !MaskContainsZeros &&
34928         ((Subtarget.hasAVX512() &&
34929           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
34930            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
34931          (Subtarget.hasVLX() &&
34932           (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
34933            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
34934          (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
34935          (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
34936          (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
34937          (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
34938       SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
34939       V1 = DAG.getBitcast(MaskVT, V1);
34940       V2 = DAG.getBitcast(MaskVT, V2);
34941       Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
34942       return DAG.getBitcast(RootVT, Res);
34943     }
34944     return SDValue();
34945   }
34946 
34947   // See if we can combine a single input shuffle with zeros to a bit-mask,
34948   // which is much simpler than any shuffle.
34949   if (UnaryShuffle && MaskContainsZeros && AllowVariableMask &&
34950       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
34951       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
34952     APInt Zero = APInt::getNullValue(MaskEltSizeInBits);
34953     APInt AllOnes = APInt::getAllOnesValue(MaskEltSizeInBits);
34954     APInt UndefElts(NumMaskElts, 0);
34955     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
34956     for (unsigned i = 0; i != NumMaskElts; ++i) {
34957       int M = Mask[i];
34958       if (M == SM_SentinelUndef) {
34959         UndefElts.setBit(i);
34960         continue;
34961       }
34962       if (M == SM_SentinelZero)
34963         continue;
34964       EltBits[i] = AllOnes;
34965     }
34966     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
34967     Res = DAG.getBitcast(MaskVT, V1);
34968     unsigned AndOpcode =
34969         MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
34970     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
34971     return DAG.getBitcast(RootVT, Res);
34972   }
34973 
34974   // If we have a single input shuffle with different shuffle patterns in the
34975   // the 128-bit lanes use the variable mask to VPERMILPS.
34976   // TODO Combine other mask types at higher depths.
34977   if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
34978       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
34979        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
34980     SmallVector<SDValue, 16> VPermIdx;
34981     for (int M : Mask) {
34982       SDValue Idx =
34983           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
34984       VPermIdx.push_back(Idx);
34985     }
34986     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
34987     Res = DAG.getBitcast(MaskVT, V1);
34988     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
34989     return DAG.getBitcast(RootVT, Res);
34990   }
34991 
34992   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
34993   // to VPERMIL2PD/VPERMIL2PS.
34994   if (AllowVariableMask && Subtarget.hasXOP() &&
34995       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
34996        MaskVT == MVT::v8f32)) {
34997     // VPERMIL2 Operation.
34998     // Bits[3] - Match Bit.
34999     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
35000     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
35001     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
35002     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
35003     SmallVector<int, 8> VPerm2Idx;
35004     unsigned M2ZImm = 0;
35005     for (int M : Mask) {
35006       if (M == SM_SentinelUndef) {
35007         VPerm2Idx.push_back(-1);
35008         continue;
35009       }
35010       if (M == SM_SentinelZero) {
35011         M2ZImm = 2;
35012         VPerm2Idx.push_back(8);
35013         continue;
35014       }
35015       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
35016       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
35017       VPerm2Idx.push_back(Index);
35018     }
35019     V1 = DAG.getBitcast(MaskVT, V1);
35020     V2 = DAG.getBitcast(MaskVT, V2);
35021     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
35022     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
35023                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
35024     return DAG.getBitcast(RootVT, Res);
35025   }
35026 
35027   // If we have 3 or more shuffle instructions or a chain involving a variable
35028   // mask, we can replace them with a single PSHUFB instruction profitably.
35029   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
35030   // instructions, but in practice PSHUFB tends to be *very* fast so we're
35031   // more aggressive.
35032   if (UnaryShuffle && AllowVariableMask &&
35033       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
35034        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
35035        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
35036     SmallVector<SDValue, 16> PSHUFBMask;
35037     int NumBytes = RootVT.getSizeInBits() / 8;
35038     int Ratio = NumBytes / NumMaskElts;
35039     for (int i = 0; i < NumBytes; ++i) {
35040       int M = Mask[i / Ratio];
35041       if (M == SM_SentinelUndef) {
35042         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
35043         continue;
35044       }
35045       if (M == SM_SentinelZero) {
35046         PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
35047         continue;
35048       }
35049       M = Ratio * M + i % Ratio;
35050       assert((M / 16) == (i / 16) && "Lane crossing detected");
35051       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
35052     }
35053     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
35054     Res = DAG.getBitcast(ByteVT, V1);
35055     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
35056     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
35057     return DAG.getBitcast(RootVT, Res);
35058   }
35059 
35060   // With XOP, if we have a 128-bit binary input shuffle we can always combine
35061   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
35062   // slower than PSHUFB on targets that support both.
35063   if (AllowVariableMask && RootVT.is128BitVector() && Subtarget.hasXOP()) {
35064     // VPPERM Mask Operation
35065     // Bits[4:0] - Byte Index (0 - 31)
35066     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
35067     SmallVector<SDValue, 16> VPPERMMask;
35068     int NumBytes = 16;
35069     int Ratio = NumBytes / NumMaskElts;
35070     for (int i = 0; i < NumBytes; ++i) {
35071       int M = Mask[i / Ratio];
35072       if (M == SM_SentinelUndef) {
35073         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
35074         continue;
35075       }
35076       if (M == SM_SentinelZero) {
35077         VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
35078         continue;
35079       }
35080       M = Ratio * M + i % Ratio;
35081       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
35082     }
35083     MVT ByteVT = MVT::v16i8;
35084     V1 = DAG.getBitcast(ByteVT, V1);
35085     V2 = DAG.getBitcast(ByteVT, V2);
35086     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
35087     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
35088     return DAG.getBitcast(RootVT, Res);
35089   }
35090 
35091   // If that failed and either input is extracted then try to combine as a
35092   // shuffle with the larger type.
35093   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
35094           Inputs, Root, BaseMask, Depth, HasVariableMask, AllowVariableMask,
35095           DAG, Subtarget))
35096     return WideShuffle;
35097 
35098   // If we have a dual input shuffle then lower to VPERMV3.
35099   if (!UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
35100       ((Subtarget.hasAVX512() &&
35101         (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
35102          MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
35103        (Subtarget.hasVLX() &&
35104         (MaskVT == MVT::v2f64 || MaskVT == MVT::v2i64 || MaskVT == MVT::v4f64 ||
35105          MaskVT == MVT::v4i64 || MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 ||
35106          MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
35107        (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
35108        (Subtarget.hasBWI() && Subtarget.hasVLX() &&
35109         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16)) ||
35110        (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
35111        (Subtarget.hasVBMI() && Subtarget.hasVLX() &&
35112         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8)))) {
35113     SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
35114     V1 = DAG.getBitcast(MaskVT, V1);
35115     V2 = DAG.getBitcast(MaskVT, V2);
35116     Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
35117     return DAG.getBitcast(RootVT, Res);
35118   }
35119 
35120   // Failed to find any combines.
35121   return SDValue();
35122 }
35123 
35124 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
35125 // instruction if possible.
35126 //
35127 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
35128 // type size to attempt to combine:
35129 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
35130 // -->
35131 // extract_subvector(shuffle(x,y,m2),0)
combineX86ShuffleChainWithExtract(ArrayRef<SDValue> Inputs,SDValue Root,ArrayRef<int> BaseMask,int Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)35132 static SDValue combineX86ShuffleChainWithExtract(
35133     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
35134     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
35135     const X86Subtarget &Subtarget) {
35136   unsigned NumMaskElts = BaseMask.size();
35137   unsigned NumInputs = Inputs.size();
35138   if (NumInputs == 0)
35139     return SDValue();
35140 
35141   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
35142   SmallVector<unsigned, 4> Offsets(NumInputs, 0);
35143 
35144   // Peek through subvectors.
35145   // TODO: Support inter-mixed EXTRACT_SUBVECTORs + BITCASTs?
35146   unsigned WideSizeInBits = WideInputs[0].getValueSizeInBits();
35147   for (unsigned i = 0; i != NumInputs; ++i) {
35148     SDValue &Src = WideInputs[i];
35149     unsigned &Offset = Offsets[i];
35150     Src = peekThroughBitcasts(Src);
35151     EVT BaseVT = Src.getValueType();
35152     while (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
35153       Offset += Src.getConstantOperandVal(1);
35154       Src = Src.getOperand(0);
35155     }
35156     WideSizeInBits = std::max(WideSizeInBits,
35157                               (unsigned)Src.getValueSizeInBits());
35158     assert((Offset % BaseVT.getVectorNumElements()) == 0 &&
35159            "Unexpected subvector extraction");
35160     Offset /= BaseVT.getVectorNumElements();
35161     Offset *= NumMaskElts;
35162   }
35163 
35164   // Bail if we're always extracting from the lowest subvectors,
35165   // combineX86ShuffleChain should match this for the current width.
35166   if (llvm::all_of(Offsets, [](unsigned Offset) { return Offset == 0; }))
35167     return SDValue();
35168 
35169   EVT RootVT = Root.getValueType();
35170   unsigned RootSizeInBits = RootVT.getSizeInBits();
35171   unsigned Scale = WideSizeInBits / RootSizeInBits;
35172   assert((WideSizeInBits % RootSizeInBits) == 0 &&
35173          "Unexpected subvector extraction");
35174 
35175   // If the src vector types aren't the same, see if we can extend
35176   // them to match each other.
35177   // TODO: Support different scalar types?
35178   EVT WideSVT = WideInputs[0].getValueType().getScalarType();
35179   if (llvm::any_of(WideInputs, [&WideSVT, &DAG](SDValue Op) {
35180         return !DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()) ||
35181                Op.getValueType().getScalarType() != WideSVT;
35182       }))
35183     return SDValue();
35184 
35185   for (SDValue &NewInput : WideInputs) {
35186     assert((WideSizeInBits % NewInput.getValueSizeInBits()) == 0 &&
35187            "Shuffle vector size mismatch");
35188     if (WideSizeInBits > NewInput.getValueSizeInBits())
35189       NewInput = widenSubVector(NewInput, false, Subtarget, DAG,
35190                                 SDLoc(NewInput), WideSizeInBits);
35191     assert(WideSizeInBits == NewInput.getValueSizeInBits() &&
35192            "Unexpected subvector extraction");
35193   }
35194 
35195   // Create new mask for larger type.
35196   for (unsigned i = 1; i != NumInputs; ++i)
35197     Offsets[i] += i * Scale * NumMaskElts;
35198 
35199   SmallVector<int, 64> WideMask(BaseMask.begin(), BaseMask.end());
35200   for (int &M : WideMask) {
35201     if (M < 0)
35202       continue;
35203     M = (M % NumMaskElts) + Offsets[M / NumMaskElts];
35204   }
35205   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
35206 
35207   // Remove unused/repeated shuffle source ops.
35208   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
35209   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
35210 
35211   if (WideInputs.size() > 2)
35212     return SDValue();
35213 
35214   // Increase depth for every upper subvector we've peeked through.
35215   Depth += count_if(Offsets, [](unsigned Offset) { return Offset > 0; });
35216 
35217   // Attempt to combine wider chain.
35218   // TODO: Can we use a better Root?
35219   SDValue WideRoot = WideInputs[0];
35220   if (SDValue WideShuffle = combineX86ShuffleChain(
35221           WideInputs, WideRoot, WideMask, Depth, HasVariableMask,
35222           AllowVariableMask, DAG, Subtarget)) {
35223     WideShuffle =
35224         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
35225     return DAG.getBitcast(RootVT, WideShuffle);
35226   }
35227   return SDValue();
35228 }
35229 
35230 // Attempt to constant fold all of the constant source ops.
35231 // Returns true if the entire shuffle is folded to a constant.
35232 // 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)35233 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
35234                                            ArrayRef<int> Mask, SDValue Root,
35235                                            bool HasVariableMask,
35236                                            SelectionDAG &DAG,
35237                                            const X86Subtarget &Subtarget) {
35238   MVT VT = Root.getSimpleValueType();
35239 
35240   unsigned SizeInBits = VT.getSizeInBits();
35241   unsigned NumMaskElts = Mask.size();
35242   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
35243   unsigned NumOps = Ops.size();
35244 
35245   // Extract constant bits from each source op.
35246   bool OneUseConstantOp = false;
35247   SmallVector<APInt, 16> UndefEltsOps(NumOps);
35248   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
35249   for (unsigned i = 0; i != NumOps; ++i) {
35250     SDValue SrcOp = Ops[i];
35251     OneUseConstantOp |= SrcOp.hasOneUse();
35252     if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
35253                                        RawBitsOps[i]))
35254       return SDValue();
35255   }
35256 
35257   // Only fold if at least one of the constants is only used once or
35258   // the combined shuffle has included a variable mask shuffle, this
35259   // is to avoid constant pool bloat.
35260   if (!OneUseConstantOp && !HasVariableMask)
35261     return SDValue();
35262 
35263   // Shuffle the constant bits according to the mask.
35264   SDLoc DL(Root);
35265   APInt UndefElts(NumMaskElts, 0);
35266   APInt ZeroElts(NumMaskElts, 0);
35267   APInt ConstantElts(NumMaskElts, 0);
35268   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
35269                                         APInt::getNullValue(MaskSizeInBits));
35270   for (unsigned i = 0; i != NumMaskElts; ++i) {
35271     int M = Mask[i];
35272     if (M == SM_SentinelUndef) {
35273       UndefElts.setBit(i);
35274       continue;
35275     } else if (M == SM_SentinelZero) {
35276       ZeroElts.setBit(i);
35277       continue;
35278     }
35279     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
35280 
35281     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
35282     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
35283 
35284     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
35285     if (SrcUndefElts[SrcMaskIdx]) {
35286       UndefElts.setBit(i);
35287       continue;
35288     }
35289 
35290     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
35291     APInt &Bits = SrcEltBits[SrcMaskIdx];
35292     if (!Bits) {
35293       ZeroElts.setBit(i);
35294       continue;
35295     }
35296 
35297     ConstantElts.setBit(i);
35298     ConstantBitData[i] = Bits;
35299   }
35300   assert((UndefElts | ZeroElts | ConstantElts).isAllOnesValue());
35301 
35302   // Attempt to create a zero vector.
35303   if ((UndefElts | ZeroElts).isAllOnesValue())
35304     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
35305 
35306   // Create the constant data.
35307   MVT MaskSVT;
35308   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
35309     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
35310   else
35311     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
35312 
35313   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
35314   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
35315     return SDValue();
35316 
35317   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
35318   return DAG.getBitcast(VT, CstOp);
35319 }
35320 
35321 /// Fully generic combining of x86 shuffle instructions.
35322 ///
35323 /// This should be the last combine run over the x86 shuffle instructions. Once
35324 /// they have been fully optimized, this will recursively consider all chains
35325 /// of single-use shuffle instructions, build a generic model of the cumulative
35326 /// shuffle operation, and check for simpler instructions which implement this
35327 /// operation. We use this primarily for two purposes:
35328 ///
35329 /// 1) Collapse generic shuffles to specialized single instructions when
35330 ///    equivalent. In most cases, this is just an encoding size win, but
35331 ///    sometimes we will collapse multiple generic shuffles into a single
35332 ///    special-purpose shuffle.
35333 /// 2) Look for sequences of shuffle instructions with 3 or more total
35334 ///    instructions, and replace them with the slightly more expensive SSSE3
35335 ///    PSHUFB instruction if available. We do this as the last combining step
35336 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
35337 ///    a suitable short sequence of other instructions. The PSHUFB will either
35338 ///    use a register or have to read from memory and so is slightly (but only
35339 ///    slightly) more expensive than the other shuffle instructions.
35340 ///
35341 /// Because this is inherently a quadratic operation (for each shuffle in
35342 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
35343 /// This should never be an issue in practice as the shuffle lowering doesn't
35344 /// produce sequences of more than 8 instructions.
35345 ///
35346 /// FIXME: We will currently miss some cases where the redundant shuffling
35347 /// would simplify under the threshold for PSHUFB formation because of
35348 /// combine-ordering. To fix this, we should do the redundant instruction
35349 /// combining in this recursive walk.
combineX86ShufflesRecursively(ArrayRef<SDValue> SrcOps,int SrcOpIndex,SDValue Root,ArrayRef<int> RootMask,ArrayRef<const SDNode * > SrcNodes,unsigned Depth,bool HasVariableMask,bool AllowVariableMask,SelectionDAG & DAG,const X86Subtarget & Subtarget)35350 static SDValue combineX86ShufflesRecursively(
35351     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
35352     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
35353     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
35354     const X86Subtarget &Subtarget) {
35355   assert(RootMask.size() > 0 &&
35356          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
35357          "Illegal shuffle root mask");
35358 
35359   // Bound the depth of our recursive combine because this is ultimately
35360   // quadratic in nature.
35361   const unsigned MaxRecursionDepth = 8;
35362   if (Depth >= MaxRecursionDepth)
35363     return SDValue();
35364 
35365   // Directly rip through bitcasts to find the underlying operand.
35366   SDValue Op = SrcOps[SrcOpIndex];
35367   Op = peekThroughOneUseBitcasts(Op);
35368 
35369   MVT VT = Op.getSimpleValueType();
35370   if (!VT.isVector())
35371     return SDValue(); // Bail if we hit a non-vector.
35372 
35373   assert(Root.getSimpleValueType().isVector() &&
35374          "Shuffles operate on vector types!");
35375   unsigned RootSizeInBits = Root.getSimpleValueType().getSizeInBits();
35376   assert(VT.getSizeInBits() == RootSizeInBits &&
35377          "Can only combine shuffles of the same vector register size.");
35378 
35379   // Extract target shuffle mask and resolve sentinels and inputs.
35380   // TODO - determine Op's demanded elts from RootMask.
35381   SmallVector<int, 64> OpMask;
35382   SmallVector<SDValue, 2> OpInputs;
35383   APInt OpUndef, OpZero;
35384   APInt OpDemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
35385   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
35386   if (!getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
35387                               OpZero, DAG, Depth, false))
35388     return SDValue();
35389 
35390   // Shuffle inputs must be the same size as the result, bail on any larger
35391   // inputs and widen any smaller inputs.
35392   if (llvm::any_of(OpInputs, [RootSizeInBits](SDValue Op) {
35393         return Op.getValueSizeInBits() > RootSizeInBits;
35394       }))
35395     return SDValue();
35396 
35397   for (SDValue &Op : OpInputs)
35398     if (Op.getValueSizeInBits() < RootSizeInBits)
35399       Op = widenSubVector(peekThroughOneUseBitcasts(Op), false, Subtarget, DAG,
35400                           SDLoc(Op), RootSizeInBits);
35401 
35402   SmallVector<int, 64> Mask;
35403   SmallVector<SDValue, 16> Ops;
35404 
35405   // We don't need to merge masks if the root is empty.
35406   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
35407   if (EmptyRoot) {
35408     // Only resolve zeros if it will remove an input, otherwise we might end
35409     // up in an infinite loop.
35410     bool ResolveKnownZeros = true;
35411     if (!OpZero.isNullValue()) {
35412       APInt UsedInputs = APInt::getNullValue(OpInputs.size());
35413       for (int i = 0, e = OpMask.size(); i != e; ++i) {
35414         int M = OpMask[i];
35415         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
35416           continue;
35417         UsedInputs.setBit(M / OpMask.size());
35418         if (UsedInputs.isAllOnesValue()) {
35419           ResolveKnownZeros = false;
35420           break;
35421         }
35422       }
35423     }
35424     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
35425                                       ResolveKnownZeros);
35426 
35427     Mask = OpMask;
35428     Ops.append(OpInputs.begin(), OpInputs.end());
35429   } else {
35430     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
35431 
35432     // Add the inputs to the Ops list, avoiding duplicates.
35433     Ops.append(SrcOps.begin(), SrcOps.end());
35434 
35435     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
35436       // Attempt to find an existing match.
35437       SDValue InputBC = peekThroughBitcasts(Input);
35438       for (int i = 0, e = Ops.size(); i < e; ++i)
35439         if (InputBC == peekThroughBitcasts(Ops[i]))
35440           return i;
35441       // Match failed - should we replace an existing Op?
35442       if (InsertionPoint >= 0) {
35443         Ops[InsertionPoint] = Input;
35444         return InsertionPoint;
35445       }
35446       // Add to the end of the Ops list.
35447       Ops.push_back(Input);
35448       return Ops.size() - 1;
35449     };
35450 
35451     SmallVector<int, 2> OpInputIdx;
35452     for (SDValue OpInput : OpInputs)
35453       OpInputIdx.push_back(
35454           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
35455 
35456     assert(((RootMask.size() > OpMask.size() &&
35457              RootMask.size() % OpMask.size() == 0) ||
35458             (OpMask.size() > RootMask.size() &&
35459              OpMask.size() % RootMask.size() == 0) ||
35460             OpMask.size() == RootMask.size()) &&
35461            "The smaller number of elements must divide the larger.");
35462 
35463     // This function can be performance-critical, so we rely on the power-of-2
35464     // knowledge that we have about the mask sizes to replace div/rem ops with
35465     // bit-masks and shifts.
35466     assert(isPowerOf2_32(RootMask.size()) &&
35467            "Non-power-of-2 shuffle mask sizes");
35468     assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes");
35469     unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
35470     unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
35471 
35472     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
35473     unsigned RootRatio =
35474         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
35475     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
35476     assert((RootRatio == 1 || OpRatio == 1) &&
35477            "Must not have a ratio for both incoming and op masks!");
35478 
35479     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
35480     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
35481     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
35482     unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
35483     unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
35484 
35485     Mask.resize(MaskWidth, SM_SentinelUndef);
35486 
35487     // Merge this shuffle operation's mask into our accumulated mask. Note that
35488     // this shuffle's mask will be the first applied to the input, followed by
35489     // the root mask to get us all the way to the root value arrangement. The
35490     // reason for this order is that we are recursing up the operation chain.
35491     for (unsigned i = 0; i < MaskWidth; ++i) {
35492       unsigned RootIdx = i >> RootRatioLog2;
35493       if (RootMask[RootIdx] < 0) {
35494         // This is a zero or undef lane, we're done.
35495         Mask[i] = RootMask[RootIdx];
35496         continue;
35497       }
35498 
35499       unsigned RootMaskedIdx =
35500           RootRatio == 1
35501               ? RootMask[RootIdx]
35502               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
35503 
35504       // Just insert the scaled root mask value if it references an input other
35505       // than the SrcOp we're currently inserting.
35506       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
35507           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
35508         Mask[i] = RootMaskedIdx;
35509         continue;
35510       }
35511 
35512       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
35513       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
35514       if (OpMask[OpIdx] < 0) {
35515         // The incoming lanes are zero or undef, it doesn't matter which ones we
35516         // are using.
35517         Mask[i] = OpMask[OpIdx];
35518         continue;
35519       }
35520 
35521       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
35522       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
35523                                           : (OpMask[OpIdx] << OpRatioLog2) +
35524                                                 (RootMaskedIdx & (OpRatio - 1));
35525 
35526       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
35527       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
35528       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
35529       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
35530 
35531       Mask[i] = OpMaskedIdx;
35532     }
35533   }
35534 
35535   // Remove unused/repeated shuffle source ops.
35536   resolveTargetShuffleInputsAndMask(Ops, Mask);
35537 
35538   // Handle the all undef/zero cases early.
35539   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
35540     return DAG.getUNDEF(Root.getValueType());
35541 
35542   // TODO - should we handle the mixed zero/undef case as well? Just returning
35543   // a zero mask will lose information on undef elements possibly reducing
35544   // future combine possibilities.
35545   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
35546     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
35547                          SDLoc(Root));
35548 
35549   assert(!Ops.empty() && "Shuffle with no inputs detected");
35550   HasVariableMask |= IsOpVariableMask;
35551 
35552   // Update the list of shuffle nodes that have been combined so far.
35553   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
35554                                                 SrcNodes.end());
35555   CombinedNodes.push_back(Op.getNode());
35556 
35557   // See if we can recurse into each shuffle source op (if it's a target
35558   // shuffle). The source op should only be generally combined if it either has
35559   // a single use (i.e. current Op) or all its users have already been combined,
35560   // if not then we can still combine but should prevent generation of variable
35561   // shuffles to avoid constant pool bloat.
35562   // Don't recurse if we already have more source ops than we can combine in
35563   // the remaining recursion depth.
35564   if (Ops.size() < (MaxRecursionDepth - Depth)) {
35565     for (int i = 0, e = Ops.size(); i < e; ++i) {
35566       // For empty roots, we need to resolve zeroable elements before combining
35567       // them with other shuffles.
35568       SmallVector<int, 64> ResolvedMask = Mask;
35569       if (EmptyRoot)
35570         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
35571       bool AllowVar = false;
35572       if (Ops[i].getNode()->hasOneUse() ||
35573           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode()))
35574         AllowVar = AllowVariableMask;
35575       if (SDValue Res = combineX86ShufflesRecursively(
35576               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1,
35577               HasVariableMask, AllowVar, DAG, Subtarget))
35578         return Res;
35579     }
35580   }
35581 
35582   // Attempt to constant fold all of the constant source ops.
35583   if (SDValue Cst = combineX86ShufflesConstants(
35584           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
35585     return Cst;
35586 
35587   // We can only combine unary and binary shuffle mask cases.
35588   if (Ops.size() <= 2) {
35589     // Minor canonicalization of the accumulated shuffle mask to make it easier
35590     // to match below. All this does is detect masks with sequential pairs of
35591     // elements, and shrink them to the half-width mask. It does this in a loop
35592     // so it will reduce the size of the mask to the minimal width mask which
35593     // performs an equivalent shuffle.
35594     SmallVector<int, 64> WidenedMask;
35595     while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
35596       Mask = std::move(WidenedMask);
35597     }
35598 
35599     // Canonicalization of binary shuffle masks to improve pattern matching by
35600     // commuting the inputs.
35601     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
35602       ShuffleVectorSDNode::commuteMask(Mask);
35603       std::swap(Ops[0], Ops[1]);
35604     }
35605 
35606     // Finally, try to combine into a single shuffle instruction.
35607     return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
35608                                   AllowVariableMask, DAG, Subtarget);
35609   }
35610 
35611   // If that failed and any input is extracted then try to combine as a
35612   // shuffle with the larger type.
35613   return combineX86ShuffleChainWithExtract(Ops, Root, Mask, Depth,
35614                                            HasVariableMask, AllowVariableMask,
35615                                            DAG, Subtarget);
35616 }
35617 
35618 /// Helper entry wrapper to combineX86ShufflesRecursively.
combineX86ShufflesRecursively(SDValue Op,SelectionDAG & DAG,const X86Subtarget & Subtarget)35619 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
35620                                              const X86Subtarget &Subtarget) {
35621   return combineX86ShufflesRecursively({Op}, 0, Op, {0}, {}, /*Depth*/ 0,
35622                                        /*HasVarMask*/ false,
35623                                        /*AllowVarMask*/ true, DAG, Subtarget);
35624 }
35625 
35626 /// Get the PSHUF-style mask from PSHUF node.
35627 ///
35628 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
35629 /// PSHUF-style masks that can be reused with such instructions.
getPSHUFShuffleMask(SDValue N)35630 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
35631   MVT VT = N.getSimpleValueType();
35632   SmallVector<int, 4> Mask;
35633   SmallVector<SDValue, 2> Ops;
35634   bool IsUnary;
35635   bool HaveMask =
35636       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask, IsUnary);
35637   (void)HaveMask;
35638   assert(HaveMask);
35639 
35640   // If we have more than 128-bits, only the low 128-bits of shuffle mask
35641   // matter. Check that the upper masks are repeats and remove them.
35642   if (VT.getSizeInBits() > 128) {
35643     int LaneElts = 128 / VT.getScalarSizeInBits();
35644 #ifndef NDEBUG
35645     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
35646       for (int j = 0; j < LaneElts; ++j)
35647         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
35648                "Mask doesn't repeat in high 128-bit lanes!");
35649 #endif
35650     Mask.resize(LaneElts);
35651   }
35652 
35653   switch (N.getOpcode()) {
35654   case X86ISD::PSHUFD:
35655     return Mask;
35656   case X86ISD::PSHUFLW:
35657     Mask.resize(4);
35658     return Mask;
35659   case X86ISD::PSHUFHW:
35660     Mask.erase(Mask.begin(), Mask.begin() + 4);
35661     for (int &M : Mask)
35662       M -= 4;
35663     return Mask;
35664   default:
35665     llvm_unreachable("No valid shuffle instruction found!");
35666   }
35667 }
35668 
35669 /// Search for a combinable shuffle across a chain ending in pshufd.
35670 ///
35671 /// We walk up the chain and look for a combinable shuffle, skipping over
35672 /// shuffles that we could hoist this shuffle's transformation past without
35673 /// altering anything.
35674 static SDValue
combineRedundantDWordShuffle(SDValue N,MutableArrayRef<int> Mask,SelectionDAG & DAG)35675 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
35676                              SelectionDAG &DAG) {
35677   assert(N.getOpcode() == X86ISD::PSHUFD &&
35678          "Called with something other than an x86 128-bit half shuffle!");
35679   SDLoc DL(N);
35680 
35681   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
35682   // of the shuffles in the chain so that we can form a fresh chain to replace
35683   // this one.
35684   SmallVector<SDValue, 8> Chain;
35685   SDValue V = N.getOperand(0);
35686   for (; V.hasOneUse(); V = V.getOperand(0)) {
35687     switch (V.getOpcode()) {
35688     default:
35689       return SDValue(); // Nothing combined!
35690 
35691     case ISD::BITCAST:
35692       // Skip bitcasts as we always know the type for the target specific
35693       // instructions.
35694       continue;
35695 
35696     case X86ISD::PSHUFD:
35697       // Found another dword shuffle.
35698       break;
35699 
35700     case X86ISD::PSHUFLW:
35701       // Check that the low words (being shuffled) are the identity in the
35702       // dword shuffle, and the high words are self-contained.
35703       if (Mask[0] != 0 || Mask[1] != 1 ||
35704           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
35705         return SDValue();
35706 
35707       Chain.push_back(V);
35708       continue;
35709 
35710     case X86ISD::PSHUFHW:
35711       // Check that the high words (being shuffled) are the identity in the
35712       // dword shuffle, and the low words are self-contained.
35713       if (Mask[2] != 2 || Mask[3] != 3 ||
35714           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
35715         return SDValue();
35716 
35717       Chain.push_back(V);
35718       continue;
35719 
35720     case X86ISD::UNPCKL:
35721     case X86ISD::UNPCKH:
35722       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
35723       // shuffle into a preceding word shuffle.
35724       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
35725           V.getSimpleValueType().getVectorElementType() != MVT::i16)
35726         return SDValue();
35727 
35728       // Search for a half-shuffle which we can combine with.
35729       unsigned CombineOp =
35730           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
35731       if (V.getOperand(0) != V.getOperand(1) ||
35732           !V->isOnlyUserOf(V.getOperand(0).getNode()))
35733         return SDValue();
35734       Chain.push_back(V);
35735       V = V.getOperand(0);
35736       do {
35737         switch (V.getOpcode()) {
35738         default:
35739           return SDValue(); // Nothing to combine.
35740 
35741         case X86ISD::PSHUFLW:
35742         case X86ISD::PSHUFHW:
35743           if (V.getOpcode() == CombineOp)
35744             break;
35745 
35746           Chain.push_back(V);
35747 
35748           LLVM_FALLTHROUGH;
35749         case ISD::BITCAST:
35750           V = V.getOperand(0);
35751           continue;
35752         }
35753         break;
35754       } while (V.hasOneUse());
35755       break;
35756     }
35757     // Break out of the loop if we break out of the switch.
35758     break;
35759   }
35760 
35761   if (!V.hasOneUse())
35762     // We fell out of the loop without finding a viable combining instruction.
35763     return SDValue();
35764 
35765   // Merge this node's mask and our incoming mask.
35766   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
35767   for (int &M : Mask)
35768     M = VMask[M];
35769   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
35770                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
35771 
35772   // Rebuild the chain around this new shuffle.
35773   while (!Chain.empty()) {
35774     SDValue W = Chain.pop_back_val();
35775 
35776     if (V.getValueType() != W.getOperand(0).getValueType())
35777       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
35778 
35779     switch (W.getOpcode()) {
35780     default:
35781       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
35782 
35783     case X86ISD::UNPCKL:
35784     case X86ISD::UNPCKH:
35785       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
35786       break;
35787 
35788     case X86ISD::PSHUFD:
35789     case X86ISD::PSHUFLW:
35790     case X86ISD::PSHUFHW:
35791       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
35792       break;
35793     }
35794   }
35795   if (V.getValueType() != N.getValueType())
35796     V = DAG.getBitcast(N.getValueType(), V);
35797 
35798   // Return the new chain to replace N.
35799   return V;
35800 }
35801 
35802 // Attempt to commute shufps LHS loads:
35803 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
combineCommutableSHUFP(SDValue N,MVT VT,const SDLoc & DL,SelectionDAG & DAG)35804 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
35805                                       SelectionDAG &DAG) {
35806   // TODO: Add vXf64 support.
35807   if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
35808     return SDValue();
35809 
35810   // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
35811   auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
35812     if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
35813       return SDValue();
35814     SDValue N0 = V.getOperand(0);
35815     SDValue N1 = V.getOperand(1);
35816     unsigned Imm = V.getConstantOperandVal(2);
35817     if (!MayFoldLoad(peekThroughOneUseBitcasts(N0)) ||
35818         MayFoldLoad(peekThroughOneUseBitcasts(N1)))
35819       return SDValue();
35820     Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
35821     return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
35822                        DAG.getTargetConstant(Imm, DL, MVT::i8));
35823   };
35824 
35825   switch (N.getOpcode()) {
35826   case X86ISD::VPERMILPI:
35827     if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
35828       unsigned Imm = N.getConstantOperandVal(1);
35829       return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
35830                          DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
35831     }
35832     break;
35833   case X86ISD::SHUFP: {
35834     SDValue N0 = N.getOperand(0);
35835     SDValue N1 = N.getOperand(1);
35836     unsigned Imm = N.getConstantOperandVal(2);
35837     if (N0 == N1) {
35838       if (SDValue NewSHUFP = commuteSHUFP(N, N0))
35839         return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
35840                            DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
35841     } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
35842       return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
35843                          DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
35844     } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
35845       return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
35846                          DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
35847     }
35848     break;
35849   }
35850   }
35851 
35852   return SDValue();
35853 }
35854 
35855 /// Try to combine x86 target specific shuffles.
combineTargetShuffle(SDValue N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)35856 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
35857                                     TargetLowering::DAGCombinerInfo &DCI,
35858                                     const X86Subtarget &Subtarget) {
35859   SDLoc DL(N);
35860   MVT VT = N.getSimpleValueType();
35861   SmallVector<int, 4> Mask;
35862   unsigned Opcode = N.getOpcode();
35863 
35864   bool IsUnary;
35865   SmallVector<int, 64> TargetMask;
35866   SmallVector<SDValue, 2> TargetOps;
35867   if (isTargetShuffle(Opcode))
35868     getTargetShuffleMask(N.getNode(), VT, true, TargetOps, TargetMask, IsUnary);
35869 
35870   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
35871   // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
35872   // represents the LHS/RHS inputs for the lower/upper halves.
35873   SmallVector<int, 16> TargetMask128;
35874   if (!TargetMask.empty() && 0 < TargetOps.size() && TargetOps.size() <= 2 &&
35875       isRepeatedTargetShuffleMask(128, VT, TargetMask, TargetMask128)) {
35876     SmallVector<int, 16> WidenedMask128 = TargetMask128;
35877     while (WidenedMask128.size() > 2) {
35878       SmallVector<int, 16> WidenedMask;
35879       if (!canWidenShuffleElements(WidenedMask128, WidenedMask))
35880         break;
35881       WidenedMask128 = std::move(WidenedMask);
35882     }
35883     if (WidenedMask128.size() == 2) {
35884       assert(isUndefOrZeroOrInRange(WidenedMask128, 0, 4) && "Illegal shuffle");
35885       SDValue BC0 = peekThroughBitcasts(TargetOps.front());
35886       SDValue BC1 = peekThroughBitcasts(TargetOps.back());
35887       EVT VT0 = BC0.getValueType();
35888       EVT VT1 = BC1.getValueType();
35889       unsigned Opcode0 = BC0.getOpcode();
35890       unsigned Opcode1 = BC1.getOpcode();
35891       bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
35892                       Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
35893       if (Opcode0 == Opcode1 && VT0 == VT1 &&
35894           (isHoriz || Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS)) {
35895         bool SingleOp = (TargetOps.size() == 1);
35896         if (!isHoriz || shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
35897           SDValue Lo = isInRange(WidenedMask128[0], 0, 2) ? BC0 : BC1;
35898           SDValue Hi = isInRange(WidenedMask128[1], 0, 2) ? BC0 : BC1;
35899           Lo = Lo.getOperand(WidenedMask128[0] & 1);
35900           Hi = Hi.getOperand(WidenedMask128[1] & 1);
35901           if (SingleOp) {
35902             MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
35903             SDValue Undef = DAG.getUNDEF(SrcVT);
35904             SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
35905             Lo = (WidenedMask128[0] == SM_SentinelZero ? Zero : Lo);
35906             Hi = (WidenedMask128[1] == SM_SentinelZero ? Zero : Hi);
35907             Lo = (WidenedMask128[0] == SM_SentinelUndef ? Undef : Lo);
35908             Hi = (WidenedMask128[1] == SM_SentinelUndef ? Undef : Hi);
35909           }
35910           SDValue Horiz = DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
35911           return DAG.getBitcast(VT, Horiz);
35912         }
35913       }
35914     }
35915   }
35916 
35917   if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
35918     return R;
35919 
35920   // Canonicalize UNARYSHUFFLE(XOR(X,-1) -> XOR(UNARYSHUFFLE(X),-1) to
35921   // help expose the 'NOT' pattern further up the DAG.
35922   // TODO: This might be beneficial for any binop with a 'splattable' operand.
35923   switch (Opcode) {
35924   case X86ISD::MOVDDUP:
35925   case X86ISD::PSHUFD: {
35926     SDValue Src = N.getOperand(0);
35927     if (Src.hasOneUse() && Src.getValueType() == VT) {
35928       if (SDValue Not = IsNOT(Src, DAG, /*OneUse*/ true)) {
35929         Not = DAG.getBitcast(VT, Not);
35930         Not = Opcode == X86ISD::MOVDDUP
35931                   ? DAG.getNode(Opcode, DL, VT, Not)
35932                   : DAG.getNode(Opcode, DL, VT, Not, N.getOperand(1));
35933         EVT IntVT = Not.getValueType().changeTypeToInteger();
35934         SDValue AllOnes = DAG.getConstant(-1, DL, IntVT);
35935         Not = DAG.getBitcast(IntVT, Not);
35936         Not = DAG.getNode(ISD::XOR, DL, IntVT, Not, AllOnes);
35937         return DAG.getBitcast(VT, Not);
35938       }
35939     }
35940     break;
35941   }
35942   }
35943 
35944   // Handle specific target shuffles.
35945   switch (Opcode) {
35946   case X86ISD::MOVDDUP: {
35947     SDValue Src = N.getOperand(0);
35948     // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
35949     if (VT == MVT::v2f64 && Src.hasOneUse() &&
35950         ISD::isNormalLoad(Src.getNode())) {
35951       LoadSDNode *LN = cast<LoadSDNode>(Src);
35952       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
35953         SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
35954         DCI.CombineTo(N.getNode(), Movddup);
35955         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
35956         DCI.recursivelyDeleteUnusedNodes(LN);
35957         return N; // Return N so it doesn't get rechecked!
35958       }
35959     }
35960 
35961     return SDValue();
35962   }
35963   case X86ISD::VBROADCAST: {
35964     SDValue Src = N.getOperand(0);
35965     SDValue BC = peekThroughBitcasts(Src);
35966     EVT SrcVT = Src.getValueType();
35967     EVT BCVT = BC.getValueType();
35968 
35969     // If broadcasting from another shuffle, attempt to simplify it.
35970     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
35971     if (isTargetShuffle(BC.getOpcode()) &&
35972         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
35973       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
35974       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
35975                                         SM_SentinelUndef);
35976       for (unsigned i = 0; i != Scale; ++i)
35977         DemandedMask[i] = i;
35978       if (SDValue Res = combineX86ShufflesRecursively(
35979               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
35980               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
35981         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
35982                            DAG.getBitcast(SrcVT, Res));
35983     }
35984 
35985     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
35986     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
35987     if (Src.getOpcode() == ISD::BITCAST &&
35988         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
35989         DAG.getTargetLoweringInfo().isTypeLegal(BCVT)) {
35990       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
35991                                    VT.getVectorNumElements());
35992       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
35993     }
35994 
35995     // Reduce broadcast source vector to lowest 128-bits.
35996     if (SrcVT.getSizeInBits() > 128)
35997       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
35998                          extract128BitVector(Src, 0, DAG, DL));
35999 
36000     // broadcast(scalar_to_vector(x)) -> broadcast(x).
36001     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
36002       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
36003 
36004     // Share broadcast with the longest vector and extract low subvector (free).
36005     for (SDNode *User : Src->uses())
36006       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
36007           User->getValueSizeInBits(0) > VT.getSizeInBits()) {
36008         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
36009                                 VT.getSizeInBits());
36010       }
36011 
36012     // vbroadcast(scalarload X) -> vbroadcast_load X
36013     // For float loads, extract other uses of the scalar from the broadcast.
36014     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
36015         ISD::isNormalLoad(Src.getNode())) {
36016       LoadSDNode *LN = cast<LoadSDNode>(Src);
36017       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36018       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
36019       SDValue BcastLd =
36020           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
36021                                   LN->getMemoryVT(), LN->getMemOperand());
36022       // If the load value is used only by N, replace it via CombineTo N.
36023       bool NoReplaceExtract = Src.hasOneUse();
36024       DCI.CombineTo(N.getNode(), BcastLd);
36025       if (NoReplaceExtract) {
36026         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
36027         DCI.recursivelyDeleteUnusedNodes(LN);
36028       } else {
36029         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
36030                                   DAG.getIntPtrConstant(0, DL));
36031         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
36032       }
36033       return N; // Return N so it doesn't get rechecked!
36034     }
36035 
36036     // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
36037     // i16. So shrink it ourselves if we can make a broadcast_load.
36038     if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
36039         Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
36040       assert(Subtarget.hasAVX2() && "Expected AVX2");
36041       SDValue TruncIn = Src.getOperand(0);
36042 
36043       // If this is a truncate of a non extending load we can just narrow it to
36044       // use a broadcast_load.
36045       if (ISD::isNormalLoad(TruncIn.getNode())) {
36046         LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
36047         // Unless its volatile or atomic.
36048         if (LN->isSimple()) {
36049           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36050           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
36051           SDValue BcastLd = DAG.getMemIntrinsicNode(
36052               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
36053               LN->getPointerInfo(), LN->getOriginalAlign(),
36054               LN->getMemOperand()->getFlags());
36055           DCI.CombineTo(N.getNode(), BcastLd);
36056           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
36057           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
36058           return N; // Return N so it doesn't get rechecked!
36059         }
36060       }
36061 
36062       // If this is a truncate of an i16 extload, we can directly replace it.
36063       if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
36064           ISD::isEXTLoad(Src.getOperand(0).getNode())) {
36065         LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
36066         if (LN->getMemoryVT().getSizeInBits() == 16) {
36067           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36068           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
36069           SDValue BcastLd =
36070               DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
36071                                       LN->getMemoryVT(), LN->getMemOperand());
36072           DCI.CombineTo(N.getNode(), BcastLd);
36073           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
36074           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
36075           return N; // Return N so it doesn't get rechecked!
36076         }
36077       }
36078 
36079       // If this is a truncate of load that has been shifted right, we can
36080       // offset the pointer and use a narrower load.
36081       if (TruncIn.getOpcode() == ISD::SRL &&
36082           TruncIn.getOperand(0).hasOneUse() &&
36083           isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
36084           ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
36085         LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
36086         unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
36087         // Make sure the shift amount and the load size are divisible by 16.
36088         // Don't do this if the load is volatile or atomic.
36089         if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
36090             LN->isSimple()) {
36091           unsigned Offset = ShiftAmt / 8;
36092           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36093           SDValue Ptr = DAG.getMemBasePlusOffset(LN->getBasePtr(), Offset, DL);
36094           SDValue Ops[] = { LN->getChain(), Ptr };
36095           SDValue BcastLd = DAG.getMemIntrinsicNode(
36096               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
36097               LN->getPointerInfo().getWithOffset(Offset),
36098               LN->getOriginalAlign(),
36099               LN->getMemOperand()->getFlags());
36100           DCI.CombineTo(N.getNode(), BcastLd);
36101           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
36102           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
36103           return N; // Return N so it doesn't get rechecked!
36104         }
36105       }
36106     }
36107 
36108     // vbroadcast(vzload X) -> vbroadcast_load X
36109     if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
36110       MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
36111       if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
36112         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36113         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
36114         SDValue BcastLd =
36115             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
36116                                     LN->getMemoryVT(), LN->getMemOperand());
36117         DCI.CombineTo(N.getNode(), BcastLd);
36118         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
36119         DCI.recursivelyDeleteUnusedNodes(LN);
36120         return N; // Return N so it doesn't get rechecked!
36121       }
36122     }
36123 
36124     // vbroadcast(vector load X) -> vbroadcast_load
36125     if (SrcVT == MVT::v2f64 && Src.hasOneUse() &&
36126         ISD::isNormalLoad(Src.getNode())) {
36127       LoadSDNode *LN = cast<LoadSDNode>(Src);
36128       // Unless the load is volatile or atomic.
36129       if (LN->isSimple()) {
36130         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36131         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
36132         SDValue BcastLd = DAG.getMemIntrinsicNode(
36133             X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
36134             LN->getPointerInfo(), LN->getOriginalAlign(),
36135             LN->getMemOperand()->getFlags());
36136         DCI.CombineTo(N.getNode(), BcastLd);
36137         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
36138         DCI.recursivelyDeleteUnusedNodes(LN);
36139         return N; // Return N so it doesn't get rechecked!
36140       }
36141     }
36142 
36143     return SDValue();
36144   }
36145   case X86ISD::VZEXT_MOVL: {
36146     SDValue N0 = N.getOperand(0);
36147 
36148     // If this a vzmovl of a full vector load, replace it with a vzload, unless
36149     // the load is volatile.
36150     if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
36151       auto *LN = cast<LoadSDNode>(N0);
36152       if (SDValue VZLoad =
36153               narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
36154         DCI.CombineTo(N.getNode(), VZLoad);
36155         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
36156         DCI.recursivelyDeleteUnusedNodes(LN);
36157         return N;
36158       }
36159     }
36160 
36161     // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
36162     // and can just use a VZEXT_LOAD.
36163     // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
36164     if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
36165       auto *LN = cast<MemSDNode>(N0);
36166       if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
36167         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
36168         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
36169         SDValue VZLoad =
36170             DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
36171                                     LN->getMemoryVT(), LN->getMemOperand());
36172         DCI.CombineTo(N.getNode(), VZLoad);
36173         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
36174         DCI.recursivelyDeleteUnusedNodes(LN);
36175         return N;
36176       }
36177     }
36178 
36179     // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
36180     // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
36181     // if the upper bits of the i64 are zero.
36182     if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
36183         N0.getOperand(0).hasOneUse() &&
36184         N0.getOperand(0).getValueType() == MVT::i64) {
36185       SDValue In = N0.getOperand(0);
36186       APInt Mask = APInt::getHighBitsSet(64, 32);
36187       if (DAG.MaskedValueIsZero(In, Mask)) {
36188         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
36189         MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
36190         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
36191         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
36192         return DAG.getBitcast(VT, Movl);
36193       }
36194     }
36195 
36196     // Load a scalar integer constant directly to XMM instead of transferring an
36197     // immediate value from GPR.
36198     // vzext_movl (scalar_to_vector C) --> load [C,0...]
36199     if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
36200       if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
36201         // Create a vector constant - scalar constant followed by zeros.
36202         EVT ScalarVT = N0.getOperand(0).getValueType();
36203         Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
36204         unsigned NumElts = VT.getVectorNumElements();
36205         Constant *Zero = ConstantInt::getNullValue(ScalarTy);
36206         SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
36207         ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
36208 
36209         // Load the vector constant from constant pool.
36210         MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
36211         SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
36212         MachinePointerInfo MPI =
36213             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
36214         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
36215         return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
36216                            MachineMemOperand::MOLoad);
36217       }
36218     }
36219 
36220     return SDValue();
36221   }
36222   case X86ISD::BLENDI: {
36223     SDValue N0 = N.getOperand(0);
36224     SDValue N1 = N.getOperand(1);
36225 
36226     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
36227     // TODO: Handle MVT::v16i16 repeated blend mask.
36228     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
36229         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
36230       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
36231       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
36232           SrcVT.getScalarSizeInBits() >= 32) {
36233         unsigned BlendMask = N.getConstantOperandVal(2);
36234         unsigned Size = VT.getVectorNumElements();
36235         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
36236         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
36237         return DAG.getBitcast(
36238             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
36239                             N1.getOperand(0),
36240                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
36241       }
36242     }
36243     return SDValue();
36244   }
36245   case X86ISD::VPERMI: {
36246     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
36247     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
36248     SDValue N0 = N.getOperand(0);
36249     SDValue N1 = N.getOperand(1);
36250     unsigned EltSizeInBits = VT.getScalarSizeInBits();
36251     if (N0.getOpcode() == ISD::BITCAST &&
36252         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
36253       SDValue Src = N0.getOperand(0);
36254       EVT SrcVT = Src.getValueType();
36255       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
36256       return DAG.getBitcast(VT, Res);
36257     }
36258     return SDValue();
36259   }
36260   case X86ISD::VPERM2X128: {
36261     // If both 128-bit values were inserted into high halves of 256-bit values,
36262     // the shuffle can be reduced to a concatenation of subvectors:
36263     // vperm2x128 (ins ?, X, C1), (ins ?, Y, C2), 0x31 --> concat X, Y
36264     // Note: We are only looking for the exact high/high shuffle mask because we
36265     //       expect to fold other similar patterns before creating this opcode.
36266     SDValue Ins0 = peekThroughBitcasts(N.getOperand(0));
36267     SDValue Ins1 = peekThroughBitcasts(N.getOperand(1));
36268     unsigned Imm = N.getConstantOperandVal(2);
36269     if (!(Imm == 0x31 &&
36270           Ins0.getOpcode() == ISD::INSERT_SUBVECTOR &&
36271           Ins1.getOpcode() == ISD::INSERT_SUBVECTOR &&
36272           Ins0.getValueType() == Ins1.getValueType()))
36273       return SDValue();
36274 
36275     SDValue X = Ins0.getOperand(1);
36276     SDValue Y = Ins1.getOperand(1);
36277     unsigned C1 = Ins0.getConstantOperandVal(2);
36278     unsigned C2 = Ins1.getConstantOperandVal(2);
36279     MVT SrcVT = X.getSimpleValueType();
36280     unsigned SrcElts = SrcVT.getVectorNumElements();
36281     if (SrcVT != Y.getSimpleValueType() || SrcVT.getSizeInBits() != 128 ||
36282         C1 != SrcElts || C2 != SrcElts)
36283       return SDValue();
36284 
36285     return DAG.getBitcast(VT, DAG.getNode(ISD::CONCAT_VECTORS, DL,
36286                                           Ins1.getValueType(), X, Y));
36287   }
36288   case X86ISD::PSHUFD:
36289   case X86ISD::PSHUFLW:
36290   case X86ISD::PSHUFHW:
36291     Mask = getPSHUFShuffleMask(N);
36292     assert(Mask.size() == 4);
36293     break;
36294   case X86ISD::MOVSD:
36295   case X86ISD::MOVSS: {
36296     SDValue N0 = N.getOperand(0);
36297     SDValue N1 = N.getOperand(1);
36298 
36299     // Canonicalize scalar FPOps:
36300     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
36301     // If commutable, allow OP(N1[0], N0[0]).
36302     unsigned Opcode1 = N1.getOpcode();
36303     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
36304         Opcode1 == ISD::FDIV) {
36305       SDValue N10 = N1.getOperand(0);
36306       SDValue N11 = N1.getOperand(1);
36307       if (N10 == N0 ||
36308           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
36309         if (N10 != N0)
36310           std::swap(N10, N11);
36311         MVT SVT = VT.getVectorElementType();
36312         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
36313         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
36314         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
36315         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
36316         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
36317         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
36318       }
36319     }
36320 
36321     return SDValue();
36322   }
36323   case X86ISD::INSERTPS: {
36324     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
36325     SDValue Op0 = N.getOperand(0);
36326     SDValue Op1 = N.getOperand(1);
36327     unsigned InsertPSMask = N.getConstantOperandVal(2);
36328     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
36329     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
36330     unsigned ZeroMask = InsertPSMask & 0xF;
36331 
36332     // If we zero out all elements from Op0 then we don't need to reference it.
36333     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
36334       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
36335                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
36336 
36337     // If we zero out the element from Op1 then we don't need to reference it.
36338     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
36339       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
36340                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
36341 
36342     // Attempt to merge insertps Op1 with an inner target shuffle node.
36343     SmallVector<int, 8> TargetMask1;
36344     SmallVector<SDValue, 2> Ops1;
36345     APInt KnownUndef1, KnownZero1;
36346     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
36347                                      KnownZero1)) {
36348       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
36349         // Zero/UNDEF insertion - zero out element and remove dependency.
36350         InsertPSMask |= (1u << DstIdx);
36351         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
36352                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
36353       }
36354       // Update insertps mask srcidx and reference the source input directly.
36355       int M = TargetMask1[SrcIdx];
36356       assert(0 <= M && M < 8 && "Shuffle index out of range");
36357       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
36358       Op1 = Ops1[M < 4 ? 0 : 1];
36359       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
36360                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
36361     }
36362 
36363     // Attempt to merge insertps Op0 with an inner target shuffle node.
36364     SmallVector<int, 8> TargetMask0;
36365     SmallVector<SDValue, 2> Ops0;
36366     APInt KnownUndef0, KnownZero0;
36367     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
36368                                      KnownZero0)) {
36369       bool Updated = false;
36370       bool UseInput00 = false;
36371       bool UseInput01 = false;
36372       for (int i = 0; i != 4; ++i) {
36373         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
36374           // No change if element is already zero or the inserted element.
36375           continue;
36376         } else if (KnownUndef0[i] || KnownZero0[i]) {
36377           // If the target mask is undef/zero then we must zero the element.
36378           InsertPSMask |= (1u << i);
36379           Updated = true;
36380           continue;
36381         }
36382 
36383         // The input vector element must be inline.
36384         int M = TargetMask0[i];
36385         if (M != i && M != (i + 4))
36386           return SDValue();
36387 
36388         // Determine which inputs of the target shuffle we're using.
36389         UseInput00 |= (0 <= M && M < 4);
36390         UseInput01 |= (4 <= M);
36391       }
36392 
36393       // If we're not using both inputs of the target shuffle then use the
36394       // referenced input directly.
36395       if (UseInput00 && !UseInput01) {
36396         Updated = true;
36397         Op0 = Ops0[0];
36398       } else if (!UseInput00 && UseInput01) {
36399         Updated = true;
36400         Op0 = Ops0[1];
36401       }
36402 
36403       if (Updated)
36404         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
36405                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
36406     }
36407 
36408     // If we're inserting an element from a vbroadcast load, fold the
36409     // load into the X86insertps instruction. We need to convert the scalar
36410     // load to a vector and clear the source lane of the INSERTPS control.
36411     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
36412       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
36413       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
36414         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
36415                                    MemIntr->getBasePtr(),
36416                                    MemIntr->getMemOperand());
36417         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
36418                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
36419                                        Load),
36420                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
36421         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
36422         return Insert;
36423       }
36424     }
36425 
36426     return SDValue();
36427   }
36428   default:
36429     return SDValue();
36430   }
36431 
36432   // Nuke no-op shuffles that show up after combining.
36433   if (isNoopShuffleMask(Mask))
36434     return N.getOperand(0);
36435 
36436   // Look for simplifications involving one or two shuffle instructions.
36437   SDValue V = N.getOperand(0);
36438   switch (N.getOpcode()) {
36439   default:
36440     break;
36441   case X86ISD::PSHUFLW:
36442   case X86ISD::PSHUFHW:
36443     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
36444 
36445     // See if this reduces to a PSHUFD which is no more expensive and can
36446     // combine with more operations. Note that it has to at least flip the
36447     // dwords as otherwise it would have been removed as a no-op.
36448     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
36449       int DMask[] = {0, 1, 2, 3};
36450       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
36451       DMask[DOffset + 0] = DOffset + 1;
36452       DMask[DOffset + 1] = DOffset + 0;
36453       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
36454       V = DAG.getBitcast(DVT, V);
36455       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
36456                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
36457       return DAG.getBitcast(VT, V);
36458     }
36459 
36460     // Look for shuffle patterns which can be implemented as a single unpack.
36461     // FIXME: This doesn't handle the location of the PSHUFD generically, and
36462     // only works when we have a PSHUFD followed by two half-shuffles.
36463     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
36464         (V.getOpcode() == X86ISD::PSHUFLW ||
36465          V.getOpcode() == X86ISD::PSHUFHW) &&
36466         V.getOpcode() != N.getOpcode() &&
36467         V.hasOneUse() && V.getOperand(0).hasOneUse()) {
36468       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
36469       if (D.getOpcode() == X86ISD::PSHUFD) {
36470         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
36471         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
36472         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
36473         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
36474         int WordMask[8];
36475         for (int i = 0; i < 4; ++i) {
36476           WordMask[i + NOffset] = Mask[i] + NOffset;
36477           WordMask[i + VOffset] = VMask[i] + VOffset;
36478         }
36479         // Map the word mask through the DWord mask.
36480         int MappedMask[8];
36481         for (int i = 0; i < 8; ++i)
36482           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
36483         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
36484             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
36485           // We can replace all three shuffles with an unpack.
36486           V = DAG.getBitcast(VT, D.getOperand(0));
36487           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
36488                                                 : X86ISD::UNPCKH,
36489                              DL, VT, V, V);
36490         }
36491       }
36492     }
36493 
36494     break;
36495 
36496   case X86ISD::PSHUFD:
36497     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
36498       return NewN;
36499 
36500     break;
36501   }
36502 
36503   return SDValue();
36504 }
36505 
36506 /// Checks if the shuffle mask takes subsequent elements
36507 /// alternately from two vectors.
36508 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
isAddSubOrSubAddMask(ArrayRef<int> Mask,bool & Op0Even)36509 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
36510 
36511   int ParitySrc[2] = {-1, -1};
36512   unsigned Size = Mask.size();
36513   for (unsigned i = 0; i != Size; ++i) {
36514     int M = Mask[i];
36515     if (M < 0)
36516       continue;
36517 
36518     // Make sure we are using the matching element from the input.
36519     if ((M % Size) != i)
36520       return false;
36521 
36522     // Make sure we use the same input for all elements of the same parity.
36523     int Src = M / Size;
36524     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
36525       return false;
36526     ParitySrc[i % 2] = Src;
36527   }
36528 
36529   // Make sure each input is used.
36530   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
36531     return false;
36532 
36533   Op0Even = ParitySrc[0] == 0;
36534   return true;
36535 }
36536 
36537 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
36538 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
36539 /// are written to the parameters \p Opnd0 and \p Opnd1.
36540 ///
36541 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
36542 /// so it is easier to generically match. We also insert dummy vector shuffle
36543 /// nodes for the operands which explicitly discard the lanes which are unused
36544 /// by this operation to try to flow through the rest of the combiner
36545 /// the fact that they're unused.
isAddSubOrSubAdd(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG,SDValue & Opnd0,SDValue & Opnd1,bool & IsSubAdd)36546 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
36547                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
36548                              bool &IsSubAdd) {
36549 
36550   EVT VT = N->getValueType(0);
36551   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36552   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
36553       !VT.getSimpleVT().isFloatingPoint())
36554     return false;
36555 
36556   // We only handle target-independent shuffles.
36557   // FIXME: It would be easy and harmless to use the target shuffle mask
36558   // extraction tool to support more.
36559   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
36560     return false;
36561 
36562   SDValue V1 = N->getOperand(0);
36563   SDValue V2 = N->getOperand(1);
36564 
36565   // Make sure we have an FADD and an FSUB.
36566   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
36567       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
36568       V1.getOpcode() == V2.getOpcode())
36569     return false;
36570 
36571   // If there are other uses of these operations we can't fold them.
36572   if (!V1->hasOneUse() || !V2->hasOneUse())
36573     return false;
36574 
36575   // Ensure that both operations have the same operands. Note that we can
36576   // commute the FADD operands.
36577   SDValue LHS, RHS;
36578   if (V1.getOpcode() == ISD::FSUB) {
36579     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
36580     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
36581         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
36582       return false;
36583   } else {
36584     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
36585     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
36586     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
36587         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
36588       return false;
36589   }
36590 
36591   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
36592   bool Op0Even;
36593   if (!isAddSubOrSubAddMask(Mask, Op0Even))
36594     return false;
36595 
36596   // It's a subadd if the vector in the even parity is an FADD.
36597   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
36598                      : V2->getOpcode() == ISD::FADD;
36599 
36600   Opnd0 = LHS;
36601   Opnd1 = RHS;
36602   return true;
36603 }
36604 
36605 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
combineShuffleToFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)36606 static SDValue combineShuffleToFMAddSub(SDNode *N,
36607                                         const X86Subtarget &Subtarget,
36608                                         SelectionDAG &DAG) {
36609   // We only handle target-independent shuffles.
36610   // FIXME: It would be easy and harmless to use the target shuffle mask
36611   // extraction tool to support more.
36612   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
36613     return SDValue();
36614 
36615   MVT VT = N->getSimpleValueType(0);
36616   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36617   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
36618     return SDValue();
36619 
36620   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
36621   SDValue Op0 = N->getOperand(0);
36622   SDValue Op1 = N->getOperand(1);
36623   SDValue FMAdd = Op0, FMSub = Op1;
36624   if (FMSub.getOpcode() != X86ISD::FMSUB)
36625     std::swap(FMAdd, FMSub);
36626 
36627   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
36628       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
36629       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
36630       FMAdd.getOperand(2) != FMSub.getOperand(2))
36631     return SDValue();
36632 
36633   // Check for correct shuffle mask.
36634   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
36635   bool Op0Even;
36636   if (!isAddSubOrSubAddMask(Mask, Op0Even))
36637     return SDValue();
36638 
36639   // FMAddSub takes zeroth operand from FMSub node.
36640   SDLoc DL(N);
36641   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
36642   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
36643   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
36644                      FMAdd.getOperand(2));
36645 }
36646 
36647 /// Try to combine a shuffle into a target-specific add-sub or
36648 /// mul-add-sub node.
combineShuffleToAddSubOrFMAddSub(SDNode * N,const X86Subtarget & Subtarget,SelectionDAG & DAG)36649 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
36650                                                 const X86Subtarget &Subtarget,
36651                                                 SelectionDAG &DAG) {
36652   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
36653     return V;
36654 
36655   SDValue Opnd0, Opnd1;
36656   bool IsSubAdd;
36657   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
36658     return SDValue();
36659 
36660   MVT VT = N->getSimpleValueType(0);
36661   SDLoc DL(N);
36662 
36663   // Try to generate X86ISD::FMADDSUB node here.
36664   SDValue Opnd2;
36665   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
36666     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
36667     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
36668   }
36669 
36670   if (IsSubAdd)
36671     return SDValue();
36672 
36673   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
36674   // the ADDSUB idiom has been successfully recognized. There are no known
36675   // X86 targets with 512-bit ADDSUB instructions!
36676   if (VT.is512BitVector())
36677     return SDValue();
36678 
36679   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
36680 }
36681 
36682 // We are looking for a shuffle where both sources are concatenated with undef
36683 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
36684 // if we can express this as a single-source shuffle, that's preferable.
combineShuffleOfConcatUndef(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)36685 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
36686                                            const X86Subtarget &Subtarget) {
36687   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
36688     return SDValue();
36689 
36690   EVT VT = N->getValueType(0);
36691 
36692   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
36693   if (!VT.is128BitVector() && !VT.is256BitVector())
36694     return SDValue();
36695 
36696   if (VT.getVectorElementType() != MVT::i32 &&
36697       VT.getVectorElementType() != MVT::i64 &&
36698       VT.getVectorElementType() != MVT::f32 &&
36699       VT.getVectorElementType() != MVT::f64)
36700     return SDValue();
36701 
36702   SDValue N0 = N->getOperand(0);
36703   SDValue N1 = N->getOperand(1);
36704 
36705   // Check that both sources are concats with undef.
36706   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
36707       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
36708       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
36709       !N1.getOperand(1).isUndef())
36710     return SDValue();
36711 
36712   // Construct the new shuffle mask. Elements from the first source retain their
36713   // index, but elements from the second source no longer need to skip an undef.
36714   SmallVector<int, 8> Mask;
36715   int NumElts = VT.getVectorNumElements();
36716 
36717   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
36718   for (int Elt : SVOp->getMask())
36719     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
36720 
36721   SDLoc DL(N);
36722   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
36723                                N1.getOperand(0));
36724   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
36725 }
36726 
36727 /// Eliminate a redundant shuffle of a horizontal math op.
foldShuffleOfHorizOp(SDNode * N,SelectionDAG & DAG)36728 static SDValue foldShuffleOfHorizOp(SDNode *N, SelectionDAG &DAG) {
36729   unsigned Opcode = N->getOpcode();
36730   if (Opcode != X86ISD::MOVDDUP && Opcode != X86ISD::VBROADCAST)
36731     if (Opcode != ISD::VECTOR_SHUFFLE || !N->getOperand(1).isUndef())
36732       return SDValue();
36733 
36734   // For a broadcast, peek through an extract element of index 0 to find the
36735   // horizontal op: broadcast (ext_vec_elt HOp, 0)
36736   EVT VT = N->getValueType(0);
36737   if (Opcode == X86ISD::VBROADCAST) {
36738     SDValue SrcOp = N->getOperand(0);
36739     if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
36740         SrcOp.getValueType() == MVT::f64 &&
36741         SrcOp.getOperand(0).getValueType() == VT &&
36742         isNullConstant(SrcOp.getOperand(1)))
36743       N = SrcOp.getNode();
36744   }
36745 
36746   SDValue HOp = N->getOperand(0);
36747   if (HOp.getOpcode() != X86ISD::HADD && HOp.getOpcode() != X86ISD::FHADD &&
36748       HOp.getOpcode() != X86ISD::HSUB && HOp.getOpcode() != X86ISD::FHSUB)
36749     return SDValue();
36750 
36751   // 128-bit horizontal math instructions are defined to operate on adjacent
36752   // lanes of each operand as:
36753   // v4X32: A[0] + A[1] , A[2] + A[3] , B[0] + B[1] , B[2] + B[3]
36754   // ...similarly for v2f64 and v8i16.
36755   if (!HOp.getOperand(0).isUndef() && !HOp.getOperand(1).isUndef() &&
36756       HOp.getOperand(0) != HOp.getOperand(1))
36757     return SDValue();
36758 
36759   // The shuffle that we are eliminating may have allowed the horizontal op to
36760   // have an undemanded (undefined) operand. Duplicate the other (defined)
36761   // operand to ensure that the results are defined across all lanes without the
36762   // shuffle.
36763   auto updateHOp = [](SDValue HorizOp, SelectionDAG &DAG) {
36764     SDValue X;
36765     if (HorizOp.getOperand(0).isUndef()) {
36766       assert(!HorizOp.getOperand(1).isUndef() && "Not expecting foldable h-op");
36767       X = HorizOp.getOperand(1);
36768     } else if (HorizOp.getOperand(1).isUndef()) {
36769       assert(!HorizOp.getOperand(0).isUndef() && "Not expecting foldable h-op");
36770       X = HorizOp.getOperand(0);
36771     } else {
36772       return HorizOp;
36773     }
36774     return DAG.getNode(HorizOp.getOpcode(), SDLoc(HorizOp),
36775                        HorizOp.getValueType(), X, X);
36776   };
36777 
36778   // When the operands of a horizontal math op are identical, the low half of
36779   // the result is the same as the high half. If a target shuffle is also
36780   // replicating low and high halves (and without changing the type/length of
36781   // the vector), we don't need the shuffle.
36782   if (Opcode == X86ISD::MOVDDUP || Opcode == X86ISD::VBROADCAST) {
36783     if (HOp.getScalarValueSizeInBits() == 64 && HOp.getValueType() == VT) {
36784       // movddup (hadd X, X) --> hadd X, X
36785       // broadcast (extract_vec_elt (hadd X, X), 0) --> hadd X, X
36786       assert((HOp.getValueType() == MVT::v2f64 ||
36787               HOp.getValueType() == MVT::v4f64) && "Unexpected type for h-op");
36788       return updateHOp(HOp, DAG);
36789     }
36790     return SDValue();
36791   }
36792 
36793   // shuffle (hadd X, X), undef, [low half...high half] --> hadd X, X
36794   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
36795   // TODO: Other mask possibilities like {1,1} and {1,0} could be added here,
36796   // but this should be tied to whatever horizontal op matching and shuffle
36797   // canonicalization are producing.
36798   if (HOp.getValueSizeInBits() == 128 &&
36799       (isTargetShuffleEquivalent(Mask, {0, 0}) ||
36800        isTargetShuffleEquivalent(Mask, {0, 1, 0, 1}) ||
36801        isTargetShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3})))
36802     return updateHOp(HOp, DAG);
36803 
36804   if (HOp.getValueSizeInBits() == 256 &&
36805       (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2}) ||
36806        isTargetShuffleEquivalent(Mask, {0, 1, 0, 1, 4, 5, 4, 5}) ||
36807        isTargetShuffleEquivalent(
36808            Mask, {0, 1, 2, 3, 0, 1, 2, 3, 8, 9, 10, 11, 8, 9, 10, 11})))
36809     return updateHOp(HOp, DAG);
36810 
36811   return SDValue();
36812 }
36813 
36814 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
36815 /// low half of each source vector and does not set any high half elements in
36816 /// the destination vector, narrow the shuffle to half its original size.
narrowShuffle(ShuffleVectorSDNode * Shuf,SelectionDAG & DAG)36817 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
36818   if (!Shuf->getValueType(0).isSimple())
36819     return SDValue();
36820   MVT VT = Shuf->getSimpleValueType(0);
36821   if (!VT.is256BitVector() && !VT.is512BitVector())
36822     return SDValue();
36823 
36824   // See if we can ignore all of the high elements of the shuffle.
36825   ArrayRef<int> Mask = Shuf->getMask();
36826   if (!isUndefUpperHalf(Mask))
36827     return SDValue();
36828 
36829   // Check if the shuffle mask accesses only the low half of each input vector
36830   // (half-index output is 0 or 2).
36831   int HalfIdx1, HalfIdx2;
36832   SmallVector<int, 8> HalfMask(Mask.size() / 2);
36833   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
36834       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
36835     return SDValue();
36836 
36837   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
36838   // The trick is knowing that all of the insert/extract are actually free
36839   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
36840   // of narrow inputs into a narrow output, and that is always cheaper than
36841   // the wide shuffle that we started with.
36842   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
36843                                Shuf->getOperand(1), HalfMask, HalfIdx1,
36844                                HalfIdx2, false, DAG, /*UseConcat*/true);
36845 }
36846 
combineShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)36847 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
36848                               TargetLowering::DAGCombinerInfo &DCI,
36849                               const X86Subtarget &Subtarget) {
36850   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
36851     if (SDValue V = narrowShuffle(Shuf, DAG))
36852       return V;
36853 
36854   // If we have legalized the vector types, look for blends of FADD and FSUB
36855   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
36856   SDLoc dl(N);
36857   EVT VT = N->getValueType(0);
36858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
36859   if (TLI.isTypeLegal(VT)) {
36860     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
36861       return AddSub;
36862 
36863     if (SDValue HAddSub = foldShuffleOfHorizOp(N, DAG))
36864       return HAddSub;
36865   }
36866 
36867   // Attempt to combine into a vector load/broadcast.
36868   if (SDValue LD = combineToConsecutiveLoads(VT, SDValue(N, 0), dl, DAG,
36869                                              Subtarget, true))
36870     return LD;
36871 
36872   // For AVX2, we sometimes want to combine
36873   // (vector_shuffle <mask> (concat_vectors t1, undef)
36874   //                        (concat_vectors t2, undef))
36875   // Into:
36876   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
36877   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
36878   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
36879     return ShufConcat;
36880 
36881   if (isTargetShuffle(N->getOpcode())) {
36882     SDValue Op(N, 0);
36883     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
36884       return Shuffle;
36885 
36886     // Try recursively combining arbitrary sequences of x86 shuffle
36887     // instructions into higher-order shuffles. We do this after combining
36888     // specific PSHUF instruction sequences into their minimal form so that we
36889     // can evaluate how many specialized shuffle instructions are involved in
36890     // a particular chain.
36891     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
36892       return Res;
36893 
36894     // Simplify source operands based on shuffle mask.
36895     // TODO - merge this into combineX86ShufflesRecursively.
36896     APInt KnownUndef, KnownZero;
36897     APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
36898     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, DCI))
36899       return SDValue(N, 0);
36900   }
36901 
36902   // Pull subvector inserts into undef through VZEXT_MOVL by making it an
36903   // insert into a zero vector. This helps get VZEXT_MOVL closer to
36904   // scalar_to_vectors where 256/512 are canonicalized to an insert and a
36905   // 128-bit scalar_to_vector. This reduces the number of isel patterns.
36906   if (N->getOpcode() == X86ISD::VZEXT_MOVL && !DCI.isBeforeLegalizeOps() &&
36907       N->getOperand(0).hasOneUse()) {
36908     SDValue V = peekThroughOneUseBitcasts(N->getOperand(0));
36909 
36910     if (V.getOpcode() == ISD::INSERT_SUBVECTOR &&
36911         V.getOperand(0).isUndef() && isNullConstant(V.getOperand(2))) {
36912       SDValue In = V.getOperand(1);
36913       MVT SubVT =
36914           MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
36915                            In.getValueSizeInBits() / VT.getScalarSizeInBits());
36916       In = DAG.getBitcast(SubVT, In);
36917       SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, dl, SubVT, In);
36918       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT,
36919                          getZeroVector(VT.getSimpleVT(), Subtarget, DAG, dl),
36920                          Movl, V.getOperand(2));
36921     }
36922   }
36923 
36924   return SDValue();
36925 }
36926 
36927 // Simplify variable target shuffle masks based on the demanded elements.
36928 // TODO: Handle DemandedBits in mask indices as well?
SimplifyDemandedVectorEltsForTargetShuffle(SDValue Op,const APInt & DemandedElts,unsigned MaskIndex,TargetLowering::TargetLoweringOpt & TLO,unsigned Depth) const36929 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
36930     SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
36931     TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
36932   // If we're demanding all elements don't bother trying to simplify the mask.
36933   unsigned NumElts = DemandedElts.getBitWidth();
36934   if (DemandedElts.isAllOnesValue())
36935     return false;
36936 
36937   SDValue Mask = Op.getOperand(MaskIndex);
36938   if (!Mask.hasOneUse())
36939     return false;
36940 
36941   // Attempt to generically simplify the variable shuffle mask.
36942   APInt MaskUndef, MaskZero;
36943   if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
36944                                  Depth + 1))
36945     return true;
36946 
36947   // Attempt to extract+simplify a (constant pool load) shuffle mask.
36948   // TODO: Support other types from getTargetShuffleMaskIndices?
36949   SDValue BC = peekThroughOneUseBitcasts(Mask);
36950   EVT BCVT = BC.getValueType();
36951   auto *Load = dyn_cast<LoadSDNode>(BC);
36952   if (!Load)
36953     return false;
36954 
36955   const Constant *C = getTargetConstantFromNode(Load);
36956   if (!C)
36957     return false;
36958 
36959   Type *CTy = C->getType();
36960   if (!CTy->isVectorTy() ||
36961       CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
36962     return false;
36963 
36964   // Handle scaling for i64 elements on 32-bit targets.
36965   unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
36966   if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
36967     return false;
36968   unsigned Scale = NumCstElts / NumElts;
36969 
36970   // Simplify mask if we have an undemanded element that is not undef.
36971   bool Simplified = false;
36972   SmallVector<Constant *, 32> ConstVecOps;
36973   for (unsigned i = 0; i != NumCstElts; ++i) {
36974     Constant *Elt = C->getAggregateElement(i);
36975     if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
36976       ConstVecOps.push_back(UndefValue::get(Elt->getType()));
36977       Simplified = true;
36978       continue;
36979     }
36980     ConstVecOps.push_back(Elt);
36981   }
36982   if (!Simplified)
36983     return false;
36984 
36985   // Generate new constant pool entry + legalize immediately for the load.
36986   SDLoc DL(Op);
36987   SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
36988   SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
36989   SDValue NewMask = TLO.DAG.getLoad(
36990       BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
36991       MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
36992       Load->getAlign());
36993   return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
36994 }
36995 
SimplifyDemandedVectorEltsForTargetNode(SDValue Op,const APInt & DemandedElts,APInt & KnownUndef,APInt & KnownZero,TargetLoweringOpt & TLO,unsigned Depth) const36996 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
36997     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
36998     TargetLoweringOpt &TLO, unsigned Depth) const {
36999   int NumElts = DemandedElts.getBitWidth();
37000   unsigned Opc = Op.getOpcode();
37001   EVT VT = Op.getValueType();
37002 
37003   // Handle special case opcodes.
37004   switch (Opc) {
37005   case X86ISD::PMULDQ:
37006   case X86ISD::PMULUDQ: {
37007     APInt LHSUndef, LHSZero;
37008     APInt RHSUndef, RHSZero;
37009     SDValue LHS = Op.getOperand(0);
37010     SDValue RHS = Op.getOperand(1);
37011     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
37012                                    Depth + 1))
37013       return true;
37014     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
37015                                    Depth + 1))
37016       return true;
37017     // Multiply by zero.
37018     KnownZero = LHSZero | RHSZero;
37019     break;
37020   }
37021   case X86ISD::VSHL:
37022   case X86ISD::VSRL:
37023   case X86ISD::VSRA: {
37024     // We only need the bottom 64-bits of the (128-bit) shift amount.
37025     SDValue Amt = Op.getOperand(1);
37026     MVT AmtVT = Amt.getSimpleValueType();
37027     assert(AmtVT.is128BitVector() && "Unexpected value type");
37028 
37029     // If we reuse the shift amount just for sse shift amounts then we know that
37030     // only the bottom 64-bits are only ever used.
37031     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
37032       unsigned UseOpc = Use->getOpcode();
37033       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
37034               UseOpc == X86ISD::VSRA) &&
37035              Use->getOperand(0) != Amt;
37036     });
37037 
37038     APInt AmtUndef, AmtZero;
37039     unsigned NumAmtElts = AmtVT.getVectorNumElements();
37040     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
37041     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
37042                                    Depth + 1, AssumeSingleUse))
37043       return true;
37044     LLVM_FALLTHROUGH;
37045   }
37046   case X86ISD::VSHLI:
37047   case X86ISD::VSRLI:
37048   case X86ISD::VSRAI: {
37049     SDValue Src = Op.getOperand(0);
37050     APInt SrcUndef;
37051     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
37052                                    Depth + 1))
37053       return true;
37054     // TODO convert SrcUndef to KnownUndef.
37055     break;
37056   }
37057   case X86ISD::KSHIFTL: {
37058     SDValue Src = Op.getOperand(0);
37059     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
37060     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
37061     unsigned ShiftAmt = Amt->getZExtValue();
37062 
37063     if (ShiftAmt == 0)
37064       return TLO.CombineTo(Op, Src);
37065 
37066     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
37067     // single shift.  We can do this if the bottom bits (which are shifted
37068     // out) are never demanded.
37069     if (Src.getOpcode() == X86ISD::KSHIFTR) {
37070       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
37071         unsigned C1 = Src.getConstantOperandVal(1);
37072         unsigned NewOpc = X86ISD::KSHIFTL;
37073         int Diff = ShiftAmt - C1;
37074         if (Diff < 0) {
37075           Diff = -Diff;
37076           NewOpc = X86ISD::KSHIFTR;
37077         }
37078 
37079         SDLoc dl(Op);
37080         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
37081         return TLO.CombineTo(
37082             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
37083       }
37084     }
37085 
37086     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
37087     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
37088                                    Depth + 1))
37089       return true;
37090 
37091     KnownUndef <<= ShiftAmt;
37092     KnownZero <<= ShiftAmt;
37093     KnownZero.setLowBits(ShiftAmt);
37094     break;
37095   }
37096   case X86ISD::KSHIFTR: {
37097     SDValue Src = Op.getOperand(0);
37098     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
37099     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
37100     unsigned ShiftAmt = Amt->getZExtValue();
37101 
37102     if (ShiftAmt == 0)
37103       return TLO.CombineTo(Op, Src);
37104 
37105     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
37106     // single shift.  We can do this if the top bits (which are shifted
37107     // out) are never demanded.
37108     if (Src.getOpcode() == X86ISD::KSHIFTL) {
37109       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
37110         unsigned C1 = Src.getConstantOperandVal(1);
37111         unsigned NewOpc = X86ISD::KSHIFTR;
37112         int Diff = ShiftAmt - C1;
37113         if (Diff < 0) {
37114           Diff = -Diff;
37115           NewOpc = X86ISD::KSHIFTL;
37116         }
37117 
37118         SDLoc dl(Op);
37119         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
37120         return TLO.CombineTo(
37121             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
37122       }
37123     }
37124 
37125     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
37126     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
37127                                    Depth + 1))
37128       return true;
37129 
37130     KnownUndef.lshrInPlace(ShiftAmt);
37131     KnownZero.lshrInPlace(ShiftAmt);
37132     KnownZero.setHighBits(ShiftAmt);
37133     break;
37134   }
37135   case X86ISD::CVTSI2P:
37136   case X86ISD::CVTUI2P: {
37137     SDValue Src = Op.getOperand(0);
37138     MVT SrcVT = Src.getSimpleValueType();
37139     APInt SrcUndef, SrcZero;
37140     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
37141     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
37142                                    Depth + 1))
37143       return true;
37144     break;
37145   }
37146   case X86ISD::PACKSS:
37147   case X86ISD::PACKUS: {
37148     SDValue N0 = Op.getOperand(0);
37149     SDValue N1 = Op.getOperand(1);
37150 
37151     APInt DemandedLHS, DemandedRHS;
37152     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
37153 
37154     APInt SrcUndef, SrcZero;
37155     if (SimplifyDemandedVectorElts(N0, DemandedLHS, SrcUndef, SrcZero, TLO,
37156                                    Depth + 1))
37157       return true;
37158     if (SimplifyDemandedVectorElts(N1, DemandedRHS, SrcUndef, SrcZero, TLO,
37159                                    Depth + 1))
37160       return true;
37161 
37162     // Aggressively peek through ops to get at the demanded elts.
37163     // TODO - we should do this for all target/faux shuffles ops.
37164     if (!DemandedElts.isAllOnesValue()) {
37165       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
37166                                                             TLO.DAG, Depth + 1);
37167       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
37168                                                             TLO.DAG, Depth + 1);
37169       if (NewN0 || NewN1) {
37170         NewN0 = NewN0 ? NewN0 : N0;
37171         NewN1 = NewN1 ? NewN1 : N1;
37172         return TLO.CombineTo(Op,
37173                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
37174       }
37175     }
37176     break;
37177   }
37178   case X86ISD::HADD:
37179   case X86ISD::HSUB:
37180   case X86ISD::FHADD:
37181   case X86ISD::FHSUB: {
37182     APInt DemandedLHS, DemandedRHS;
37183     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
37184 
37185     APInt LHSUndef, LHSZero;
37186     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, LHSUndef,
37187                                    LHSZero, TLO, Depth + 1))
37188       return true;
37189     APInt RHSUndef, RHSZero;
37190     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, RHSUndef,
37191                                    RHSZero, TLO, Depth + 1))
37192       return true;
37193     break;
37194   }
37195   case X86ISD::VTRUNC:
37196   case X86ISD::VTRUNCS:
37197   case X86ISD::VTRUNCUS: {
37198     SDValue Src = Op.getOperand(0);
37199     MVT SrcVT = Src.getSimpleValueType();
37200     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
37201     APInt SrcUndef, SrcZero;
37202     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
37203                                    Depth + 1))
37204       return true;
37205     KnownZero = SrcZero.zextOrTrunc(NumElts);
37206     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
37207     break;
37208   }
37209   case X86ISD::BLENDV: {
37210     APInt SelUndef, SelZero;
37211     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
37212                                    SelZero, TLO, Depth + 1))
37213       return true;
37214 
37215     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
37216     APInt LHSUndef, LHSZero;
37217     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
37218                                    LHSZero, TLO, Depth + 1))
37219       return true;
37220 
37221     APInt RHSUndef, RHSZero;
37222     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
37223                                    RHSZero, TLO, Depth + 1))
37224       return true;
37225 
37226     KnownZero = LHSZero & RHSZero;
37227     KnownUndef = LHSUndef & RHSUndef;
37228     break;
37229   }
37230   case X86ISD::VZEXT_MOVL: {
37231     // If upper demanded elements are already zero then we have nothing to do.
37232     SDValue Src = Op.getOperand(0);
37233     APInt DemandedUpperElts = DemandedElts;
37234     DemandedUpperElts.clearLowBits(1);
37235     if (TLO.DAG.computeKnownBits(Src, DemandedUpperElts, Depth + 1).isZero())
37236       return TLO.CombineTo(Op, Src);
37237     break;
37238   }
37239   case X86ISD::VBROADCAST: {
37240     SDValue Src = Op.getOperand(0);
37241     MVT SrcVT = Src.getSimpleValueType();
37242     if (!SrcVT.isVector())
37243       return false;
37244     // Don't bother broadcasting if we just need the 0'th element.
37245     if (DemandedElts == 1) {
37246       if (Src.getValueType() != VT)
37247         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
37248                              SDLoc(Op));
37249       return TLO.CombineTo(Op, Src);
37250     }
37251     APInt SrcUndef, SrcZero;
37252     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
37253     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
37254                                    Depth + 1))
37255       return true;
37256     // Aggressively peek through src to get at the demanded elt.
37257     // TODO - we should do this for all target/faux shuffles ops.
37258     if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
37259             Src, SrcElts, TLO.DAG, Depth + 1))
37260       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
37261     break;
37262   }
37263   case X86ISD::VPERMV:
37264     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
37265                                                    Depth))
37266       return true;
37267     break;
37268   case X86ISD::PSHUFB:
37269   case X86ISD::VPERMV3:
37270   case X86ISD::VPERMILPV:
37271     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
37272                                                    Depth))
37273       return true;
37274     break;
37275   case X86ISD::VPPERM:
37276   case X86ISD::VPERMIL2:
37277     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
37278                                                    Depth))
37279       return true;
37280     break;
37281   }
37282 
37283   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
37284   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
37285   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
37286   if ((VT.is256BitVector() || VT.is512BitVector()) &&
37287       DemandedElts.lshr(NumElts / 2) == 0) {
37288     unsigned SizeInBits = VT.getSizeInBits();
37289     unsigned ExtSizeInBits = SizeInBits / 2;
37290 
37291     // See if 512-bit ops only use the bottom 128-bits.
37292     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
37293       ExtSizeInBits = SizeInBits / 4;
37294 
37295     switch (Opc) {
37296       // Subvector broadcast.
37297     case X86ISD::SUBV_BROADCAST: {
37298       SDLoc DL(Op);
37299       SDValue Src = Op.getOperand(0);
37300       if (Src.getValueSizeInBits() > ExtSizeInBits)
37301         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
37302       else if (Src.getValueSizeInBits() < ExtSizeInBits) {
37303         MVT SrcSVT = Src.getSimpleValueType().getScalarType();
37304         MVT SrcVT =
37305             MVT::getVectorVT(SrcSVT, ExtSizeInBits / SrcSVT.getSizeInBits());
37306         Src = TLO.DAG.getNode(X86ISD::SUBV_BROADCAST, DL, SrcVT, Src);
37307       }
37308       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Src, 0,
37309                                                TLO.DAG, DL, ExtSizeInBits));
37310     }
37311       // Byte shifts by immediate.
37312     case X86ISD::VSHLDQ:
37313     case X86ISD::VSRLDQ:
37314       // Shift by uniform.
37315     case X86ISD::VSHL:
37316     case X86ISD::VSRL:
37317     case X86ISD::VSRA:
37318       // Shift by immediate.
37319     case X86ISD::VSHLI:
37320     case X86ISD::VSRLI:
37321     case X86ISD::VSRAI: {
37322       SDLoc DL(Op);
37323       SDValue Ext0 =
37324           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
37325       SDValue ExtOp =
37326           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
37327       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
37328       SDValue Insert =
37329           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
37330       return TLO.CombineTo(Op, Insert);
37331     }
37332     case X86ISD::VPERMI: {
37333       // Simplify PERMPD/PERMQ to extract_subvector.
37334       // TODO: This should be done in shuffle combining.
37335       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
37336         SmallVector<int, 4> Mask;
37337         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
37338         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
37339           SDLoc DL(Op);
37340           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
37341           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
37342           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
37343           return TLO.CombineTo(Op, Insert);
37344         }
37345       }
37346       break;
37347     }
37348       // Zero upper elements.
37349     case X86ISD::VZEXT_MOVL:
37350       // Target unary shuffles by immediate:
37351     case X86ISD::PSHUFD:
37352     case X86ISD::PSHUFLW:
37353     case X86ISD::PSHUFHW:
37354     case X86ISD::VPERMILPI:
37355       // (Non-Lane Crossing) Target Shuffles.
37356     case X86ISD::VPERMILPV:
37357     case X86ISD::VPERMIL2:
37358     case X86ISD::PSHUFB:
37359     case X86ISD::UNPCKL:
37360     case X86ISD::UNPCKH:
37361     case X86ISD::BLENDI:
37362       // Saturated Packs.
37363     case X86ISD::PACKSS:
37364     case X86ISD::PACKUS:
37365       // Horizontal Ops.
37366     case X86ISD::HADD:
37367     case X86ISD::HSUB:
37368     case X86ISD::FHADD:
37369     case X86ISD::FHSUB: {
37370       SDLoc DL(Op);
37371       SmallVector<SDValue, 4> Ops;
37372       for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
37373         SDValue SrcOp = Op.getOperand(i);
37374         EVT SrcVT = SrcOp.getValueType();
37375         assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
37376                "Unsupported vector size");
37377         Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
37378                                                           ExtSizeInBits)
37379                                        : SrcOp);
37380       }
37381       MVT ExtVT = VT.getSimpleVT();
37382       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
37383                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
37384       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
37385       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
37386       SDValue Insert =
37387           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
37388       return TLO.CombineTo(Op, Insert);
37389     }
37390     }
37391   }
37392 
37393   // Get target/faux shuffle mask.
37394   APInt OpUndef, OpZero;
37395   SmallVector<int, 64> OpMask;
37396   SmallVector<SDValue, 2> OpInputs;
37397   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
37398                               OpZero, TLO.DAG, Depth, false))
37399     return false;
37400 
37401   // Shuffle inputs must be the same size as the result.
37402   if (OpMask.size() != (unsigned)NumElts ||
37403       llvm::any_of(OpInputs, [VT](SDValue V) {
37404         return VT.getSizeInBits() != V.getValueSizeInBits() ||
37405                !V.getValueType().isVector();
37406       }))
37407     return false;
37408 
37409   KnownZero = OpZero;
37410   KnownUndef = OpUndef;
37411 
37412   // Check if shuffle mask can be simplified to undef/zero/identity.
37413   int NumSrcs = OpInputs.size();
37414   for (int i = 0; i != NumElts; ++i)
37415     if (!DemandedElts[i])
37416       OpMask[i] = SM_SentinelUndef;
37417 
37418   if (isUndefInRange(OpMask, 0, NumElts)) {
37419     KnownUndef.setAllBits();
37420     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
37421   }
37422   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
37423     KnownZero.setAllBits();
37424     return TLO.CombineTo(
37425         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
37426   }
37427   for (int Src = 0; Src != NumSrcs; ++Src)
37428     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
37429       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
37430 
37431   // Attempt to simplify inputs.
37432   for (int Src = 0; Src != NumSrcs; ++Src) {
37433     // TODO: Support inputs of different types.
37434     if (OpInputs[Src].getValueType() != VT)
37435       continue;
37436 
37437     int Lo = Src * NumElts;
37438     APInt SrcElts = APInt::getNullValue(NumElts);
37439     for (int i = 0; i != NumElts; ++i)
37440       if (DemandedElts[i]) {
37441         int M = OpMask[i] - Lo;
37442         if (0 <= M && M < NumElts)
37443           SrcElts.setBit(M);
37444       }
37445 
37446     // TODO - Propagate input undef/zero elts.
37447     APInt SrcUndef, SrcZero;
37448     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
37449                                    TLO, Depth + 1))
37450       return true;
37451   }
37452 
37453   // If we don't demand all elements, then attempt to combine to a simpler
37454   // shuffle.
37455   // TODO: Handle other depths, but first we need to handle the fact that
37456   // it might combine to the same shuffle.
37457   if (!DemandedElts.isAllOnesValue() && Depth == 0) {
37458     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
37459     for (int i = 0; i != NumElts; ++i)
37460       if (DemandedElts[i])
37461         DemandedMask[i] = i;
37462 
37463     SDValue NewShuffle = combineX86ShufflesRecursively(
37464         {Op}, 0, Op, DemandedMask, {}, Depth, /*HasVarMask*/ false,
37465         /*AllowVarMask*/ true, TLO.DAG, Subtarget);
37466     if (NewShuffle)
37467       return TLO.CombineTo(Op, NewShuffle);
37468   }
37469 
37470   return false;
37471 }
37472 
SimplifyDemandedBitsForTargetNode(SDValue Op,const APInt & OriginalDemandedBits,const APInt & OriginalDemandedElts,KnownBits & Known,TargetLoweringOpt & TLO,unsigned Depth) const37473 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
37474     SDValue Op, const APInt &OriginalDemandedBits,
37475     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
37476     unsigned Depth) const {
37477   EVT VT = Op.getValueType();
37478   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
37479   unsigned Opc = Op.getOpcode();
37480   switch(Opc) {
37481   case X86ISD::VTRUNC: {
37482     KnownBits KnownOp;
37483     SDValue Src = Op.getOperand(0);
37484     MVT SrcVT = Src.getSimpleValueType();
37485 
37486     // Simplify the input, using demanded bit information.
37487     APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
37488     APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
37489     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
37490       return true;
37491     break;
37492   }
37493   case X86ISD::PMULDQ:
37494   case X86ISD::PMULUDQ: {
37495     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
37496     KnownBits KnownOp;
37497     SDValue LHS = Op.getOperand(0);
37498     SDValue RHS = Op.getOperand(1);
37499     // FIXME: Can we bound this better?
37500     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
37501     if (SimplifyDemandedBits(LHS, DemandedMask, OriginalDemandedElts, KnownOp,
37502                              TLO, Depth + 1))
37503       return true;
37504     if (SimplifyDemandedBits(RHS, DemandedMask, OriginalDemandedElts, KnownOp,
37505                              TLO, Depth + 1))
37506       return true;
37507 
37508     // Aggressively peek through ops to get at the demanded low bits.
37509     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
37510         LHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
37511     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
37512         RHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
37513     if (DemandedLHS || DemandedRHS) {
37514       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
37515       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
37516       return TLO.CombineTo(
37517           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
37518     }
37519     break;
37520   }
37521   case X86ISD::VSHLI: {
37522     SDValue Op0 = Op.getOperand(0);
37523 
37524     unsigned ShAmt = Op.getConstantOperandVal(1);
37525     if (ShAmt >= BitWidth)
37526       break;
37527 
37528     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
37529 
37530     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
37531     // single shift.  We can do this if the bottom bits (which are shifted
37532     // out) are never demanded.
37533     if (Op0.getOpcode() == X86ISD::VSRLI &&
37534         OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
37535       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
37536       if (Shift2Amt < BitWidth) {
37537         int Diff = ShAmt - Shift2Amt;
37538         if (Diff == 0)
37539           return TLO.CombineTo(Op, Op0.getOperand(0));
37540 
37541         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
37542         SDValue NewShift = TLO.DAG.getNode(
37543             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
37544             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
37545         return TLO.CombineTo(Op, NewShift);
37546       }
37547     }
37548 
37549     // If we are only demanding sign bits then we can use the shift source directly.
37550     unsigned NumSignBits =
37551         TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
37552     unsigned UpperDemandedBits =
37553         BitWidth - OriginalDemandedBits.countTrailingZeros();
37554     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
37555       return TLO.CombineTo(Op, Op0);
37556 
37557     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
37558                              TLO, Depth + 1))
37559       return true;
37560 
37561     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
37562     Known.Zero <<= ShAmt;
37563     Known.One <<= ShAmt;
37564 
37565     // Low bits known zero.
37566     Known.Zero.setLowBits(ShAmt);
37567     break;
37568   }
37569   case X86ISD::VSRLI: {
37570     unsigned ShAmt = Op.getConstantOperandVal(1);
37571     if (ShAmt >= BitWidth)
37572       break;
37573 
37574     APInt DemandedMask = OriginalDemandedBits << ShAmt;
37575 
37576     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
37577                              OriginalDemandedElts, Known, TLO, Depth + 1))
37578       return true;
37579 
37580     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
37581     Known.Zero.lshrInPlace(ShAmt);
37582     Known.One.lshrInPlace(ShAmt);
37583 
37584     // High bits known zero.
37585     Known.Zero.setHighBits(ShAmt);
37586     break;
37587   }
37588   case X86ISD::VSRAI: {
37589     SDValue Op0 = Op.getOperand(0);
37590     SDValue Op1 = Op.getOperand(1);
37591 
37592     unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
37593     if (ShAmt >= BitWidth)
37594       break;
37595 
37596     APInt DemandedMask = OriginalDemandedBits << ShAmt;
37597 
37598     // If we just want the sign bit then we don't need to shift it.
37599     if (OriginalDemandedBits.isSignMask())
37600       return TLO.CombineTo(Op, Op0);
37601 
37602     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
37603     if (Op0.getOpcode() == X86ISD::VSHLI &&
37604         Op.getOperand(1) == Op0.getOperand(1)) {
37605       SDValue Op00 = Op0.getOperand(0);
37606       unsigned NumSignBits =
37607           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
37608       if (ShAmt < NumSignBits)
37609         return TLO.CombineTo(Op, Op00);
37610     }
37611 
37612     // If any of the demanded bits are produced by the sign extension, we also
37613     // demand the input sign bit.
37614     if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
37615       DemandedMask.setSignBit();
37616 
37617     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
37618                              TLO, Depth + 1))
37619       return true;
37620 
37621     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
37622     Known.Zero.lshrInPlace(ShAmt);
37623     Known.One.lshrInPlace(ShAmt);
37624 
37625     // If the input sign bit is known to be zero, or if none of the top bits
37626     // are demanded, turn this into an unsigned shift right.
37627     if (Known.Zero[BitWidth - ShAmt - 1] ||
37628         OriginalDemandedBits.countLeadingZeros() >= ShAmt)
37629       return TLO.CombineTo(
37630           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
37631 
37632     // High bits are known one.
37633     if (Known.One[BitWidth - ShAmt - 1])
37634       Known.One.setHighBits(ShAmt);
37635     break;
37636   }
37637   case X86ISD::PEXTRB:
37638   case X86ISD::PEXTRW: {
37639     SDValue Vec = Op.getOperand(0);
37640     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
37641     MVT VecVT = Vec.getSimpleValueType();
37642     unsigned NumVecElts = VecVT.getVectorNumElements();
37643 
37644     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
37645       unsigned Idx = CIdx->getZExtValue();
37646       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
37647 
37648       // If we demand no bits from the vector then we must have demanded
37649       // bits from the implict zext - simplify to zero.
37650       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
37651       if (DemandedVecBits == 0)
37652         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
37653 
37654       APInt KnownUndef, KnownZero;
37655       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
37656       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
37657                                      KnownZero, TLO, Depth + 1))
37658         return true;
37659 
37660       KnownBits KnownVec;
37661       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
37662                                KnownVec, TLO, Depth + 1))
37663         return true;
37664 
37665       if (SDValue V = SimplifyMultipleUseDemandedBits(
37666               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
37667         return TLO.CombineTo(
37668             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
37669 
37670       Known = KnownVec.zext(BitWidth);
37671       return false;
37672     }
37673     break;
37674   }
37675   case X86ISD::PINSRB:
37676   case X86ISD::PINSRW: {
37677     SDValue Vec = Op.getOperand(0);
37678     SDValue Scl = Op.getOperand(1);
37679     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
37680     MVT VecVT = Vec.getSimpleValueType();
37681 
37682     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
37683       unsigned Idx = CIdx->getZExtValue();
37684       if (!OriginalDemandedElts[Idx])
37685         return TLO.CombineTo(Op, Vec);
37686 
37687       KnownBits KnownVec;
37688       APInt DemandedVecElts(OriginalDemandedElts);
37689       DemandedVecElts.clearBit(Idx);
37690       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
37691                                KnownVec, TLO, Depth + 1))
37692         return true;
37693 
37694       KnownBits KnownScl;
37695       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
37696       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
37697       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
37698         return true;
37699 
37700       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
37701       Known.One = KnownVec.One & KnownScl.One;
37702       Known.Zero = KnownVec.Zero & KnownScl.Zero;
37703       return false;
37704     }
37705     break;
37706   }
37707   case X86ISD::PACKSS:
37708     // PACKSS saturates to MIN/MAX integer values. So if we just want the
37709     // sign bit then we can just ask for the source operands sign bit.
37710     // TODO - add known bits handling.
37711     if (OriginalDemandedBits.isSignMask()) {
37712       APInt DemandedLHS, DemandedRHS;
37713       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
37714 
37715       KnownBits KnownLHS, KnownRHS;
37716       APInt SignMask = APInt::getSignMask(BitWidth * 2);
37717       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
37718                                KnownLHS, TLO, Depth + 1))
37719         return true;
37720       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
37721                                KnownRHS, TLO, Depth + 1))
37722         return true;
37723 
37724       // Attempt to avoid multi-use ops if we don't need anything from them.
37725       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
37726           Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
37727       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
37728           Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
37729       if (DemandedOp0 || DemandedOp1) {
37730         SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
37731         SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
37732         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
37733       }
37734     }
37735     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
37736     break;
37737   case X86ISD::PCMPGT:
37738     // icmp sgt(0, R) == ashr(R, BitWidth-1).
37739     // iff we only need the sign bit then we can use R directly.
37740     if (OriginalDemandedBits.isSignMask() &&
37741         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
37742       return TLO.CombineTo(Op, Op.getOperand(1));
37743     break;
37744   case X86ISD::MOVMSK: {
37745     SDValue Src = Op.getOperand(0);
37746     MVT SrcVT = Src.getSimpleValueType();
37747     unsigned SrcBits = SrcVT.getScalarSizeInBits();
37748     unsigned NumElts = SrcVT.getVectorNumElements();
37749 
37750     // If we don't need the sign bits at all just return zero.
37751     if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
37752       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
37753 
37754     // Only demand the vector elements of the sign bits we need.
37755     APInt KnownUndef, KnownZero;
37756     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
37757     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
37758                                    TLO, Depth + 1))
37759       return true;
37760 
37761     Known.Zero = KnownZero.zextOrSelf(BitWidth);
37762     Known.Zero.setHighBits(BitWidth - NumElts);
37763 
37764     // MOVMSK only uses the MSB from each vector element.
37765     KnownBits KnownSrc;
37766     APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
37767     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
37768                              Depth + 1))
37769       return true;
37770 
37771     if (KnownSrc.One[SrcBits - 1])
37772       Known.One.setLowBits(NumElts);
37773     else if (KnownSrc.Zero[SrcBits - 1])
37774       Known.Zero.setLowBits(NumElts);
37775 
37776     // Attempt to avoid multi-use os if we don't need anything from it.
37777     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
37778             Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
37779       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
37780     return false;
37781   }
37782   case X86ISD::BEXTR: {
37783     SDValue Op0 = Op.getOperand(0);
37784     SDValue Op1 = Op.getOperand(1);
37785 
37786     // Only bottom 16-bits of the control bits are required.
37787     if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
37788       // NOTE: SimplifyDemandedBits won't do this for constants.
37789       const APInt &Val1 = Cst1->getAPIntValue();
37790       APInt MaskedVal1 = Val1 & 0xFFFF;
37791       if (MaskedVal1 != Val1) {
37792         SDLoc DL(Op);
37793         return TLO.CombineTo(
37794             Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
37795                                 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
37796       }
37797     }
37798 
37799     KnownBits Known1;
37800     APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
37801     if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
37802       return true;
37803 
37804     // If the length is 0, replace with 0.
37805     KnownBits LengthBits = Known1.extractBits(8, 8);
37806     if (LengthBits.isZero())
37807       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
37808 
37809     break;
37810   }
37811   }
37812 
37813   return TargetLowering::SimplifyDemandedBitsForTargetNode(
37814       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
37815 }
37816 
SimplifyMultipleUseDemandedBitsForTargetNode(SDValue Op,const APInt & DemandedBits,const APInt & DemandedElts,SelectionDAG & DAG,unsigned Depth) const37817 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
37818     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
37819     SelectionDAG &DAG, unsigned Depth) const {
37820   int NumElts = DemandedElts.getBitWidth();
37821   unsigned Opc = Op.getOpcode();
37822   EVT VT = Op.getValueType();
37823 
37824   switch (Opc) {
37825   case X86ISD::PINSRB:
37826   case X86ISD::PINSRW: {
37827     // If we don't demand the inserted element, return the base vector.
37828     SDValue Vec = Op.getOperand(0);
37829     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
37830     MVT VecVT = Vec.getSimpleValueType();
37831     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
37832         !DemandedElts[CIdx->getZExtValue()])
37833       return Vec;
37834     break;
37835   }
37836   case X86ISD::VSHLI: {
37837     // If we are only demanding sign bits then we can use the shift source
37838     // directly.
37839     SDValue Op0 = Op.getOperand(0);
37840     unsigned ShAmt = Op.getConstantOperandVal(1);
37841     unsigned BitWidth = DemandedBits.getBitWidth();
37842     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
37843     unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
37844     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
37845       return Op0;
37846     break;
37847   }
37848   case X86ISD::VSRAI:
37849     // iff we only need the sign bit then we can use the source directly.
37850     // TODO: generalize where we only demand extended signbits.
37851     if (DemandedBits.isSignMask())
37852       return Op.getOperand(0);
37853     break;
37854   case X86ISD::PCMPGT:
37855     // icmp sgt(0, R) == ashr(R, BitWidth-1).
37856     // iff we only need the sign bit then we can use R directly.
37857     if (DemandedBits.isSignMask() &&
37858         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
37859       return Op.getOperand(1);
37860     break;
37861   }
37862 
37863   APInt ShuffleUndef, ShuffleZero;
37864   SmallVector<int, 16> ShuffleMask;
37865   SmallVector<SDValue, 2> ShuffleOps;
37866   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
37867                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
37868     // If all the demanded elts are from one operand and are inline,
37869     // then we can use the operand directly.
37870     int NumOps = ShuffleOps.size();
37871     if (ShuffleMask.size() == (unsigned)NumElts &&
37872         llvm::all_of(ShuffleOps, [VT](SDValue V) {
37873           return VT.getSizeInBits() == V.getValueSizeInBits();
37874         })) {
37875 
37876       if (DemandedElts.isSubsetOf(ShuffleUndef))
37877         return DAG.getUNDEF(VT);
37878       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
37879         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
37880 
37881       // Bitmask that indicates which ops have only been accessed 'inline'.
37882       APInt IdentityOp = APInt::getAllOnesValue(NumOps);
37883       for (int i = 0; i != NumElts; ++i) {
37884         int M = ShuffleMask[i];
37885         if (!DemandedElts[i] || ShuffleUndef[i])
37886           continue;
37887         int OpIdx = M / NumElts;
37888         int EltIdx = M % NumElts;
37889         if (M < 0 || EltIdx != i) {
37890           IdentityOp.clearAllBits();
37891           break;
37892         }
37893         IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
37894         if (IdentityOp == 0)
37895           break;
37896       }
37897       assert((IdentityOp == 0 || IdentityOp.countPopulation() == 1) &&
37898              "Multiple identity shuffles detected");
37899 
37900       if (IdentityOp != 0)
37901         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countTrailingZeros()]);
37902     }
37903   }
37904 
37905   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
37906       Op, DemandedBits, DemandedElts, DAG, Depth);
37907 }
37908 
37909 // Helper to peek through bitops/setcc to determine size of source vector.
37910 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
checkBitcastSrcVectorSize(SDValue Src,unsigned Size)37911 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size) {
37912   switch (Src.getOpcode()) {
37913   case ISD::SETCC:
37914     return Src.getOperand(0).getValueSizeInBits() == Size;
37915   case ISD::AND:
37916   case ISD::XOR:
37917   case ISD::OR:
37918     return checkBitcastSrcVectorSize(Src.getOperand(0), Size) &&
37919            checkBitcastSrcVectorSize(Src.getOperand(1), Size);
37920   }
37921   return false;
37922 }
37923 
37924 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
getAltBitOpcode(unsigned Opcode)37925 static unsigned getAltBitOpcode(unsigned Opcode) {
37926   switch(Opcode) {
37927   case ISD::AND: return X86ISD::FAND;
37928   case ISD::OR: return X86ISD::FOR;
37929   case ISD::XOR: return X86ISD::FXOR;
37930   case X86ISD::ANDNP: return X86ISD::FANDN;
37931   }
37932   llvm_unreachable("Unknown bitwise opcode");
37933 }
37934 
37935 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
adjustBitcastSrcVectorSSE1(SelectionDAG & DAG,SDValue Src,const SDLoc & DL)37936 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
37937                                           const SDLoc &DL) {
37938   EVT SrcVT = Src.getValueType();
37939   if (SrcVT != MVT::v4i1)
37940     return SDValue();
37941 
37942   switch (Src.getOpcode()) {
37943   case ISD::SETCC:
37944     if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
37945         ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
37946         cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
37947       SDValue Op0 = Src.getOperand(0);
37948       if (ISD::isNormalLoad(Op0.getNode()))
37949         return DAG.getBitcast(MVT::v4f32, Op0);
37950       if (Op0.getOpcode() == ISD::BITCAST &&
37951           Op0.getOperand(0).getValueType() == MVT::v4f32)
37952         return Op0.getOperand(0);
37953     }
37954     break;
37955   case ISD::AND:
37956   case ISD::XOR:
37957   case ISD::OR: {
37958     SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
37959     SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
37960     if (Op0 && Op1)
37961       return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
37962                          Op1);
37963     break;
37964   }
37965   }
37966   return SDValue();
37967 }
37968 
37969 // Helper to push sign extension of vXi1 SETCC result through bitops.
signExtendBitcastSrcVector(SelectionDAG & DAG,EVT SExtVT,SDValue Src,const SDLoc & DL)37970 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
37971                                           SDValue Src, const SDLoc &DL) {
37972   switch (Src.getOpcode()) {
37973   case ISD::SETCC:
37974     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
37975   case ISD::AND:
37976   case ISD::XOR:
37977   case ISD::OR:
37978     return DAG.getNode(
37979         Src.getOpcode(), DL, SExtVT,
37980         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
37981         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
37982   }
37983   llvm_unreachable("Unexpected node type for vXi1 sign extension");
37984 }
37985 
37986 // Try to match patterns such as
37987 // (i16 bitcast (v16i1 x))
37988 // ->
37989 // (i16 movmsk (16i8 sext (v16i1 x)))
37990 // before the illegal vector is scalarized on subtargets that don't have legal
37991 // vxi1 types.
combineBitcastvxi1(SelectionDAG & DAG,EVT VT,SDValue Src,const SDLoc & DL,const X86Subtarget & Subtarget)37992 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
37993                                   const SDLoc &DL,
37994                                   const X86Subtarget &Subtarget) {
37995   EVT SrcVT = Src.getValueType();
37996   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
37997     return SDValue();
37998 
37999   // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
38000   // legalization destroys the v4i32 type.
38001   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
38002     if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
38003       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
38004                       DAG.getBitcast(MVT::v4f32, V));
38005       return DAG.getZExtOrTrunc(V, DL, VT);
38006     }
38007   }
38008 
38009   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
38010   // movmskb even with avx512. This will be better than truncating to vXi1 and
38011   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
38012   // vpcmpeqb/vpcmpgtb.
38013   bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
38014                       (Src.getOperand(0).getValueType() == MVT::v16i8 ||
38015                        Src.getOperand(0).getValueType() == MVT::v32i8 ||
38016                        Src.getOperand(0).getValueType() == MVT::v64i8);
38017 
38018   // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
38019   // directly with vpmovmskb/vmovmskps/vmovmskpd.
38020   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
38021       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
38022       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
38023     EVT CmpVT = Src.getOperand(0).getValueType();
38024     EVT EltVT = CmpVT.getVectorElementType();
38025     if (CmpVT.getSizeInBits() <= 256 &&
38026         (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
38027       PreferMovMsk = true;
38028   }
38029 
38030   // With AVX512 vxi1 types are legal and we prefer using k-regs.
38031   // MOVMSK is supported in SSE2 or later.
38032   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
38033     return SDValue();
38034 
38035   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
38036   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
38037   // v8i16 and v16i16.
38038   // For these two cases, we can shuffle the upper element bytes to a
38039   // consecutive sequence at the start of the vector and treat the results as
38040   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
38041   // for v16i16 this is not the case, because the shuffle is expensive, so we
38042   // avoid sign-extending to this type entirely.
38043   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
38044   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
38045   MVT SExtVT;
38046   bool PropagateSExt = false;
38047   switch (SrcVT.getSimpleVT().SimpleTy) {
38048   default:
38049     return SDValue();
38050   case MVT::v2i1:
38051     SExtVT = MVT::v2i64;
38052     break;
38053   case MVT::v4i1:
38054     SExtVT = MVT::v4i32;
38055     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
38056     // sign-extend to a 256-bit operation to avoid truncation.
38057     if (Subtarget.hasAVX() && checkBitcastSrcVectorSize(Src, 256)) {
38058       SExtVT = MVT::v4i64;
38059       PropagateSExt = true;
38060     }
38061     break;
38062   case MVT::v8i1:
38063     SExtVT = MVT::v8i16;
38064     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
38065     // sign-extend to a 256-bit operation to match the compare.
38066     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
38067     // 256-bit because the shuffle is cheaper than sign extending the result of
38068     // the compare.
38069     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256) ||
38070                                checkBitcastSrcVectorSize(Src, 512))) {
38071       SExtVT = MVT::v8i32;
38072       PropagateSExt = true;
38073     }
38074     break;
38075   case MVT::v16i1:
38076     SExtVT = MVT::v16i8;
38077     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
38078     // it is not profitable to sign-extend to 256-bit because this will
38079     // require an extra cross-lane shuffle which is more expensive than
38080     // truncating the result of the compare to 128-bits.
38081     break;
38082   case MVT::v32i1:
38083     SExtVT = MVT::v32i8;
38084     break;
38085   case MVT::v64i1:
38086     // If we have AVX512F, but not AVX512BW and the input is truncated from
38087     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
38088     if (Subtarget.hasAVX512()) {
38089       if (Subtarget.hasBWI())
38090         return SDValue();
38091       SExtVT = MVT::v64i8;
38092       break;
38093     }
38094     // Split if this is a <64 x i8> comparison result.
38095     if (checkBitcastSrcVectorSize(Src, 512)) {
38096       SExtVT = MVT::v64i8;
38097       break;
38098     }
38099     return SDValue();
38100   };
38101 
38102   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
38103                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
38104 
38105   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
38106     V = getPMOVMSKB(DL, V, DAG, Subtarget);
38107   } else {
38108     if (SExtVT == MVT::v8i16)
38109       V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
38110                       DAG.getUNDEF(MVT::v8i16));
38111     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
38112   }
38113 
38114   EVT IntVT =
38115       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
38116   V = DAG.getZExtOrTrunc(V, DL, IntVT);
38117   return DAG.getBitcast(VT, V);
38118 }
38119 
38120 // Convert a vXi1 constant build vector to the same width scalar integer.
combinevXi1ConstantToInteger(SDValue Op,SelectionDAG & DAG)38121 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
38122   EVT SrcVT = Op.getValueType();
38123   assert(SrcVT.getVectorElementType() == MVT::i1 &&
38124          "Expected a vXi1 vector");
38125   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
38126          "Expected a constant build vector");
38127 
38128   APInt Imm(SrcVT.getVectorNumElements(), 0);
38129   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
38130     SDValue In = Op.getOperand(Idx);
38131     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
38132       Imm.setBit(Idx);
38133   }
38134   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
38135   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
38136 }
38137 
combineCastedMaskArithmetic(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)38138 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
38139                                            TargetLowering::DAGCombinerInfo &DCI,
38140                                            const X86Subtarget &Subtarget) {
38141   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
38142 
38143   if (!DCI.isBeforeLegalizeOps())
38144     return SDValue();
38145 
38146   // Only do this if we have k-registers.
38147   if (!Subtarget.hasAVX512())
38148     return SDValue();
38149 
38150   EVT DstVT = N->getValueType(0);
38151   SDValue Op = N->getOperand(0);
38152   EVT SrcVT = Op.getValueType();
38153 
38154   if (!Op.hasOneUse())
38155     return SDValue();
38156 
38157   // Look for logic ops.
38158   if (Op.getOpcode() != ISD::AND &&
38159       Op.getOpcode() != ISD::OR &&
38160       Op.getOpcode() != ISD::XOR)
38161     return SDValue();
38162 
38163   // Make sure we have a bitcast between mask registers and a scalar type.
38164   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
38165         DstVT.isScalarInteger()) &&
38166       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
38167         SrcVT.isScalarInteger()))
38168     return SDValue();
38169 
38170   SDValue LHS = Op.getOperand(0);
38171   SDValue RHS = Op.getOperand(1);
38172 
38173   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
38174       LHS.getOperand(0).getValueType() == DstVT)
38175     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
38176                        DAG.getBitcast(DstVT, RHS));
38177 
38178   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
38179       RHS.getOperand(0).getValueType() == DstVT)
38180     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
38181                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
38182 
38183   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
38184   // Most of these have to move a constant from the scalar domain anyway.
38185   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
38186     RHS = combinevXi1ConstantToInteger(RHS, DAG);
38187     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
38188                        DAG.getBitcast(DstVT, LHS), RHS);
38189   }
38190 
38191   return SDValue();
38192 }
38193 
createMMXBuildVector(BuildVectorSDNode * BV,SelectionDAG & DAG,const X86Subtarget & Subtarget)38194 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
38195                                     const X86Subtarget &Subtarget) {
38196   SDLoc DL(BV);
38197   unsigned NumElts = BV->getNumOperands();
38198   SDValue Splat = BV->getSplatValue();
38199 
38200   // Build MMX element from integer GPR or SSE float values.
38201   auto CreateMMXElement = [&](SDValue V) {
38202     if (V.isUndef())
38203       return DAG.getUNDEF(MVT::x86mmx);
38204     if (V.getValueType().isFloatingPoint()) {
38205       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
38206         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
38207         V = DAG.getBitcast(MVT::v2i64, V);
38208         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
38209       }
38210       V = DAG.getBitcast(MVT::i32, V);
38211     } else {
38212       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
38213     }
38214     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
38215   };
38216 
38217   // Convert build vector ops to MMX data in the bottom elements.
38218   SmallVector<SDValue, 8> Ops;
38219 
38220   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
38221   if (Splat) {
38222     if (Splat.isUndef())
38223       return DAG.getUNDEF(MVT::x86mmx);
38224 
38225     Splat = CreateMMXElement(Splat);
38226 
38227     if (Subtarget.hasSSE1()) {
38228       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
38229       if (NumElts == 8)
38230         Splat = DAG.getNode(
38231             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
38232             DAG.getConstant(Intrinsic::x86_mmx_punpcklbw, DL, MVT::i32), Splat,
38233             Splat);
38234 
38235       // Use PSHUFW to repeat 16-bit elements.
38236       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
38237       return DAG.getNode(
38238           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
38239           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL, MVT::i32),
38240           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
38241     }
38242     Ops.append(NumElts, Splat);
38243   } else {
38244     for (unsigned i = 0; i != NumElts; ++i)
38245       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
38246   }
38247 
38248   // Use tree of PUNPCKLs to build up general MMX vector.
38249   while (Ops.size() > 1) {
38250     unsigned NumOps = Ops.size();
38251     unsigned IntrinOp =
38252         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
38253                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
38254                                     : Intrinsic::x86_mmx_punpcklbw));
38255     SDValue Intrin = DAG.getConstant(IntrinOp, DL, MVT::i32);
38256     for (unsigned i = 0; i != NumOps; i += 2)
38257       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
38258                                Ops[i], Ops[i + 1]);
38259     Ops.resize(NumOps / 2);
38260   }
38261 
38262   return Ops[0];
38263 }
38264 
38265 // Recursive function that attempts to find if a bool vector node was originally
38266 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
38267 // integer. If so, replace the scalar ops with bool vector equivalents back down
38268 // the chain.
combineBitcastToBoolVector(EVT VT,SDValue V,SDLoc DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)38269 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, SDLoc DL,
38270                                           SelectionDAG &DAG,
38271                                           const X86Subtarget &Subtarget) {
38272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38273   unsigned Opc = V.getOpcode();
38274   switch (Opc) {
38275   case ISD::BITCAST: {
38276     // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
38277     SDValue Src = V.getOperand(0);
38278     EVT SrcVT = Src.getValueType();
38279     if (SrcVT.isVector() || SrcVT.isFloatingPoint())
38280       return DAG.getBitcast(VT, Src);
38281     break;
38282   }
38283   case ISD::TRUNCATE: {
38284     // If we find a suitable source, a truncated scalar becomes a subvector.
38285     SDValue Src = V.getOperand(0);
38286     EVT NewSrcVT =
38287         EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
38288     if (TLI.isTypeLegal(NewSrcVT))
38289       if (SDValue N0 =
38290               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
38291         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
38292                            DAG.getIntPtrConstant(0, DL));
38293     break;
38294   }
38295   case ISD::ANY_EXTEND:
38296   case ISD::ZERO_EXTEND: {
38297     // If we find a suitable source, an extended scalar becomes a subvector.
38298     SDValue Src = V.getOperand(0);
38299     EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
38300                                     Src.getScalarValueSizeInBits());
38301     if (TLI.isTypeLegal(NewSrcVT))
38302       if (SDValue N0 =
38303               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
38304         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
38305                            Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
38306                                                   : DAG.getConstant(0, DL, VT),
38307                            N0, DAG.getIntPtrConstant(0, DL));
38308     break;
38309   }
38310   case ISD::OR: {
38311     // If we find suitable sources, we can just move an OR to the vector domain.
38312     SDValue Src0 = V.getOperand(0);
38313     SDValue Src1 = V.getOperand(1);
38314     if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
38315       if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
38316         return DAG.getNode(Opc, DL, VT, N0, N1);
38317     break;
38318   }
38319   case ISD::SHL: {
38320     // If we find a suitable source, a SHL becomes a KSHIFTL.
38321     SDValue Src0 = V.getOperand(0);
38322     if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
38323       if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
38324         return DAG.getNode(
38325             X86ISD::KSHIFTL, DL, VT, N0,
38326             DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
38327     break;
38328   }
38329   }
38330   return SDValue();
38331 }
38332 
combineBitcast(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)38333 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
38334                               TargetLowering::DAGCombinerInfo &DCI,
38335                               const X86Subtarget &Subtarget) {
38336   SDValue N0 = N->getOperand(0);
38337   EVT VT = N->getValueType(0);
38338   EVT SrcVT = N0.getValueType();
38339 
38340   // Try to match patterns such as
38341   // (i16 bitcast (v16i1 x))
38342   // ->
38343   // (i16 movmsk (16i8 sext (v16i1 x)))
38344   // before the setcc result is scalarized on subtargets that don't have legal
38345   // vxi1 types.
38346   if (DCI.isBeforeLegalize()) {
38347     SDLoc dl(N);
38348     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
38349       return V;
38350 
38351     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
38352     // type, widen both sides to avoid a trip through memory.
38353     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
38354         Subtarget.hasAVX512()) {
38355       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
38356       N0 = DAG.getBitcast(MVT::v8i1, N0);
38357       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
38358                          DAG.getIntPtrConstant(0, dl));
38359     }
38360 
38361     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
38362     // type, widen both sides to avoid a trip through memory.
38363     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
38364         Subtarget.hasAVX512()) {
38365       // Use zeros for the widening if we already have some zeroes. This can
38366       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
38367       // stream of this.
38368       // FIXME: It might make sense to detect a concat_vectors with a mix of
38369       // zeroes and undef and turn it into insert_subvector for i1 vectors as
38370       // a separate combine. What we can't do is canonicalize the operands of
38371       // such a concat or we'll get into a loop with SimplifyDemandedBits.
38372       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
38373         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
38374         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
38375           SrcVT = LastOp.getValueType();
38376           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
38377           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
38378           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
38379           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
38380           N0 = DAG.getBitcast(MVT::i8, N0);
38381           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
38382         }
38383       }
38384 
38385       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
38386       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
38387       Ops[0] = N0;
38388       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
38389       N0 = DAG.getBitcast(MVT::i8, N0);
38390       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
38391     }
38392   } else {
38393     // If we're bitcasting from iX to vXi1, see if the integer originally
38394     // began as a vXi1 and whether we can remove the bitcast entirely.
38395     if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
38396         SrcVT.isScalarInteger() &&
38397         DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
38398       if (SDValue V =
38399               combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
38400         return V;
38401     }
38402   }
38403 
38404   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
38405   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
38406   // due to insert_subvector legalization on KNL. By promoting the copy to i16
38407   // we can help with known bits propagation from the vXi1 domain to the
38408   // scalar domain.
38409   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
38410       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
38411       N0.getOperand(0).getValueType() == MVT::v16i1 &&
38412       isNullConstant(N0.getOperand(1)))
38413     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
38414                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
38415 
38416   // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
38417   // and the vbroadcast_load are both integer or both fp. In some cases this
38418   // will remove the bitcast entirely.
38419   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
38420        VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
38421     auto *BCast = cast<MemIntrinsicSDNode>(N0);
38422     unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
38423     unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
38424     // Don't swap i8/i16 since don't have fp types that size.
38425     if (MemSize >= 32) {
38426       MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
38427                                        : MVT::getIntegerVT(MemSize);
38428       MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
38429                                         : MVT::getIntegerVT(SrcVTSize);
38430       LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
38431 
38432       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
38433       SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
38434       SDValue ResNode =
38435           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
38436                                   MemVT, BCast->getMemOperand());
38437       DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
38438       return DAG.getBitcast(VT, ResNode);
38439     }
38440   }
38441 
38442   // Since MMX types are special and don't usually play with other vector types,
38443   // it's better to handle them early to be sure we emit efficient code by
38444   // avoiding store-load conversions.
38445   if (VT == MVT::x86mmx) {
38446     // Detect MMX constant vectors.
38447     APInt UndefElts;
38448     SmallVector<APInt, 1> EltBits;
38449     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
38450       SDLoc DL(N0);
38451       // Handle zero-extension of i32 with MOVD.
38452       if (EltBits[0].countLeadingZeros() >= 32)
38453         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
38454                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
38455       // Else, bitcast to a double.
38456       // TODO - investigate supporting sext 32-bit immediates on x86_64.
38457       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
38458       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
38459     }
38460 
38461     // Detect bitcasts to x86mmx low word.
38462     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
38463         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
38464         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
38465       bool LowUndef = true, AllUndefOrZero = true;
38466       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
38467         SDValue Op = N0.getOperand(i);
38468         LowUndef &= Op.isUndef() || (i >= e/2);
38469         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
38470       }
38471       if (AllUndefOrZero) {
38472         SDValue N00 = N0.getOperand(0);
38473         SDLoc dl(N00);
38474         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
38475                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
38476         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
38477       }
38478     }
38479 
38480     // Detect bitcasts of 64-bit build vectors and convert to a
38481     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
38482     // lowest element.
38483     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
38484         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
38485          SrcVT == MVT::v8i8))
38486       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
38487 
38488     // Detect bitcasts between element or subvector extraction to x86mmx.
38489     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
38490          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
38491         isNullConstant(N0.getOperand(1))) {
38492       SDValue N00 = N0.getOperand(0);
38493       if (N00.getValueType().is128BitVector())
38494         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
38495                            DAG.getBitcast(MVT::v2i64, N00));
38496     }
38497 
38498     // Detect bitcasts from FP_TO_SINT to x86mmx.
38499     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
38500       SDLoc DL(N0);
38501       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
38502                                 DAG.getUNDEF(MVT::v2i32));
38503       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
38504                          DAG.getBitcast(MVT::v2i64, Res));
38505     }
38506   }
38507 
38508   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
38509   // most of these to scalar anyway.
38510   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
38511       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
38512       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
38513     return combinevXi1ConstantToInteger(N0, DAG);
38514   }
38515 
38516   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
38517       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
38518       isa<ConstantSDNode>(N0)) {
38519     auto *C = cast<ConstantSDNode>(N0);
38520     if (C->isAllOnesValue())
38521       return DAG.getConstant(1, SDLoc(N0), VT);
38522     if (C->isNullValue())
38523       return DAG.getConstant(0, SDLoc(N0), VT);
38524   }
38525 
38526   // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
38527   // Turn it into a sign bit compare that produces a k-register. This avoids
38528   // a trip through a GPR.
38529   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
38530       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
38531       isPowerOf2_32(VT.getVectorNumElements())) {
38532     unsigned NumElts = VT.getVectorNumElements();
38533     SDValue Src = N0;
38534 
38535     // Peek through truncate.
38536     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
38537       Src = N0.getOperand(0);
38538 
38539     if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
38540       SDValue MovmskIn = Src.getOperand(0);
38541       MVT MovmskVT = MovmskIn.getSimpleValueType();
38542       unsigned MovMskElts = MovmskVT.getVectorNumElements();
38543 
38544       // We allow extra bits of the movmsk to be used since they are known zero.
38545       // We can't convert a VPMOVMSKB without avx512bw.
38546       if (MovMskElts <= NumElts &&
38547           (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
38548         EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
38549         MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
38550         SDLoc dl(N);
38551         MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
38552         SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
38553                                    DAG.getConstant(0, dl, IntVT), ISD::SETLT);
38554         if (EVT(CmpVT) == VT)
38555           return Cmp;
38556 
38557         // Pad with zeroes up to original VT to replace the zeroes that were
38558         // being used from the MOVMSK.
38559         unsigned NumConcats = NumElts / MovMskElts;
38560         SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
38561         Ops[0] = Cmp;
38562         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
38563       }
38564     }
38565   }
38566 
38567   // Try to remove bitcasts from input and output of mask arithmetic to
38568   // remove GPR<->K-register crossings.
38569   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
38570     return V;
38571 
38572   // Convert a bitcasted integer logic operation that has one bitcasted
38573   // floating-point operand into a floating-point logic operation. This may
38574   // create a load of a constant, but that is cheaper than materializing the
38575   // constant in an integer register and transferring it to an SSE register or
38576   // transferring the SSE operand to integer register and back.
38577   unsigned FPOpcode;
38578   switch (N0.getOpcode()) {
38579     case ISD::AND: FPOpcode = X86ISD::FAND; break;
38580     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
38581     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
38582     default: return SDValue();
38583   }
38584 
38585   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
38586         (Subtarget.hasSSE2() && VT == MVT::f64)))
38587     return SDValue();
38588 
38589   SDValue LogicOp0 = N0.getOperand(0);
38590   SDValue LogicOp1 = N0.getOperand(1);
38591   SDLoc DL0(N0);
38592 
38593   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
38594   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
38595       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).getValueType() == VT &&
38596       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
38597     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
38598     return DAG.getNode(FPOpcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
38599   }
38600   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
38601   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
38602       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).getValueType() == VT &&
38603       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
38604     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
38605     return DAG.getNode(FPOpcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
38606   }
38607 
38608   return SDValue();
38609 }
38610 
38611 // Given a ABS node, detect the following pattern:
38612 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
38613 // This is useful as it is the input into a SAD pattern.
detectZextAbsDiff(const SDValue & Abs,SDValue & Op0,SDValue & Op1)38614 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
38615   SDValue AbsOp1 = Abs->getOperand(0);
38616   if (AbsOp1.getOpcode() != ISD::SUB)
38617     return false;
38618 
38619   Op0 = AbsOp1.getOperand(0);
38620   Op1 = AbsOp1.getOperand(1);
38621 
38622   // Check if the operands of the sub are zero-extended from vectors of i8.
38623   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
38624       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
38625       Op1.getOpcode() != ISD::ZERO_EXTEND ||
38626       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
38627     return false;
38628 
38629   return true;
38630 }
38631 
38632 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
38633 // to these zexts.
createPSADBW(SelectionDAG & DAG,const SDValue & Zext0,const SDValue & Zext1,const SDLoc & DL,const X86Subtarget & Subtarget)38634 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
38635                             const SDValue &Zext1, const SDLoc &DL,
38636                             const X86Subtarget &Subtarget) {
38637   // Find the appropriate width for the PSADBW.
38638   EVT InVT = Zext0.getOperand(0).getValueType();
38639   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
38640 
38641   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
38642   // fill in the missing vector elements with 0.
38643   unsigned NumConcat = RegSize / InVT.getSizeInBits();
38644   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
38645   Ops[0] = Zext0.getOperand(0);
38646   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
38647   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
38648   Ops[0] = Zext1.getOperand(0);
38649   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
38650 
38651   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
38652   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
38653                           ArrayRef<SDValue> Ops) {
38654     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
38655     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
38656   };
38657   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
38658   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
38659                           PSADBWBuilder);
38660 }
38661 
38662 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
38663 // PHMINPOSUW.
combineHorizontalMinMaxResult(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)38664 static SDValue combineHorizontalMinMaxResult(SDNode *Extract, SelectionDAG &DAG,
38665                                              const X86Subtarget &Subtarget) {
38666   // Bail without SSE41.
38667   if (!Subtarget.hasSSE41())
38668     return SDValue();
38669 
38670   EVT ExtractVT = Extract->getValueType(0);
38671   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
38672     return SDValue();
38673 
38674   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
38675   ISD::NodeType BinOp;
38676   SDValue Src = DAG.matchBinOpReduction(
38677       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
38678   if (!Src)
38679     return SDValue();
38680 
38681   EVT SrcVT = Src.getValueType();
38682   EVT SrcSVT = SrcVT.getScalarType();
38683   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
38684     return SDValue();
38685 
38686   SDLoc DL(Extract);
38687   SDValue MinPos = Src;
38688 
38689   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
38690   while (SrcVT.getSizeInBits() > 128) {
38691     SDValue Lo, Hi;
38692     std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
38693     SrcVT = Lo.getValueType();
38694     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
38695   }
38696   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
38697           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
38698          "Unexpected value type");
38699 
38700   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
38701   // to flip the value accordingly.
38702   SDValue Mask;
38703   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
38704   if (BinOp == ISD::SMAX)
38705     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
38706   else if (BinOp == ISD::SMIN)
38707     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
38708   else if (BinOp == ISD::UMAX)
38709     Mask = DAG.getConstant(APInt::getAllOnesValue(MaskEltsBits), DL, SrcVT);
38710 
38711   if (Mask)
38712     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
38713 
38714   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
38715   // shuffling each upper element down and insert zeros. This means that the
38716   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
38717   // ready for the PHMINPOS.
38718   if (ExtractVT == MVT::i8) {
38719     SDValue Upper = DAG.getVectorShuffle(
38720         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
38721         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
38722     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
38723   }
38724 
38725   // Perform the PHMINPOS on a v8i16 vector,
38726   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
38727   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
38728   MinPos = DAG.getBitcast(SrcVT, MinPos);
38729 
38730   if (Mask)
38731     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
38732 
38733   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
38734                      DAG.getIntPtrConstant(0, DL));
38735 }
38736 
38737 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
combineHorizontalPredicateResult(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)38738 static SDValue combineHorizontalPredicateResult(SDNode *Extract,
38739                                                 SelectionDAG &DAG,
38740                                                 const X86Subtarget &Subtarget) {
38741   // Bail without SSE2.
38742   if (!Subtarget.hasSSE2())
38743     return SDValue();
38744 
38745   EVT ExtractVT = Extract->getValueType(0);
38746   unsigned BitWidth = ExtractVT.getSizeInBits();
38747   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
38748       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
38749     return SDValue();
38750 
38751   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
38752   ISD::NodeType BinOp;
38753   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
38754   if (!Match && ExtractVT == MVT::i1)
38755     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
38756   if (!Match)
38757     return SDValue();
38758 
38759   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
38760   // which we can't support here for now.
38761   if (Match.getScalarValueSizeInBits() != BitWidth)
38762     return SDValue();
38763 
38764   SDValue Movmsk;
38765   SDLoc DL(Extract);
38766   EVT MatchVT = Match.getValueType();
38767   unsigned NumElts = MatchVT.getVectorNumElements();
38768   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
38769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38770 
38771   if (ExtractVT == MVT::i1) {
38772     // Special case for (pre-legalization) vXi1 reductions.
38773     if (NumElts > 64 || !isPowerOf2_32(NumElts))
38774       return SDValue();
38775     if (TLI.isTypeLegal(MatchVT)) {
38776       // If this is a legal AVX512 predicate type then we can just bitcast.
38777       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
38778       Movmsk = DAG.getBitcast(MovmskVT, Match);
38779     } else {
38780       // For all_of(setcc(vec,0,eq)) - avoid vXi64 comparisons if we don't have
38781       // PCMPEQQ (SSE41+), use PCMPEQD instead.
38782       if (BinOp == ISD::AND && !Subtarget.hasSSE41() &&
38783           Match.getOpcode() == ISD::SETCC &&
38784           ISD::isBuildVectorAllZeros(Match.getOperand(1).getNode()) &&
38785           cast<CondCodeSDNode>(Match.getOperand(2))->get() ==
38786               ISD::CondCode::SETEQ) {
38787         SDValue Vec = Match.getOperand(0);
38788         if (Vec.getValueType().getScalarType() == MVT::i64 &&
38789             (2 * NumElts) <= MaxElts) {
38790           NumElts *= 2;
38791           EVT CmpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
38792           MatchVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
38793           Match = DAG.getSetCC(
38794               DL, MatchVT, DAG.getBitcast(CmpVT, Match.getOperand(0)),
38795               DAG.getBitcast(CmpVT, Match.getOperand(1)), ISD::CondCode::SETEQ);
38796         }
38797       }
38798 
38799       // Use combineBitcastvxi1 to create the MOVMSK.
38800       while (NumElts > MaxElts) {
38801         SDValue Lo, Hi;
38802         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
38803         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
38804         NumElts /= 2;
38805       }
38806       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
38807       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
38808     }
38809     if (!Movmsk)
38810       return SDValue();
38811     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
38812   } else {
38813     // FIXME: Better handling of k-registers or 512-bit vectors?
38814     unsigned MatchSizeInBits = Match.getValueSizeInBits();
38815     if (!(MatchSizeInBits == 128 ||
38816           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
38817       return SDValue();
38818 
38819     // Make sure this isn't a vector of 1 element. The perf win from using
38820     // MOVMSK diminishes with less elements in the reduction, but it is
38821     // generally better to get the comparison over to the GPRs as soon as
38822     // possible to reduce the number of vector ops.
38823     if (Match.getValueType().getVectorNumElements() < 2)
38824       return SDValue();
38825 
38826     // Check that we are extracting a reduction of all sign bits.
38827     if (DAG.ComputeNumSignBits(Match) != BitWidth)
38828       return SDValue();
38829 
38830     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
38831       SDValue Lo, Hi;
38832       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
38833       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
38834       MatchSizeInBits = Match.getValueSizeInBits();
38835     }
38836 
38837     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
38838     MVT MaskSrcVT;
38839     if (64 == BitWidth || 32 == BitWidth)
38840       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
38841                                    MatchSizeInBits / BitWidth);
38842     else
38843       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
38844 
38845     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
38846     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
38847     NumElts = MaskSrcVT.getVectorNumElements();
38848   }
38849   assert((NumElts <= 32 || NumElts == 64) &&
38850          "Not expecting more than 64 elements");
38851 
38852   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
38853   if (BinOp == ISD::XOR) {
38854     // parity -> (AND (CTPOP(MOVMSK X)), 1)
38855     SDValue Mask = DAG.getConstant(1, DL, CmpVT);
38856     SDValue Result = DAG.getNode(ISD::CTPOP, DL, CmpVT, Movmsk);
38857     Result = DAG.getNode(ISD::AND, DL, CmpVT, Result, Mask);
38858     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
38859   }
38860 
38861   SDValue CmpC;
38862   ISD::CondCode CondCode;
38863   if (BinOp == ISD::OR) {
38864     // any_of -> MOVMSK != 0
38865     CmpC = DAG.getConstant(0, DL, CmpVT);
38866     CondCode = ISD::CondCode::SETNE;
38867   } else {
38868     // all_of -> MOVMSK == ((1 << NumElts) - 1)
38869     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
38870                            DL, CmpVT);
38871     CondCode = ISD::CondCode::SETEQ;
38872   }
38873 
38874   // The setcc produces an i8 of 0/1, so extend that to the result width and
38875   // negate to get the final 0/-1 mask value.
38876   EVT SetccVT =
38877       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
38878   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
38879   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
38880   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
38881   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
38882 }
38883 
combineBasicSADPattern(SDNode * Extract,SelectionDAG & DAG,const X86Subtarget & Subtarget)38884 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
38885                                       const X86Subtarget &Subtarget) {
38886   // PSADBW is only supported on SSE2 and up.
38887   if (!Subtarget.hasSSE2())
38888     return SDValue();
38889 
38890   EVT ExtractVT = Extract->getValueType(0);
38891   // Verify the type we're extracting is either i32 or i64.
38892   // FIXME: Could support other types, but this is what we have coverage for.
38893   if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
38894     return SDValue();
38895 
38896   EVT VT = Extract->getOperand(0).getValueType();
38897   if (!isPowerOf2_32(VT.getVectorNumElements()))
38898     return SDValue();
38899 
38900   // Match shuffle + add pyramid.
38901   ISD::NodeType BinOp;
38902   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
38903 
38904   // The operand is expected to be zero extended from i8
38905   // (verified in detectZextAbsDiff).
38906   // In order to convert to i64 and above, additional any/zero/sign
38907   // extend is expected.
38908   // The zero extend from 32 bit has no mathematical effect on the result.
38909   // Also the sign extend is basically zero extend
38910   // (extends the sign bit which is zero).
38911   // So it is correct to skip the sign/zero extend instruction.
38912   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
38913                Root.getOpcode() == ISD::ZERO_EXTEND ||
38914                Root.getOpcode() == ISD::ANY_EXTEND))
38915     Root = Root.getOperand(0);
38916 
38917   // If there was a match, we want Root to be a select that is the root of an
38918   // abs-diff pattern.
38919   if (!Root || Root.getOpcode() != ISD::ABS)
38920     return SDValue();
38921 
38922   // Check whether we have an abs-diff pattern feeding into the select.
38923   SDValue Zext0, Zext1;
38924   if (!detectZextAbsDiff(Root, Zext0, Zext1))
38925     return SDValue();
38926 
38927   // Create the SAD instruction.
38928   SDLoc DL(Extract);
38929   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
38930 
38931   // If the original vector was wider than 8 elements, sum over the results
38932   // in the SAD vector.
38933   unsigned Stages = Log2_32(VT.getVectorNumElements());
38934   EVT SadVT = SAD.getValueType();
38935   if (Stages > 3) {
38936     unsigned SadElems = SadVT.getVectorNumElements();
38937 
38938     for(unsigned i = Stages - 3; i > 0; --i) {
38939       SmallVector<int, 16> Mask(SadElems, -1);
38940       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
38941         Mask[j] = MaskEnd + j;
38942 
38943       SDValue Shuffle =
38944           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
38945       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
38946     }
38947   }
38948 
38949   unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
38950   // Return the lowest ExtractSizeInBits bits.
38951   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
38952                                SadVT.getSizeInBits() / ExtractSizeInBits);
38953   SAD = DAG.getBitcast(ResVT, SAD);
38954   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
38955                      Extract->getOperand(1));
38956 }
38957 
38958 // Attempt to peek through a target shuffle and extract the scalar from the
38959 // source.
combineExtractWithShuffle(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)38960 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
38961                                          TargetLowering::DAGCombinerInfo &DCI,
38962                                          const X86Subtarget &Subtarget) {
38963   if (DCI.isBeforeLegalizeOps())
38964     return SDValue();
38965 
38966   SDLoc dl(N);
38967   SDValue Src = N->getOperand(0);
38968   SDValue Idx = N->getOperand(1);
38969 
38970   EVT VT = N->getValueType(0);
38971   EVT SrcVT = Src.getValueType();
38972   EVT SrcSVT = SrcVT.getVectorElementType();
38973   unsigned SrcEltBits = SrcSVT.getSizeInBits();
38974   unsigned NumSrcElts = SrcVT.getVectorNumElements();
38975 
38976   // Don't attempt this for boolean mask vectors or unknown extraction indices.
38977   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
38978     return SDValue();
38979 
38980   const APInt &IdxC = N->getConstantOperandAPInt(1);
38981   if (IdxC.uge(NumSrcElts))
38982     return SDValue();
38983 
38984   SDValue SrcBC = peekThroughBitcasts(Src);
38985 
38986   // Handle extract(bitcast(broadcast(scalar_value))).
38987   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
38988     SDValue SrcOp = SrcBC.getOperand(0);
38989     EVT SrcOpVT = SrcOp.getValueType();
38990     if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
38991         (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
38992       unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
38993       unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
38994       // TODO support non-zero offsets.
38995       if (Offset == 0) {
38996         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
38997         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
38998         return SrcOp;
38999       }
39000     }
39001   }
39002 
39003   // If we're extracting a single element from a broadcast load and there are
39004   // no other users, just create a single load.
39005   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
39006     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
39007     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
39008     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
39009         VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
39010       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
39011                                  MemIntr->getBasePtr(),
39012                                  MemIntr->getPointerInfo(),
39013                                  MemIntr->getOriginalAlign(),
39014                                  MemIntr->getMemOperand()->getFlags());
39015       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
39016       return Load;
39017     }
39018   }
39019 
39020   // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
39021   // TODO: Move to DAGCombine?
39022   if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
39023       SrcBC.getValueType().isInteger() &&
39024       (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
39025       SrcBC.getScalarValueSizeInBits() ==
39026           SrcBC.getOperand(0).getValueSizeInBits()) {
39027     unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
39028     if (IdxC.ult(Scale)) {
39029       unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
39030       SDValue Scl = SrcBC.getOperand(0);
39031       EVT SclVT = Scl.getValueType();
39032       if (Offset) {
39033         Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
39034                           DAG.getShiftAmountConstant(Offset, SclVT, dl));
39035       }
39036       Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
39037       Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
39038       return Scl;
39039     }
39040   }
39041 
39042   // Handle extract(truncate(x)) for 0'th index.
39043   // TODO: Treat this as a faux shuffle?
39044   // TODO: When can we use this for general indices?
39045   if (ISD::TRUNCATE == Src.getOpcode() && SrcVT.is128BitVector() && IdxC == 0) {
39046     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
39047     Src = DAG.getBitcast(SrcVT, Src);
39048     return DAG.getNode(N->getOpcode(), dl, VT, Src, Idx);
39049   }
39050 
39051   // Resolve the target shuffle inputs and mask.
39052   SmallVector<int, 16> Mask;
39053   SmallVector<SDValue, 2> Ops;
39054   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
39055     return SDValue();
39056 
39057   // Shuffle inputs must be the same size as the result.
39058   if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
39059         return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
39060       }))
39061     return SDValue();
39062 
39063   // Attempt to narrow/widen the shuffle mask to the correct size.
39064   if (Mask.size() != NumSrcElts) {
39065     if ((NumSrcElts % Mask.size()) == 0) {
39066       SmallVector<int, 16> ScaledMask;
39067       int Scale = NumSrcElts / Mask.size();
39068       narrowShuffleMaskElts(Scale, Mask, ScaledMask);
39069       Mask = std::move(ScaledMask);
39070     } else if ((Mask.size() % NumSrcElts) == 0) {
39071       // Simplify Mask based on demanded element.
39072       int ExtractIdx = (int)N->getConstantOperandVal(1);
39073       int Scale = Mask.size() / NumSrcElts;
39074       int Lo = Scale * ExtractIdx;
39075       int Hi = Scale * (ExtractIdx + 1);
39076       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
39077         if (i < Lo || Hi <= i)
39078           Mask[i] = SM_SentinelUndef;
39079 
39080       SmallVector<int, 16> WidenedMask;
39081       while (Mask.size() > NumSrcElts &&
39082              canWidenShuffleElements(Mask, WidenedMask))
39083         Mask = std::move(WidenedMask);
39084       // TODO - investigate support for wider shuffle masks with known upper
39085       // undef/zero elements for implicit zero-extension.
39086     }
39087   }
39088 
39089   // Check if narrowing/widening failed.
39090   if (Mask.size() != NumSrcElts)
39091     return SDValue();
39092 
39093   int SrcIdx = Mask[IdxC.getZExtValue()];
39094 
39095   // If the shuffle source element is undef/zero then we can just accept it.
39096   if (SrcIdx == SM_SentinelUndef)
39097     return DAG.getUNDEF(VT);
39098 
39099   if (SrcIdx == SM_SentinelZero)
39100     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
39101                                 : DAG.getConstant(0, dl, VT);
39102 
39103   SDValue SrcOp = Ops[SrcIdx / Mask.size()];
39104   SrcIdx = SrcIdx % Mask.size();
39105 
39106   // We can only extract other elements from 128-bit vectors and in certain
39107   // circumstances, depending on SSE-level.
39108   // TODO: Investigate using extract_subvector for larger vectors.
39109   // TODO: Investigate float/double extraction if it will be just stored.
39110   if ((SrcVT == MVT::v4i32 || SrcVT == MVT::v2i64) &&
39111       ((SrcIdx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
39112     assert(SrcSVT == VT && "Unexpected extraction type");
39113     SrcOp = DAG.getBitcast(SrcVT, SrcOp);
39114     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcSVT, SrcOp,
39115                        DAG.getIntPtrConstant(SrcIdx, dl));
39116   }
39117 
39118   if ((SrcVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
39119       (SrcVT == MVT::v16i8 && Subtarget.hasSSE41())) {
39120     assert(VT.getSizeInBits() >= SrcEltBits && "Unexpected extraction type");
39121     unsigned OpCode = (SrcVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
39122     SrcOp = DAG.getBitcast(SrcVT, SrcOp);
39123     SDValue ExtOp = DAG.getNode(OpCode, dl, MVT::i32, SrcOp,
39124                                 DAG.getIntPtrConstant(SrcIdx, dl));
39125     return DAG.getZExtOrTrunc(ExtOp, dl, VT);
39126   }
39127 
39128   return SDValue();
39129 }
39130 
39131 /// Extracting a scalar FP value from vector element 0 is free, so extract each
39132 /// operand first, then perform the math as a scalar op.
scalarizeExtEltFP(SDNode * ExtElt,SelectionDAG & DAG)39133 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG) {
39134   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
39135   SDValue Vec = ExtElt->getOperand(0);
39136   SDValue Index = ExtElt->getOperand(1);
39137   EVT VT = ExtElt->getValueType(0);
39138   EVT VecVT = Vec.getValueType();
39139 
39140   // TODO: If this is a unary/expensive/expand op, allow extraction from a
39141   // non-zero element because the shuffle+scalar op will be cheaper?
39142   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
39143     return SDValue();
39144 
39145   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
39146   // extract, the condition code), so deal with those as a special-case.
39147   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
39148     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
39149     if (OpVT != MVT::f32 && OpVT != MVT::f64)
39150       return SDValue();
39151 
39152     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
39153     SDLoc DL(ExtElt);
39154     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
39155                                Vec.getOperand(0), Index);
39156     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
39157                                Vec.getOperand(1), Index);
39158     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
39159   }
39160 
39161   if (VT != MVT::f32 && VT != MVT::f64)
39162     return SDValue();
39163 
39164   // Vector FP selects don't fit the pattern of FP math ops (because the
39165   // condition has a different type and we have to change the opcode), so deal
39166   // with those here.
39167   // FIXME: This is restricted to pre type legalization by ensuring the setcc
39168   // has i1 elements. If we loosen this we need to convert vector bool to a
39169   // scalar bool.
39170   if (Vec.getOpcode() == ISD::VSELECT &&
39171       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
39172       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
39173       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
39174     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
39175     SDLoc DL(ExtElt);
39176     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
39177                                Vec.getOperand(0).getValueType().getScalarType(),
39178                                Vec.getOperand(0), Index);
39179     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
39180                                Vec.getOperand(1), Index);
39181     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
39182                                Vec.getOperand(2), Index);
39183     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
39184   }
39185 
39186   // TODO: This switch could include FNEG and the x86-specific FP logic ops
39187   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
39188   // missed load folding and fma+fneg combining.
39189   switch (Vec.getOpcode()) {
39190   case ISD::FMA: // Begin 3 operands
39191   case ISD::FMAD:
39192   case ISD::FADD: // Begin 2 operands
39193   case ISD::FSUB:
39194   case ISD::FMUL:
39195   case ISD::FDIV:
39196   case ISD::FREM:
39197   case ISD::FCOPYSIGN:
39198   case ISD::FMINNUM:
39199   case ISD::FMAXNUM:
39200   case ISD::FMINNUM_IEEE:
39201   case ISD::FMAXNUM_IEEE:
39202   case ISD::FMAXIMUM:
39203   case ISD::FMINIMUM:
39204   case X86ISD::FMAX:
39205   case X86ISD::FMIN:
39206   case ISD::FABS: // Begin 1 operand
39207   case ISD::FSQRT:
39208   case ISD::FRINT:
39209   case ISD::FCEIL:
39210   case ISD::FTRUNC:
39211   case ISD::FNEARBYINT:
39212   case ISD::FROUND:
39213   case ISD::FFLOOR:
39214   case X86ISD::FRCP:
39215   case X86ISD::FRSQRT: {
39216     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
39217     SDLoc DL(ExtElt);
39218     SmallVector<SDValue, 4> ExtOps;
39219     for (SDValue Op : Vec->ops())
39220       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
39221     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
39222   }
39223   default:
39224     return SDValue();
39225   }
39226   llvm_unreachable("All opcodes should return within switch");
39227 }
39228 
39229 /// Try to convert a vector reduction sequence composed of binops and shuffles
39230 /// into horizontal ops.
combineReductionToHorizontal(SDNode * ExtElt,SelectionDAG & DAG,const X86Subtarget & Subtarget)39231 static SDValue combineReductionToHorizontal(SDNode *ExtElt, SelectionDAG &DAG,
39232                                             const X86Subtarget &Subtarget) {
39233   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
39234 
39235   // We need at least SSE2 to anything here.
39236   if (!Subtarget.hasSSE2())
39237     return SDValue();
39238 
39239   ISD::NodeType Opc;
39240   SDValue Rdx =
39241       DAG.matchBinOpReduction(ExtElt, Opc, {ISD::ADD, ISD::FADD}, true);
39242   if (!Rdx)
39243     return SDValue();
39244 
39245   SDValue Index = ExtElt->getOperand(1);
39246   assert(isNullConstant(Index) &&
39247          "Reduction doesn't end in an extract from index 0");
39248 
39249   EVT VT = ExtElt->getValueType(0);
39250   EVT VecVT = Rdx.getValueType();
39251   if (VecVT.getScalarType() != VT)
39252     return SDValue();
39253 
39254   SDLoc DL(ExtElt);
39255 
39256   // vXi8 reduction - sub 128-bit vector.
39257   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
39258     if (VecVT == MVT::v4i8) {
39259       // Pad with zero.
39260       if (Subtarget.hasSSE41()) {
39261         Rdx = DAG.getBitcast(MVT::i32, Rdx);
39262         Rdx = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
39263                           DAG.getConstant(0, DL, MVT::v4i32), Rdx,
39264                           DAG.getIntPtrConstant(0, DL));
39265         Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
39266       } else {
39267         Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
39268                           DAG.getConstant(0, DL, VecVT));
39269       }
39270     }
39271     if (Rdx.getValueType() == MVT::v8i8) {
39272       // Pad with undef.
39273       Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
39274                         DAG.getUNDEF(MVT::v8i8));
39275     }
39276     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
39277                       DAG.getConstant(0, DL, MVT::v16i8));
39278     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
39279     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
39280   }
39281 
39282   // Must be a >=128-bit vector with pow2 elements.
39283   if ((VecVT.getSizeInBits() % 128) != 0 ||
39284       !isPowerOf2_32(VecVT.getVectorNumElements()))
39285     return SDValue();
39286 
39287   // vXi8 reduction - sum lo/hi halves then use PSADBW.
39288   if (VT == MVT::i8) {
39289     while (Rdx.getValueSizeInBits() > 128) {
39290       SDValue Lo, Hi;
39291       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
39292       VecVT = Lo.getValueType();
39293       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
39294     }
39295     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
39296 
39297     SDValue Hi = DAG.getVectorShuffle(
39298         MVT::v16i8, DL, Rdx, Rdx,
39299         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
39300     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
39301     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
39302                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
39303     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
39304     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
39305   }
39306 
39307   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
39308   if (!shouldUseHorizontalOp(true, DAG, Subtarget))
39309     return SDValue();
39310 
39311   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
39312 
39313   // 256-bit horizontal instructions operate on 128-bit chunks rather than
39314   // across the whole vector, so we need an extract + hop preliminary stage.
39315   // This is the only step where the operands of the hop are not the same value.
39316   // TODO: We could extend this to handle 512-bit or even longer vectors.
39317   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
39318       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
39319     unsigned NumElts = VecVT.getVectorNumElements();
39320     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
39321     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
39322     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
39323     VecVT = Rdx.getValueType();
39324   }
39325   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
39326       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
39327     return SDValue();
39328 
39329   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
39330   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
39331   for (unsigned i = 0; i != ReductionSteps; ++i)
39332     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
39333 
39334   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
39335 }
39336 
39337 /// Detect vector gather/scatter index generation and convert it from being a
39338 /// bunch of shuffles and extracts into a somewhat faster sequence.
39339 /// For i686, the best sequence is apparently storing the value and loading
39340 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
combineExtractVectorElt(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39341 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
39342                                        TargetLowering::DAGCombinerInfo &DCI,
39343                                        const X86Subtarget &Subtarget) {
39344   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
39345     return NewOp;
39346 
39347   SDValue InputVector = N->getOperand(0);
39348   SDValue EltIdx = N->getOperand(1);
39349   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
39350 
39351   EVT SrcVT = InputVector.getValueType();
39352   EVT VT = N->getValueType(0);
39353   SDLoc dl(InputVector);
39354   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
39355   unsigned NumSrcElts = SrcVT.getVectorNumElements();
39356 
39357   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
39358     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
39359 
39360   // Integer Constant Folding.
39361   if (CIdx && VT.isInteger()) {
39362     APInt UndefVecElts;
39363     SmallVector<APInt, 16> EltBits;
39364     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
39365     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
39366                                       EltBits, true, false)) {
39367       uint64_t Idx = CIdx->getZExtValue();
39368       if (UndefVecElts[Idx])
39369         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
39370       return DAG.getConstant(EltBits[Idx].zextOrSelf(VT.getScalarSizeInBits()),
39371                              dl, VT);
39372     }
39373   }
39374 
39375   if (IsPextr) {
39376     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39377     if (TLI.SimplifyDemandedBits(
39378             SDValue(N, 0), APInt::getAllOnesValue(VT.getSizeInBits()), DCI))
39379       return SDValue(N, 0);
39380 
39381     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
39382     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
39383          InputVector.getOpcode() == X86ISD::PINSRW) &&
39384         InputVector.getOperand(2) == EltIdx) {
39385       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
39386              "Vector type mismatch");
39387       SDValue Scl = InputVector.getOperand(1);
39388       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
39389       return DAG.getZExtOrTrunc(Scl, dl, VT);
39390     }
39391 
39392     // TODO - Remove this once we can handle the implicit zero-extension of
39393     // X86ISD::PEXTRW/X86ISD::PEXTRB in combineHorizontalPredicateResult and
39394     // combineBasicSADPattern.
39395     return SDValue();
39396   }
39397 
39398   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
39399   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
39400       VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
39401     SDValue MMXSrc = InputVector.getOperand(0);
39402 
39403     // The bitcast source is a direct mmx result.
39404     if (MMXSrc.getValueType() == MVT::x86mmx)
39405       return DAG.getBitcast(VT, InputVector);
39406   }
39407 
39408   // Detect mmx to i32 conversion through a v2i32 elt extract.
39409   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
39410       VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
39411     SDValue MMXSrc = InputVector.getOperand(0);
39412 
39413     // The bitcast source is a direct mmx result.
39414     if (MMXSrc.getValueType() == MVT::x86mmx)
39415       return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
39416   }
39417 
39418   // Check whether this extract is the root of a sum of absolute differences
39419   // pattern. This has to be done here because we really want it to happen
39420   // pre-legalization,
39421   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
39422     return SAD;
39423 
39424   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
39425   if (SDValue Cmp = combineHorizontalPredicateResult(N, DAG, Subtarget))
39426     return Cmp;
39427 
39428   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
39429   if (SDValue MinMax = combineHorizontalMinMaxResult(N, DAG, Subtarget))
39430     return MinMax;
39431 
39432   if (SDValue V = combineReductionToHorizontal(N, DAG, Subtarget))
39433     return V;
39434 
39435   if (SDValue V = scalarizeExtEltFP(N, DAG))
39436     return V;
39437 
39438   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
39439   // and then testing the relevant element.
39440   //
39441   // Note that we only combine extracts on the *same* result number, i.e.
39442   //   t0 = merge_values a0, a1, a2, a3
39443   //   i1 = extract_vector_elt t0, Constant:i64<2>
39444   //   i1 = extract_vector_elt t0, Constant:i64<3>
39445   // but not
39446   //   i1 = extract_vector_elt t0:1, Constant:i64<2>
39447   // since the latter would need its own MOVMSK.
39448   if (CIdx && SrcVT.getScalarType() == MVT::i1) {
39449     SmallVector<SDNode *, 16> BoolExtracts;
39450     unsigned ResNo = InputVector.getResNo();
39451     auto IsBoolExtract = [&BoolExtracts, &ResNo](SDNode *Use) {
39452       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
39453           isa<ConstantSDNode>(Use->getOperand(1)) &&
39454           Use->getOperand(0).getResNo() == ResNo &&
39455           Use->getValueType(0) == MVT::i1) {
39456         BoolExtracts.push_back(Use);
39457         return true;
39458       }
39459       return false;
39460     };
39461     if (all_of(InputVector->uses(), IsBoolExtract) &&
39462         BoolExtracts.size() > 1) {
39463       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
39464       if (SDValue BC =
39465               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
39466         for (SDNode *Use : BoolExtracts) {
39467           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
39468           unsigned MaskIdx = Use->getConstantOperandVal(1);
39469           APInt MaskBit = APInt::getOneBitSet(NumSrcElts, MaskIdx);
39470           SDValue Mask = DAG.getConstant(MaskBit, dl, BCVT);
39471           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
39472           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
39473           DCI.CombineTo(Use, Res);
39474         }
39475         return SDValue(N, 0);
39476       }
39477     }
39478   }
39479 
39480   return SDValue();
39481 }
39482 
39483 /// If a vector select has an operand that is -1 or 0, try to simplify the
39484 /// select to a bitwise logic operation.
39485 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
39486 static SDValue
combineVSelectWithAllOnesOrZeros(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39487 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
39488                                  TargetLowering::DAGCombinerInfo &DCI,
39489                                  const X86Subtarget &Subtarget) {
39490   SDValue Cond = N->getOperand(0);
39491   SDValue LHS = N->getOperand(1);
39492   SDValue RHS = N->getOperand(2);
39493   EVT VT = LHS.getValueType();
39494   EVT CondVT = Cond.getValueType();
39495   SDLoc DL(N);
39496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39497 
39498   if (N->getOpcode() != ISD::VSELECT)
39499     return SDValue();
39500 
39501   assert(CondVT.isVector() && "Vector select expects a vector selector!");
39502 
39503   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
39504   // TODO: Can we assert that both operands are not zeros (because that should
39505   //       get simplified at node creation time)?
39506   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
39507   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
39508 
39509   // If both inputs are 0/undef, create a complete zero vector.
39510   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
39511   if (TValIsAllZeros && FValIsAllZeros) {
39512     if (VT.isFloatingPoint())
39513       return DAG.getConstantFP(0.0, DL, VT);
39514     return DAG.getConstant(0, DL, VT);
39515   }
39516 
39517   // To use the condition operand as a bitwise mask, it must have elements that
39518   // are the same size as the select elements. Ie, the condition operand must
39519   // have already been promoted from the IR select condition type <N x i1>.
39520   // Don't check if the types themselves are equal because that excludes
39521   // vector floating-point selects.
39522   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
39523     return SDValue();
39524 
39525   // Try to invert the condition if true value is not all 1s and false value is
39526   // not all 0s. Only do this if the condition has one use.
39527   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
39528   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
39529       // Check if the selector will be produced by CMPP*/PCMP*.
39530       Cond.getOpcode() == ISD::SETCC &&
39531       // Check if SETCC has already been promoted.
39532       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
39533           CondVT) {
39534     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
39535 
39536     if (TValIsAllZeros || FValIsAllOnes) {
39537       SDValue CC = Cond.getOperand(2);
39538       ISD::CondCode NewCC = ISD::getSetCCInverse(
39539           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
39540       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
39541                           NewCC);
39542       std::swap(LHS, RHS);
39543       TValIsAllOnes = FValIsAllOnes;
39544       FValIsAllZeros = TValIsAllZeros;
39545     }
39546   }
39547 
39548   // Cond value must be 'sign splat' to be converted to a logical op.
39549   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
39550     return SDValue();
39551 
39552   // vselect Cond, 111..., 000... -> Cond
39553   if (TValIsAllOnes && FValIsAllZeros)
39554     return DAG.getBitcast(VT, Cond);
39555 
39556   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(CondVT))
39557     return SDValue();
39558 
39559   // vselect Cond, 111..., X -> or Cond, X
39560   if (TValIsAllOnes) {
39561     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
39562     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
39563     return DAG.getBitcast(VT, Or);
39564   }
39565 
39566   // vselect Cond, X, 000... -> and Cond, X
39567   if (FValIsAllZeros) {
39568     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
39569     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
39570     return DAG.getBitcast(VT, And);
39571   }
39572 
39573   // vselect Cond, 000..., X -> andn Cond, X
39574   if (TValIsAllZeros) {
39575     MVT AndNVT = MVT::getVectorVT(MVT::i64, CondVT.getSizeInBits() / 64);
39576     SDValue CastCond = DAG.getBitcast(AndNVT, Cond);
39577     SDValue CastRHS = DAG.getBitcast(AndNVT, RHS);
39578     SDValue AndN = DAG.getNode(X86ISD::ANDNP, DL, AndNVT, CastCond, CastRHS);
39579     return DAG.getBitcast(VT, AndN);
39580   }
39581 
39582   return SDValue();
39583 }
39584 
39585 /// If both arms of a vector select are concatenated vectors, split the select,
39586 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
39587 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
39588 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
narrowVectorSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)39589 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
39590                                   const X86Subtarget &Subtarget) {
39591   unsigned Opcode = N->getOpcode();
39592   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
39593     return SDValue();
39594 
39595   // TODO: Split 512-bit vectors too?
39596   EVT VT = N->getValueType(0);
39597   if (!VT.is256BitVector())
39598     return SDValue();
39599 
39600   // TODO: Split as long as any 2 of the 3 operands are concatenated?
39601   SDValue Cond = N->getOperand(0);
39602   SDValue TVal = N->getOperand(1);
39603   SDValue FVal = N->getOperand(2);
39604   SmallVector<SDValue, 4> CatOpsT, CatOpsF;
39605   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
39606       !collectConcatOps(TVal.getNode(), CatOpsT) ||
39607       !collectConcatOps(FVal.getNode(), CatOpsF))
39608     return SDValue();
39609 
39610   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
39611                             ArrayRef<SDValue> Ops) {
39612     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
39613   };
39614   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
39615                           makeBlend, /*CheckBWI*/ false);
39616 }
39617 
combineSelectOfTwoConstants(SDNode * N,SelectionDAG & DAG)39618 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
39619   SDValue Cond = N->getOperand(0);
39620   SDValue LHS = N->getOperand(1);
39621   SDValue RHS = N->getOperand(2);
39622   SDLoc DL(N);
39623 
39624   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
39625   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
39626   if (!TrueC || !FalseC)
39627     return SDValue();
39628 
39629   // Don't do this for crazy integer types.
39630   EVT VT = N->getValueType(0);
39631   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
39632     return SDValue();
39633 
39634   // We're going to use the condition bit in math or logic ops. We could allow
39635   // this with a wider condition value (post-legalization it becomes an i8),
39636   // but if nothing is creating selects that late, it doesn't matter.
39637   if (Cond.getValueType() != MVT::i1)
39638     return SDValue();
39639 
39640   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
39641   // 3, 5, or 9 with i32/i64, so those get transformed too.
39642   // TODO: For constants that overflow or do not differ by power-of-2 or small
39643   // multiplier, convert to 'and' + 'add'.
39644   const APInt &TrueVal = TrueC->getAPIntValue();
39645   const APInt &FalseVal = FalseC->getAPIntValue();
39646   bool OV;
39647   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
39648   if (OV)
39649     return SDValue();
39650 
39651   APInt AbsDiff = Diff.abs();
39652   if (AbsDiff.isPowerOf2() ||
39653       ((VT == MVT::i32 || VT == MVT::i64) &&
39654        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
39655 
39656     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
39657     // of the condition can usually be folded into a compare predicate, but even
39658     // without that, the sequence should be cheaper than a CMOV alternative.
39659     if (TrueVal.slt(FalseVal)) {
39660       Cond = DAG.getNOT(DL, Cond, MVT::i1);
39661       std::swap(TrueC, FalseC);
39662     }
39663 
39664     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
39665     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
39666 
39667     // Multiply condition by the difference if non-one.
39668     if (!AbsDiff.isOneValue())
39669       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
39670 
39671     // Add the base if non-zero.
39672     if (!FalseC->isNullValue())
39673       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
39674 
39675     return R;
39676   }
39677 
39678   return SDValue();
39679 }
39680 
39681 /// If this is a *dynamic* select (non-constant condition) and we can match
39682 /// this node with one of the variable blend instructions, restructure the
39683 /// condition so that blends can use the high (sign) bit of each element.
39684 /// This function will also call SimplifyDemandedBits on already created
39685 /// BLENDV to perform additional simplifications.
combineVSelectToBLENDV(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39686 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
39687                                            TargetLowering::DAGCombinerInfo &DCI,
39688                                            const X86Subtarget &Subtarget) {
39689   SDValue Cond = N->getOperand(0);
39690   if ((N->getOpcode() != ISD::VSELECT &&
39691        N->getOpcode() != X86ISD::BLENDV) ||
39692       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
39693     return SDValue();
39694 
39695   // Don't optimize before the condition has been transformed to a legal type
39696   // and don't ever optimize vector selects that map to AVX512 mask-registers.
39697   unsigned BitWidth = Cond.getScalarValueSizeInBits();
39698   if (BitWidth < 8 || BitWidth > 64)
39699     return SDValue();
39700 
39701   // We can only handle the cases where VSELECT is directly legal on the
39702   // subtarget. We custom lower VSELECT nodes with constant conditions and
39703   // this makes it hard to see whether a dynamic VSELECT will correctly
39704   // lower, so we both check the operation's status and explicitly handle the
39705   // cases where a *dynamic* blend will fail even though a constant-condition
39706   // blend could be custom lowered.
39707   // FIXME: We should find a better way to handle this class of problems.
39708   // Potentially, we should combine constant-condition vselect nodes
39709   // pre-legalization into shuffles and not mark as many types as custom
39710   // lowered.
39711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39712   EVT VT = N->getValueType(0);
39713   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
39714     return SDValue();
39715   // FIXME: We don't support i16-element blends currently. We could and
39716   // should support them by making *all* the bits in the condition be set
39717   // rather than just the high bit and using an i8-element blend.
39718   if (VT.getVectorElementType() == MVT::i16)
39719     return SDValue();
39720   // Dynamic blending was only available from SSE4.1 onward.
39721   if (VT.is128BitVector() && !Subtarget.hasSSE41())
39722     return SDValue();
39723   // Byte blends are only available in AVX2
39724   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
39725     return SDValue();
39726   // There are no 512-bit blend instructions that use sign bits.
39727   if (VT.is512BitVector())
39728     return SDValue();
39729 
39730   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
39731     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
39732          UI != UE; ++UI)
39733       if ((UI->getOpcode() != ISD::VSELECT &&
39734            UI->getOpcode() != X86ISD::BLENDV) ||
39735           UI.getOperandNo() != 0)
39736         return false;
39737 
39738     return true;
39739   };
39740 
39741   APInt DemandedBits(APInt::getSignMask(BitWidth));
39742 
39743   if (OnlyUsedAsSelectCond(Cond)) {
39744     KnownBits Known;
39745     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
39746                                           !DCI.isBeforeLegalizeOps());
39747     if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
39748       return SDValue();
39749 
39750     // If we changed the computation somewhere in the DAG, this change will
39751     // affect all users of Cond. Update all the nodes so that we do not use
39752     // the generic VSELECT anymore. Otherwise, we may perform wrong
39753     // optimizations as we messed with the actual expectation for the vector
39754     // boolean values.
39755     for (SDNode *U : Cond->uses()) {
39756       if (U->getOpcode() == X86ISD::BLENDV)
39757         continue;
39758 
39759       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
39760                                Cond, U->getOperand(1), U->getOperand(2));
39761       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
39762       DCI.AddToWorklist(U);
39763     }
39764     DCI.CommitTargetLoweringOpt(TLO);
39765     return SDValue(N, 0);
39766   }
39767 
39768   // Otherwise we can still at least try to simplify multiple use bits.
39769   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
39770       return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
39771                          N->getOperand(1), N->getOperand(2));
39772 
39773   return SDValue();
39774 }
39775 
39776 // Try to match:
39777 //   (or (and (M, (sub 0, X)), (pandn M, X)))
39778 // which is a special case of:
39779 //   (select M, (sub 0, X), X)
39780 // Per:
39781 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
39782 // We know that, if fNegate is 0 or 1:
39783 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
39784 //
39785 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
39786 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
39787 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
39788 // This lets us transform our vselect to:
39789 //   (add (xor X, M), (and M, 1))
39790 // And further to:
39791 //   (sub (xor X, M), M)
combineLogicBlendIntoConditionalNegate(EVT VT,SDValue Mask,SDValue X,SDValue Y,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)39792 static SDValue combineLogicBlendIntoConditionalNegate(
39793     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
39794     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
39795   EVT MaskVT = Mask.getValueType();
39796   assert(MaskVT.isInteger() &&
39797          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
39798          "Mask must be zero/all-bits");
39799 
39800   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
39801     return SDValue();
39802   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
39803     return SDValue();
39804 
39805   auto IsNegV = [](SDNode *N, SDValue V) {
39806     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
39807            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
39808   };
39809 
39810   SDValue V;
39811   if (IsNegV(Y.getNode(), X))
39812     V = X;
39813   else if (IsNegV(X.getNode(), Y))
39814     V = Y;
39815   else
39816     return SDValue();
39817 
39818   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
39819   SDValue SubOp2 = Mask;
39820 
39821   // If the negate was on the false side of the select, then
39822   // the operands of the SUB need to be swapped. PR 27251.
39823   // This is because the pattern being matched above is
39824   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
39825   // but if the pattern matched was
39826   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
39827   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
39828   // pattern also needs to be a negation of the replacement pattern above.
39829   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
39830   // sub accomplishes the negation of the replacement pattern.
39831   if (V == Y)
39832     std::swap(SubOp1, SubOp2);
39833 
39834   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
39835   return DAG.getBitcast(VT, Res);
39836 }
39837 
39838 /// Do target-specific dag combines on SELECT and VSELECT nodes.
combineSelect(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)39839 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
39840                              TargetLowering::DAGCombinerInfo &DCI,
39841                              const X86Subtarget &Subtarget) {
39842   SDLoc DL(N);
39843   SDValue Cond = N->getOperand(0);
39844   SDValue LHS = N->getOperand(1);
39845   SDValue RHS = N->getOperand(2);
39846 
39847   // Try simplification again because we use this function to optimize
39848   // BLENDV nodes that are not handled by the generic combiner.
39849   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
39850     return V;
39851 
39852   EVT VT = LHS.getValueType();
39853   EVT CondVT = Cond.getValueType();
39854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39855   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
39856 
39857   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
39858   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
39859   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
39860   if (CondVT.isVector() && CondVT.isInteger() &&
39861       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
39862       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
39863       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
39864     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
39865                                                            DL, DAG, Subtarget))
39866       return V;
39867 
39868   // Convert vselects with constant condition into shuffles.
39869   if (CondConstantVector && DCI.isBeforeLegalizeOps()) {
39870     SmallVector<int, 64> Mask;
39871     if (createShuffleMaskFromVSELECT(Mask, Cond))
39872       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
39873   }
39874 
39875   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
39876   // instructions match the semantics of the common C idiom x<y?x:y but not
39877   // x<=y?x:y, because of how they handle negative zero (which can be
39878   // ignored in unsafe-math mode).
39879   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
39880   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
39881       VT != MVT::f80 && VT != MVT::f128 &&
39882       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
39883       (Subtarget.hasSSE2() ||
39884        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
39885     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
39886 
39887     unsigned Opcode = 0;
39888     // Check for x CC y ? x : y.
39889     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
39890         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
39891       switch (CC) {
39892       default: break;
39893       case ISD::SETULT:
39894         // Converting this to a min would handle NaNs incorrectly, and swapping
39895         // the operands would cause it to handle comparisons between positive
39896         // and negative zero incorrectly.
39897         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
39898           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
39899               !(DAG.isKnownNeverZeroFloat(LHS) ||
39900                 DAG.isKnownNeverZeroFloat(RHS)))
39901             break;
39902           std::swap(LHS, RHS);
39903         }
39904         Opcode = X86ISD::FMIN;
39905         break;
39906       case ISD::SETOLE:
39907         // Converting this to a min would handle comparisons between positive
39908         // and negative zero incorrectly.
39909         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
39910             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
39911           break;
39912         Opcode = X86ISD::FMIN;
39913         break;
39914       case ISD::SETULE:
39915         // Converting this to a min would handle both negative zeros and NaNs
39916         // incorrectly, but we can swap the operands to fix both.
39917         std::swap(LHS, RHS);
39918         LLVM_FALLTHROUGH;
39919       case ISD::SETOLT:
39920       case ISD::SETLT:
39921       case ISD::SETLE:
39922         Opcode = X86ISD::FMIN;
39923         break;
39924 
39925       case ISD::SETOGE:
39926         // Converting this to a max would handle comparisons between positive
39927         // and negative zero incorrectly.
39928         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
39929             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
39930           break;
39931         Opcode = X86ISD::FMAX;
39932         break;
39933       case ISD::SETUGT:
39934         // Converting this to a max would handle NaNs incorrectly, and swapping
39935         // the operands would cause it to handle comparisons between positive
39936         // and negative zero incorrectly.
39937         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
39938           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
39939               !(DAG.isKnownNeverZeroFloat(LHS) ||
39940                 DAG.isKnownNeverZeroFloat(RHS)))
39941             break;
39942           std::swap(LHS, RHS);
39943         }
39944         Opcode = X86ISD::FMAX;
39945         break;
39946       case ISD::SETUGE:
39947         // Converting this to a max would handle both negative zeros and NaNs
39948         // incorrectly, but we can swap the operands to fix both.
39949         std::swap(LHS, RHS);
39950         LLVM_FALLTHROUGH;
39951       case ISD::SETOGT:
39952       case ISD::SETGT:
39953       case ISD::SETGE:
39954         Opcode = X86ISD::FMAX;
39955         break;
39956       }
39957     // Check for x CC y ? y : x -- a min/max with reversed arms.
39958     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
39959                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
39960       switch (CC) {
39961       default: break;
39962       case ISD::SETOGE:
39963         // Converting this to a min would handle comparisons between positive
39964         // and negative zero incorrectly, and swapping the operands would
39965         // cause it to handle NaNs incorrectly.
39966         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
39967             !(DAG.isKnownNeverZeroFloat(LHS) ||
39968               DAG.isKnownNeverZeroFloat(RHS))) {
39969           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
39970             break;
39971           std::swap(LHS, RHS);
39972         }
39973         Opcode = X86ISD::FMIN;
39974         break;
39975       case ISD::SETUGT:
39976         // Converting this to a min would handle NaNs incorrectly.
39977         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
39978           break;
39979         Opcode = X86ISD::FMIN;
39980         break;
39981       case ISD::SETUGE:
39982         // Converting this to a min would handle both negative zeros and NaNs
39983         // incorrectly, but we can swap the operands to fix both.
39984         std::swap(LHS, RHS);
39985         LLVM_FALLTHROUGH;
39986       case ISD::SETOGT:
39987       case ISD::SETGT:
39988       case ISD::SETGE:
39989         Opcode = X86ISD::FMIN;
39990         break;
39991 
39992       case ISD::SETULT:
39993         // Converting this to a max would handle NaNs incorrectly.
39994         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
39995           break;
39996         Opcode = X86ISD::FMAX;
39997         break;
39998       case ISD::SETOLE:
39999         // Converting this to a max would handle comparisons between positive
40000         // and negative zero incorrectly, and swapping the operands would
40001         // cause it to handle NaNs incorrectly.
40002         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
40003             !DAG.isKnownNeverZeroFloat(LHS) &&
40004             !DAG.isKnownNeverZeroFloat(RHS)) {
40005           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
40006             break;
40007           std::swap(LHS, RHS);
40008         }
40009         Opcode = X86ISD::FMAX;
40010         break;
40011       case ISD::SETULE:
40012         // Converting this to a max would handle both negative zeros and NaNs
40013         // incorrectly, but we can swap the operands to fix both.
40014         std::swap(LHS, RHS);
40015         LLVM_FALLTHROUGH;
40016       case ISD::SETOLT:
40017       case ISD::SETLT:
40018       case ISD::SETLE:
40019         Opcode = X86ISD::FMAX;
40020         break;
40021       }
40022     }
40023 
40024     if (Opcode)
40025       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
40026   }
40027 
40028   // Some mask scalar intrinsics rely on checking if only one bit is set
40029   // and implement it in C code like this:
40030   // A[0] = (U & 1) ? A[0] : W[0];
40031   // This creates some redundant instructions that break pattern matching.
40032   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
40033   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
40034       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
40035     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
40036     SDValue AndNode = Cond.getOperand(0);
40037     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
40038         isNullConstant(Cond.getOperand(1)) &&
40039         isOneConstant(AndNode.getOperand(1))) {
40040       // LHS and RHS swapped due to
40041       // setcc outputting 1 when AND resulted in 0 and vice versa.
40042       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
40043       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
40044     }
40045   }
40046 
40047   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
40048   // lowering on KNL. In this case we convert it to
40049   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
40050   // The same situation all vectors of i8 and i16 without BWI.
40051   // Make sure we extend these even before type legalization gets a chance to
40052   // split wide vectors.
40053   // Since SKX these selects have a proper lowering.
40054   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
40055       CondVT.getVectorElementType() == MVT::i1 &&
40056       (VT.getVectorElementType() == MVT::i8 ||
40057        VT.getVectorElementType() == MVT::i16)) {
40058     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
40059     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
40060   }
40061 
40062   // AVX512 - Extend select with zero to merge with target shuffle.
40063   // select(mask, extract_subvector(shuffle(x)), zero) -->
40064   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
40065   // TODO - support non target shuffles as well.
40066   if (Subtarget.hasAVX512() && CondVT.isVector() &&
40067       CondVT.getVectorElementType() == MVT::i1) {
40068     auto SelectableOp = [&TLI](SDValue Op) {
40069       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40070              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
40071              isNullConstant(Op.getOperand(1)) &&
40072              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
40073              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
40074     };
40075 
40076     bool SelectableLHS = SelectableOp(LHS);
40077     bool SelectableRHS = SelectableOp(RHS);
40078     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
40079     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
40080 
40081     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
40082       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
40083                                 : RHS.getOperand(0).getValueType();
40084       unsigned NumSrcElts = SrcVT.getVectorNumElements();
40085       EVT SrcCondVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumSrcElts);
40086       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
40087                             VT.getSizeInBits());
40088       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
40089                             VT.getSizeInBits());
40090       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
40091                          DAG.getUNDEF(SrcCondVT), Cond,
40092                          DAG.getIntPtrConstant(0, DL));
40093       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
40094       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
40095     }
40096   }
40097 
40098   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
40099     return V;
40100 
40101   // Canonicalize max and min:
40102   // (x > y) ? x : y -> (x >= y) ? x : y
40103   // (x < y) ? x : y -> (x <= y) ? x : y
40104   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
40105   // the need for an extra compare
40106   // against zero. e.g.
40107   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
40108   // subl   %esi, %edi
40109   // testl  %edi, %edi
40110   // movl   $0, %eax
40111   // cmovgl %edi, %eax
40112   // =>
40113   // xorl   %eax, %eax
40114   // subl   %esi, $edi
40115   // cmovsl %eax, %edi
40116   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
40117       Cond.hasOneUse() &&
40118       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
40119       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
40120     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
40121     switch (CC) {
40122     default: break;
40123     case ISD::SETLT:
40124     case ISD::SETGT: {
40125       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
40126       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
40127                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
40128       return DAG.getSelect(DL, VT, Cond, LHS, RHS);
40129     }
40130     }
40131   }
40132 
40133   // Match VSELECTs into subs with unsigned saturation.
40134   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
40135       // psubus is available in SSE2 for i8 and i16 vectors.
40136       Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
40137       isPowerOf2_32(VT.getVectorNumElements()) &&
40138       (VT.getVectorElementType() == MVT::i8 ||
40139        VT.getVectorElementType() == MVT::i16)) {
40140     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
40141 
40142     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
40143     // left side invert the predicate to simplify logic below.
40144     SDValue Other;
40145     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
40146       Other = RHS;
40147       CC = ISD::getSetCCInverse(CC, VT.getVectorElementType());
40148     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
40149       Other = LHS;
40150     }
40151 
40152     if (Other.getNode() && Other->getNumOperands() == 2 &&
40153         Other->getOperand(0) == Cond.getOperand(0)) {
40154       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
40155       SDValue CondRHS = Cond->getOperand(1);
40156 
40157       // Look for a general sub with unsigned saturation first.
40158       // x >= y ? x-y : 0 --> subus x, y
40159       // x >  y ? x-y : 0 --> subus x, y
40160       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
40161           Other->getOpcode() == ISD::SUB && OpRHS == CondRHS)
40162         return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
40163 
40164       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) {
40165         if (isa<BuildVectorSDNode>(CondRHS)) {
40166           // If the RHS is a constant we have to reverse the const
40167           // canonicalization.
40168           // x > C-1 ? x+-C : 0 --> subus x, C
40169           auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
40170             return (!Op && !Cond) ||
40171                    (Op && Cond &&
40172                     Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
40173           };
40174           if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
40175               ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
40176                                         /*AllowUndefs*/ true)) {
40177             OpRHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
40178                                 OpRHS);
40179             return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
40180           }
40181 
40182           // Another special case: If C was a sign bit, the sub has been
40183           // canonicalized into a xor.
40184           // FIXME: Would it be better to use computeKnownBits to determine
40185           //        whether it's safe to decanonicalize the xor?
40186           // x s< 0 ? x^C : 0 --> subus x, C
40187           if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
40188             if (CC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
40189                 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
40190                 OpRHSConst->getAPIntValue().isSignMask()) {
40191               // Note that we have to rebuild the RHS constant here to ensure we
40192               // don't rely on particular values of undef lanes.
40193               OpRHS = DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT);
40194               return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
40195             }
40196           }
40197         }
40198       }
40199     }
40200   }
40201 
40202   // Match VSELECTs into add with unsigned saturation.
40203   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
40204       // paddus is available in SSE2 for i8 and i16 vectors.
40205       Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
40206       isPowerOf2_32(VT.getVectorNumElements()) &&
40207       (VT.getVectorElementType() == MVT::i8 ||
40208        VT.getVectorElementType() == MVT::i16)) {
40209     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
40210 
40211     SDValue CondLHS = Cond->getOperand(0);
40212     SDValue CondRHS = Cond->getOperand(1);
40213 
40214     // Check if one of the arms of the VSELECT is vector with all bits set.
40215     // If it's on the left side invert the predicate to simplify logic below.
40216     SDValue Other;
40217     if (ISD::isBuildVectorAllOnes(LHS.getNode())) {
40218       Other = RHS;
40219       CC = ISD::getSetCCInverse(CC, VT.getVectorElementType());
40220     } else if (ISD::isBuildVectorAllOnes(RHS.getNode())) {
40221       Other = LHS;
40222     }
40223 
40224     if (Other.getNode() && Other.getOpcode() == ISD::ADD) {
40225       SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
40226 
40227       // Canonicalize condition operands.
40228       if (CC == ISD::SETUGE) {
40229         std::swap(CondLHS, CondRHS);
40230         CC = ISD::SETULE;
40231       }
40232 
40233       // We can test against either of the addition operands.
40234       // x <= x+y ? x+y : ~0 --> addus x, y
40235       // x+y >= x ? x+y : ~0 --> addus x, y
40236       if (CC == ISD::SETULE && Other == CondRHS &&
40237           (OpLHS == CondLHS || OpRHS == CondLHS))
40238         return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
40239 
40240       if (isa<BuildVectorSDNode>(OpRHS) && isa<BuildVectorSDNode>(CondRHS) &&
40241           CondLHS == OpLHS) {
40242         // If the RHS is a constant we have to reverse the const
40243         // canonicalization.
40244         // x > ~C ? x+C : ~0 --> addus x, C
40245         auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
40246           return Cond->getAPIntValue() == ~Op->getAPIntValue();
40247         };
40248         if (CC == ISD::SETULE &&
40249             ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
40250           return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
40251       }
40252     }
40253   }
40254 
40255   // Check if the first operand is all zeros and Cond type is vXi1.
40256   // If this an avx512 target we can improve the use of zero masking by
40257   // swapping the operands and inverting the condition.
40258   if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
40259        Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
40260       ISD::isBuildVectorAllZeros(LHS.getNode()) &&
40261       !ISD::isBuildVectorAllZeros(RHS.getNode())) {
40262     // Invert the cond to not(cond) : xor(op,allones)=not(op)
40263     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
40264     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
40265     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
40266   }
40267 
40268   // Early exit check
40269   if (!TLI.isTypeLegal(VT))
40270     return SDValue();
40271 
40272   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
40273     return V;
40274 
40275   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
40276     return V;
40277 
40278   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
40279     return V;
40280 
40281   // select(~Cond, X, Y) -> select(Cond, Y, X)
40282   if (CondVT.getScalarType() != MVT::i1)
40283     if (SDValue CondNot = IsNOT(Cond, DAG))
40284       return DAG.getNode(N->getOpcode(), DL, VT,
40285                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
40286 
40287   // Try to optimize vXi1 selects if both operands are either all constants or
40288   // bitcasts from scalar integer type. In that case we can convert the operands
40289   // to integer and use an integer select which will be converted to a CMOV.
40290   // We need to take a little bit of care to avoid creating an i64 type after
40291   // type legalization.
40292   if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
40293       VT.getVectorElementType() == MVT::i1 &&
40294       (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
40295     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
40296     bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
40297     bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
40298 
40299     if ((LHSIsConst ||
40300          (LHS.getOpcode() == ISD::BITCAST &&
40301           LHS.getOperand(0).getValueType() == IntVT)) &&
40302         (RHSIsConst ||
40303          (RHS.getOpcode() == ISD::BITCAST &&
40304           RHS.getOperand(0).getValueType() == IntVT))) {
40305       if (LHSIsConst)
40306         LHS = combinevXi1ConstantToInteger(LHS, DAG);
40307       else
40308         LHS = LHS.getOperand(0);
40309 
40310       if (RHSIsConst)
40311         RHS = combinevXi1ConstantToInteger(RHS, DAG);
40312       else
40313         RHS = RHS.getOperand(0);
40314 
40315       SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
40316       return DAG.getBitcast(VT, Select);
40317     }
40318   }
40319 
40320   // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
40321   // single bits, then invert the predicate and swap the select operands.
40322   // This can lower using a vector shift bit-hack rather than mask and compare.
40323   if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
40324       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
40325       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
40326       Cond.getOperand(0).getOpcode() == ISD::AND &&
40327       isNullOrNullSplat(Cond.getOperand(1)) &&
40328       cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
40329       Cond.getOperand(0).getValueType() == VT) {
40330     // The 'and' mask must be composed of power-of-2 constants.
40331     SDValue And = Cond.getOperand(0);
40332     auto *C = isConstOrConstSplat(And.getOperand(1));
40333     if (C && C->getAPIntValue().isPowerOf2()) {
40334       // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
40335       SDValue NotCond =
40336           DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
40337       return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
40338     }
40339 
40340     // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
40341     // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
40342     // 16-bit lacks a proper blendv.
40343     unsigned EltBitWidth = VT.getScalarSizeInBits();
40344     bool CanShiftBlend =
40345         TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
40346                                 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
40347                                 (Subtarget.hasXOP()));
40348     if (CanShiftBlend &&
40349         ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
40350           return C->getAPIntValue().isPowerOf2();
40351         })) {
40352       // Create a left-shift constant to get the mask bits over to the sign-bit.
40353       SDValue Mask = And.getOperand(1);
40354       SmallVector<int, 32> ShlVals;
40355       for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
40356         auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
40357         ShlVals.push_back(EltBitWidth - 1 -
40358                           MaskVal->getAPIntValue().exactLogBase2());
40359       }
40360       // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
40361       SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
40362       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
40363       SDValue NewCond =
40364           DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
40365       return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
40366     }
40367   }
40368 
40369   return SDValue();
40370 }
40371 
40372 /// Combine:
40373 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
40374 /// to:
40375 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
40376 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
40377 /// Note that this is only legal for some op/cc combinations.
combineSetCCAtomicArith(SDValue Cmp,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)40378 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
40379                                        SelectionDAG &DAG,
40380                                        const X86Subtarget &Subtarget) {
40381   // This combine only operates on CMP-like nodes.
40382   if (!(Cmp.getOpcode() == X86ISD::CMP ||
40383         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
40384     return SDValue();
40385 
40386   // Can't replace the cmp if it has more uses than the one we're looking at.
40387   // FIXME: We would like to be able to handle this, but would need to make sure
40388   // all uses were updated.
40389   if (!Cmp.hasOneUse())
40390     return SDValue();
40391 
40392   // This only applies to variations of the common case:
40393   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
40394   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
40395   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
40396   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
40397   // Using the proper condcodes (see below), overflow is checked for.
40398 
40399   // FIXME: We can generalize both constraints:
40400   // - XOR/OR/AND (if they were made to survive AtomicExpand)
40401   // - LHS != 1
40402   // if the result is compared.
40403 
40404   SDValue CmpLHS = Cmp.getOperand(0);
40405   SDValue CmpRHS = Cmp.getOperand(1);
40406 
40407   if (!CmpLHS.hasOneUse())
40408     return SDValue();
40409 
40410   unsigned Opc = CmpLHS.getOpcode();
40411   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
40412     return SDValue();
40413 
40414   SDValue OpRHS = CmpLHS.getOperand(2);
40415   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
40416   if (!OpRHSC)
40417     return SDValue();
40418 
40419   APInt Addend = OpRHSC->getAPIntValue();
40420   if (Opc == ISD::ATOMIC_LOAD_SUB)
40421     Addend = -Addend;
40422 
40423   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
40424   if (!CmpRHSC)
40425     return SDValue();
40426 
40427   APInt Comparison = CmpRHSC->getAPIntValue();
40428 
40429   // If the addend is the negation of the comparison value, then we can do
40430   // a full comparison by emitting the atomic arithmetic as a locked sub.
40431   if (Comparison == -Addend) {
40432     // The CC is fine, but we need to rewrite the LHS of the comparison as an
40433     // atomic sub.
40434     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
40435     auto AtomicSub = DAG.getAtomic(
40436         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpLHS.getValueType(),
40437         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
40438         /*RHS*/ DAG.getConstant(-Addend, SDLoc(CmpRHS), CmpRHS.getValueType()),
40439         AN->getMemOperand());
40440     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
40441     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
40442                                   DAG.getUNDEF(CmpLHS.getValueType()));
40443     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
40444     return LockOp;
40445   }
40446 
40447   // We can handle comparisons with zero in a number of cases by manipulating
40448   // the CC used.
40449   if (!Comparison.isNullValue())
40450     return SDValue();
40451 
40452   if (CC == X86::COND_S && Addend == 1)
40453     CC = X86::COND_LE;
40454   else if (CC == X86::COND_NS && Addend == 1)
40455     CC = X86::COND_G;
40456   else if (CC == X86::COND_G && Addend == -1)
40457     CC = X86::COND_GE;
40458   else if (CC == X86::COND_LE && Addend == -1)
40459     CC = X86::COND_L;
40460   else
40461     return SDValue();
40462 
40463   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
40464   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
40465                                 DAG.getUNDEF(CmpLHS.getValueType()));
40466   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
40467   return LockOp;
40468 }
40469 
40470 // Check whether a boolean test is testing a boolean value generated by
40471 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
40472 // code.
40473 //
40474 // Simplify the following patterns:
40475 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
40476 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
40477 // to (Op EFLAGS Cond)
40478 //
40479 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
40480 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
40481 // to (Op EFLAGS !Cond)
40482 //
40483 // where Op could be BRCOND or CMOV.
40484 //
checkBoolTestSetCCCombine(SDValue Cmp,X86::CondCode & CC)40485 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
40486   // This combine only operates on CMP-like nodes.
40487   if (!(Cmp.getOpcode() == X86ISD::CMP ||
40488         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
40489     return SDValue();
40490 
40491   // Quit if not used as a boolean value.
40492   if (CC != X86::COND_E && CC != X86::COND_NE)
40493     return SDValue();
40494 
40495   // Check CMP operands. One of them should be 0 or 1 and the other should be
40496   // an SetCC or extended from it.
40497   SDValue Op1 = Cmp.getOperand(0);
40498   SDValue Op2 = Cmp.getOperand(1);
40499 
40500   SDValue SetCC;
40501   const ConstantSDNode* C = nullptr;
40502   bool needOppositeCond = (CC == X86::COND_E);
40503   bool checkAgainstTrue = false; // Is it a comparison against 1?
40504 
40505   if ((C = dyn_cast<ConstantSDNode>(Op1)))
40506     SetCC = Op2;
40507   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
40508     SetCC = Op1;
40509   else // Quit if all operands are not constants.
40510     return SDValue();
40511 
40512   if (C->getZExtValue() == 1) {
40513     needOppositeCond = !needOppositeCond;
40514     checkAgainstTrue = true;
40515   } else if (C->getZExtValue() != 0)
40516     // Quit if the constant is neither 0 or 1.
40517     return SDValue();
40518 
40519   bool truncatedToBoolWithAnd = false;
40520   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
40521   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
40522          SetCC.getOpcode() == ISD::TRUNCATE ||
40523          SetCC.getOpcode() == ISD::AND) {
40524     if (SetCC.getOpcode() == ISD::AND) {
40525       int OpIdx = -1;
40526       if (isOneConstant(SetCC.getOperand(0)))
40527         OpIdx = 1;
40528       if (isOneConstant(SetCC.getOperand(1)))
40529         OpIdx = 0;
40530       if (OpIdx < 0)
40531         break;
40532       SetCC = SetCC.getOperand(OpIdx);
40533       truncatedToBoolWithAnd = true;
40534     } else
40535       SetCC = SetCC.getOperand(0);
40536   }
40537 
40538   switch (SetCC.getOpcode()) {
40539   case X86ISD::SETCC_CARRY:
40540     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
40541     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
40542     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
40543     // truncated to i1 using 'and'.
40544     if (checkAgainstTrue && !truncatedToBoolWithAnd)
40545       break;
40546     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
40547            "Invalid use of SETCC_CARRY!");
40548     LLVM_FALLTHROUGH;
40549   case X86ISD::SETCC:
40550     // Set the condition code or opposite one if necessary.
40551     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
40552     if (needOppositeCond)
40553       CC = X86::GetOppositeBranchCondition(CC);
40554     return SetCC.getOperand(1);
40555   case X86ISD::CMOV: {
40556     // Check whether false/true value has canonical one, i.e. 0 or 1.
40557     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
40558     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
40559     // Quit if true value is not a constant.
40560     if (!TVal)
40561       return SDValue();
40562     // Quit if false value is not a constant.
40563     if (!FVal) {
40564       SDValue Op = SetCC.getOperand(0);
40565       // Skip 'zext' or 'trunc' node.
40566       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
40567           Op.getOpcode() == ISD::TRUNCATE)
40568         Op = Op.getOperand(0);
40569       // A special case for rdrand/rdseed, where 0 is set if false cond is
40570       // found.
40571       if ((Op.getOpcode() != X86ISD::RDRAND &&
40572            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
40573         return SDValue();
40574     }
40575     // Quit if false value is not the constant 0 or 1.
40576     bool FValIsFalse = true;
40577     if (FVal && FVal->getZExtValue() != 0) {
40578       if (FVal->getZExtValue() != 1)
40579         return SDValue();
40580       // If FVal is 1, opposite cond is needed.
40581       needOppositeCond = !needOppositeCond;
40582       FValIsFalse = false;
40583     }
40584     // Quit if TVal is not the constant opposite of FVal.
40585     if (FValIsFalse && TVal->getZExtValue() != 1)
40586       return SDValue();
40587     if (!FValIsFalse && TVal->getZExtValue() != 0)
40588       return SDValue();
40589     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
40590     if (needOppositeCond)
40591       CC = X86::GetOppositeBranchCondition(CC);
40592     return SetCC.getOperand(3);
40593   }
40594   }
40595 
40596   return SDValue();
40597 }
40598 
40599 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
40600 /// Match:
40601 ///   (X86or (X86setcc) (X86setcc))
40602 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
checkBoolTestAndOrSetCCCombine(SDValue Cond,X86::CondCode & CC0,X86::CondCode & CC1,SDValue & Flags,bool & isAnd)40603 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
40604                                            X86::CondCode &CC1, SDValue &Flags,
40605                                            bool &isAnd) {
40606   if (Cond->getOpcode() == X86ISD::CMP) {
40607     if (!isNullConstant(Cond->getOperand(1)))
40608       return false;
40609 
40610     Cond = Cond->getOperand(0);
40611   }
40612 
40613   isAnd = false;
40614 
40615   SDValue SetCC0, SetCC1;
40616   switch (Cond->getOpcode()) {
40617   default: return false;
40618   case ISD::AND:
40619   case X86ISD::AND:
40620     isAnd = true;
40621     LLVM_FALLTHROUGH;
40622   case ISD::OR:
40623   case X86ISD::OR:
40624     SetCC0 = Cond->getOperand(0);
40625     SetCC1 = Cond->getOperand(1);
40626     break;
40627   };
40628 
40629   // Make sure we have SETCC nodes, using the same flags value.
40630   if (SetCC0.getOpcode() != X86ISD::SETCC ||
40631       SetCC1.getOpcode() != X86ISD::SETCC ||
40632       SetCC0->getOperand(1) != SetCC1->getOperand(1))
40633     return false;
40634 
40635   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
40636   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
40637   Flags = SetCC0->getOperand(1);
40638   return true;
40639 }
40640 
40641 // When legalizing carry, we create carries via add X, -1
40642 // If that comes from an actual carry, via setcc, we use the
40643 // carry directly.
combineCarryThroughADD(SDValue EFLAGS,SelectionDAG & DAG)40644 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
40645   if (EFLAGS.getOpcode() == X86ISD::ADD) {
40646     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
40647       SDValue Carry = EFLAGS.getOperand(0);
40648       while (Carry.getOpcode() == ISD::TRUNCATE ||
40649              Carry.getOpcode() == ISD::ZERO_EXTEND ||
40650              Carry.getOpcode() == ISD::SIGN_EXTEND ||
40651              Carry.getOpcode() == ISD::ANY_EXTEND ||
40652              (Carry.getOpcode() == ISD::AND &&
40653               isOneConstant(Carry.getOperand(1))))
40654         Carry = Carry.getOperand(0);
40655       if (Carry.getOpcode() == X86ISD::SETCC ||
40656           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
40657         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
40658         uint64_t CarryCC = Carry.getConstantOperandVal(0);
40659         SDValue CarryOp1 = Carry.getOperand(1);
40660         if (CarryCC == X86::COND_B)
40661           return CarryOp1;
40662         if (CarryCC == X86::COND_A) {
40663           // Try to convert COND_A into COND_B in an attempt to facilitate
40664           // materializing "setb reg".
40665           //
40666           // Do not flip "e > c", where "c" is a constant, because Cmp
40667           // instruction cannot take an immediate as its first operand.
40668           //
40669           if (CarryOp1.getOpcode() == X86ISD::SUB &&
40670               CarryOp1.getNode()->hasOneUse() &&
40671               CarryOp1.getValueType().isInteger() &&
40672               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
40673             SDValue SubCommute =
40674                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
40675                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
40676             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
40677           }
40678         }
40679         // If this is a check of the z flag of an add with 1, switch to the
40680         // C flag.
40681         if (CarryCC == X86::COND_E &&
40682             CarryOp1.getOpcode() == X86ISD::ADD &&
40683             isOneConstant(CarryOp1.getOperand(1)))
40684           return CarryOp1;
40685       }
40686     }
40687   }
40688 
40689   return SDValue();
40690 }
40691 
40692 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
40693 /// to avoid the inversion.
combinePTESTCC(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)40694 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
40695                               SelectionDAG &DAG,
40696                               const X86Subtarget &Subtarget) {
40697   // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
40698   if (EFLAGS.getOpcode() != X86ISD::PTEST &&
40699       EFLAGS.getOpcode() != X86ISD::TESTP)
40700     return SDValue();
40701 
40702   // PTEST/TESTP sets EFLAGS as:
40703   // TESTZ: ZF = (Op0 & Op1) == 0
40704   // TESTC: CF = (~Op0 & Op1) == 0
40705   // TESTNZC: ZF == 0 && CF == 0
40706   EVT VT = EFLAGS.getValueType();
40707   SDValue Op0 = EFLAGS.getOperand(0);
40708   SDValue Op1 = EFLAGS.getOperand(1);
40709   EVT OpVT = Op0.getValueType();
40710 
40711   // TEST*(~X,Y) == TEST*(X,Y)
40712   if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
40713     X86::CondCode InvCC;
40714     switch (CC) {
40715     case X86::COND_B:
40716       // testc -> testz.
40717       InvCC = X86::COND_E;
40718       break;
40719     case X86::COND_AE:
40720       // !testc -> !testz.
40721       InvCC = X86::COND_NE;
40722       break;
40723     case X86::COND_E:
40724       // testz -> testc.
40725       InvCC = X86::COND_B;
40726       break;
40727     case X86::COND_NE:
40728       // !testz -> !testc.
40729       InvCC = X86::COND_AE;
40730       break;
40731     case X86::COND_A:
40732     case X86::COND_BE:
40733       // testnzc -> testnzc (no change).
40734       InvCC = CC;
40735       break;
40736     default:
40737       InvCC = X86::COND_INVALID;
40738       break;
40739     }
40740 
40741     if (InvCC != X86::COND_INVALID) {
40742       CC = InvCC;
40743       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
40744                          DAG.getBitcast(OpVT, NotOp0), Op1);
40745     }
40746   }
40747 
40748   if (CC == X86::COND_E || CC == X86::COND_NE) {
40749     // TESTZ(X,~Y) == TESTC(Y,X)
40750     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
40751       CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
40752       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
40753                          DAG.getBitcast(OpVT, NotOp1), Op0);
40754     }
40755 
40756     if (Op0 == Op1) {
40757       SDValue BC = peekThroughBitcasts(Op0);
40758       EVT BCVT = BC.getValueType();
40759       assert(BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
40760              "Unexpected vector type");
40761 
40762       // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
40763       if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
40764         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
40765                            DAG.getBitcast(OpVT, BC.getOperand(0)),
40766                            DAG.getBitcast(OpVT, BC.getOperand(1)));
40767       }
40768 
40769       // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
40770       if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
40771         CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
40772         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
40773                            DAG.getBitcast(OpVT, BC.getOperand(0)),
40774                            DAG.getBitcast(OpVT, BC.getOperand(1)));
40775       }
40776 
40777       // If every element is an all-sign value, see if we can use MOVMSK to
40778       // more efficiently extract the sign bits and compare that.
40779       // TODO: Handle TESTC with comparison inversion.
40780       // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
40781       // MOVMSK combines to make sure its never worse than PTEST?
40782       unsigned EltBits = BCVT.getScalarSizeInBits();
40783       if (DAG.ComputeNumSignBits(BC) == EltBits) {
40784         assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
40785         APInt SignMask = APInt::getSignMask(EltBits);
40786         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40787         if (SDValue Res =
40788                 TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
40789           // For vXi16 cases we need to use pmovmksb and extract every other
40790           // sign bit.
40791           SDLoc DL(EFLAGS);
40792           if (EltBits == 16) {
40793             MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
40794             Res = DAG.getBitcast(MovmskVT, Res);
40795             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
40796             Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
40797                               DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
40798           } else {
40799             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
40800           }
40801           return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
40802                              DAG.getConstant(0, DL, MVT::i32));
40803         }
40804       }
40805     }
40806 
40807     // TESTZ(-1,X) == TESTZ(X,X)
40808     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
40809       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
40810 
40811     // TESTZ(X,-1) == TESTZ(X,X)
40812     if (ISD::isBuildVectorAllOnes(Op1.getNode()))
40813       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
40814   }
40815 
40816   return SDValue();
40817 }
40818 
40819 // Attempt to simplify the MOVMSK input based on the comparison type.
combineSetCCMOVMSK(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)40820 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
40821                                   SelectionDAG &DAG,
40822                                   const X86Subtarget &Subtarget) {
40823   // Handle eq/ne against zero (any_of).
40824   // Handle eq/ne against -1 (all_of).
40825   if (!(CC == X86::COND_E || CC == X86::COND_NE))
40826     return SDValue();
40827   if (EFLAGS.getValueType() != MVT::i32)
40828     return SDValue();
40829   unsigned CmpOpcode = EFLAGS.getOpcode();
40830   if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
40831     return SDValue();
40832   auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
40833   if (!CmpConstant)
40834     return SDValue();
40835   const APInt &CmpVal = CmpConstant->getAPIntValue();
40836 
40837   SDValue CmpOp = EFLAGS.getOperand(0);
40838   unsigned CmpBits = CmpOp.getValueSizeInBits();
40839   assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
40840 
40841   // Peek through any truncate.
40842   if (CmpOp.getOpcode() == ISD::TRUNCATE)
40843     CmpOp = CmpOp.getOperand(0);
40844 
40845   // Bail if we don't find a MOVMSK.
40846   if (CmpOp.getOpcode() != X86ISD::MOVMSK)
40847     return SDValue();
40848 
40849   SDValue Vec = CmpOp.getOperand(0);
40850   MVT VecVT = Vec.getSimpleValueType();
40851   assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
40852          "Unexpected MOVMSK operand");
40853   unsigned NumElts = VecVT.getVectorNumElements();
40854   unsigned NumEltBits = VecVT.getScalarSizeInBits();
40855 
40856   bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isNullValue();
40857   bool IsAllOf = CmpOpcode == X86ISD::SUB && NumElts <= CmpBits &&
40858                  CmpVal.isMask(NumElts);
40859   if (!IsAnyOf && !IsAllOf)
40860     return SDValue();
40861 
40862   // See if we can peek through to a vector with a wider element type, if the
40863   // signbits extend down to all the sub-elements as well.
40864   // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
40865   // potential SimplifyDemandedBits/Elts cases.
40866   if (Vec.getOpcode() == ISD::BITCAST) {
40867     SDValue BC = peekThroughBitcasts(Vec);
40868     MVT BCVT = BC.getSimpleValueType();
40869     unsigned BCNumElts = BCVT.getVectorNumElements();
40870     unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
40871     if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
40872         BCNumEltBits > NumEltBits &&
40873         DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
40874       SDLoc DL(EFLAGS);
40875       unsigned CmpMask = IsAnyOf ? 0 : ((1 << BCNumElts) - 1);
40876       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
40877                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
40878                          DAG.getConstant(CmpMask, DL, MVT::i32));
40879     }
40880   }
40881 
40882   // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
40883   // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
40884   if (IsAllOf && Subtarget.hasSSE41()) {
40885     SDValue BC = peekThroughBitcasts(Vec);
40886     if (BC.getOpcode() == X86ISD::PCMPEQ &&
40887         ISD::isBuildVectorAllZeros(BC.getOperand(1).getNode())) {
40888       MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
40889       SDValue V = DAG.getBitcast(TestVT, BC.getOperand(0));
40890       return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
40891     }
40892   }
40893 
40894   // See if we can avoid a PACKSS by calling MOVMSK on the sources.
40895   // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
40896   // sign bits prior to the comparison with zero unless we know that
40897   // the vXi16 splats the sign bit down to the lower i8 half.
40898   // TODO: Handle all_of patterns.
40899   if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
40900     SDValue VecOp0 = Vec.getOperand(0);
40901     SDValue VecOp1 = Vec.getOperand(1);
40902     bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
40903     bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
40904     // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
40905     if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
40906       SDLoc DL(EFLAGS);
40907       SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
40908       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
40909       Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
40910       if (!SignExt0) {
40911         Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
40912                              DAG.getConstant(0xAAAA, DL, MVT::i16));
40913       }
40914       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
40915                          DAG.getConstant(0, DL, MVT::i16));
40916     }
40917     // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
40918     // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
40919     if (CmpBits == 16 && Subtarget.hasInt256() &&
40920         VecOp0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40921         VecOp1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
40922         VecOp0.getOperand(0) == VecOp1.getOperand(0) &&
40923         VecOp0.getConstantOperandAPInt(1) == 0 &&
40924         VecOp1.getConstantOperandAPInt(1) == 8 &&
40925         (IsAnyOf || (SignExt0 && SignExt1))) {
40926       SDLoc DL(EFLAGS);
40927       SDValue Result = DAG.getBitcast(MVT::v32i8, VecOp0.getOperand(0));
40928       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
40929       unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
40930       if (!SignExt0 || !SignExt1) {
40931         assert(IsAnyOf && "Only perform v16i16 signmasks for any_of patterns");
40932         Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
40933                              DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
40934       }
40935       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
40936                          DAG.getConstant(CmpMask, DL, MVT::i32));
40937     }
40938   }
40939 
40940   // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
40941   SmallVector<int, 32> ShuffleMask;
40942   SmallVector<SDValue, 2> ShuffleInputs;
40943   if (NumElts == CmpBits &&
40944       getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
40945                              ShuffleMask, DAG) &&
40946       ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
40947       ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits()) {
40948     unsigned NumShuffleElts = ShuffleMask.size();
40949     APInt DemandedElts = APInt::getNullValue(NumShuffleElts);
40950     for (int M : ShuffleMask) {
40951       assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index");
40952       DemandedElts.setBit(M);
40953     }
40954     if (DemandedElts.isAllOnesValue()) {
40955       SDLoc DL(EFLAGS);
40956       SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
40957       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
40958       Result =
40959           DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
40960       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
40961                          EFLAGS.getOperand(1));
40962     }
40963   }
40964 
40965   return SDValue();
40966 }
40967 
40968 /// Optimize an EFLAGS definition used according to the condition code \p CC
40969 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
40970 /// uses of chain values.
combineSetCCEFLAGS(SDValue EFLAGS,X86::CondCode & CC,SelectionDAG & DAG,const X86Subtarget & Subtarget)40971 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
40972                                   SelectionDAG &DAG,
40973                                   const X86Subtarget &Subtarget) {
40974   if (CC == X86::COND_B)
40975     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
40976       return Flags;
40977 
40978   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
40979     return R;
40980 
40981   if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
40982     return R;
40983 
40984   if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
40985     return R;
40986 
40987   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
40988 }
40989 
40990 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
combineCMov(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)40991 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
40992                            TargetLowering::DAGCombinerInfo &DCI,
40993                            const X86Subtarget &Subtarget) {
40994   SDLoc DL(N);
40995 
40996   SDValue FalseOp = N->getOperand(0);
40997   SDValue TrueOp = N->getOperand(1);
40998   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
40999   SDValue Cond = N->getOperand(3);
41000 
41001   // cmov X, X, ?, ? --> X
41002   if (TrueOp == FalseOp)
41003     return TrueOp;
41004 
41005   // Try to simplify the EFLAGS and condition code operands.
41006   // We can't always do this as FCMOV only supports a subset of X86 cond.
41007   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
41008     if (!(FalseOp.getValueType() == MVT::f80 ||
41009           (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
41010           (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
41011         !Subtarget.hasCMov() || hasFPCMov(CC)) {
41012       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
41013                        Flags};
41014       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
41015     }
41016   }
41017 
41018   // If this is a select between two integer constants, try to do some
41019   // optimizations.  Note that the operands are ordered the opposite of SELECT
41020   // operands.
41021   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
41022     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
41023       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
41024       // larger than FalseC (the false value).
41025       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
41026         CC = X86::GetOppositeBranchCondition(CC);
41027         std::swap(TrueC, FalseC);
41028         std::swap(TrueOp, FalseOp);
41029       }
41030 
41031       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
41032       // This is efficient for any integer data type (including i8/i16) and
41033       // shift amount.
41034       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
41035         Cond = getSETCC(CC, Cond, DL, DAG);
41036 
41037         // Zero extend the condition if needed.
41038         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
41039 
41040         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
41041         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
41042                            DAG.getConstant(ShAmt, DL, MVT::i8));
41043         return Cond;
41044       }
41045 
41046       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
41047       // for any integer data type, including i8/i16.
41048       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
41049         Cond = getSETCC(CC, Cond, DL, DAG);
41050 
41051         // Zero extend the condition if needed.
41052         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
41053                            FalseC->getValueType(0), Cond);
41054         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
41055                            SDValue(FalseC, 0));
41056         return Cond;
41057       }
41058 
41059       // Optimize cases that will turn into an LEA instruction.  This requires
41060       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
41061       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
41062         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
41063         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
41064                "Implicit constant truncation");
41065 
41066         bool isFastMultiplier = false;
41067         if (Diff.ult(10)) {
41068           switch (Diff.getZExtValue()) {
41069           default: break;
41070           case 1:  // result = add base, cond
41071           case 2:  // result = lea base(    , cond*2)
41072           case 3:  // result = lea base(cond, cond*2)
41073           case 4:  // result = lea base(    , cond*4)
41074           case 5:  // result = lea base(cond, cond*4)
41075           case 8:  // result = lea base(    , cond*8)
41076           case 9:  // result = lea base(cond, cond*8)
41077             isFastMultiplier = true;
41078             break;
41079           }
41080         }
41081 
41082         if (isFastMultiplier) {
41083           Cond = getSETCC(CC, Cond, DL ,DAG);
41084           // Zero extend the condition if needed.
41085           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
41086                              Cond);
41087           // Scale the condition by the difference.
41088           if (Diff != 1)
41089             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
41090                                DAG.getConstant(Diff, DL, Cond.getValueType()));
41091 
41092           // Add the base if non-zero.
41093           if (FalseC->getAPIntValue() != 0)
41094             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
41095                                SDValue(FalseC, 0));
41096           return Cond;
41097         }
41098       }
41099     }
41100   }
41101 
41102   // Handle these cases:
41103   //   (select (x != c), e, c) -> select (x != c), e, x),
41104   //   (select (x == c), c, e) -> select (x == c), x, e)
41105   // where the c is an integer constant, and the "select" is the combination
41106   // of CMOV and CMP.
41107   //
41108   // The rationale for this change is that the conditional-move from a constant
41109   // needs two instructions, however, conditional-move from a register needs
41110   // only one instruction.
41111   //
41112   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
41113   //  some instruction-combining opportunities. This opt needs to be
41114   //  postponed as late as possible.
41115   //
41116   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
41117     // the DCI.xxxx conditions are provided to postpone the optimization as
41118     // late as possible.
41119 
41120     ConstantSDNode *CmpAgainst = nullptr;
41121     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
41122         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
41123         !isa<ConstantSDNode>(Cond.getOperand(0))) {
41124 
41125       if (CC == X86::COND_NE &&
41126           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
41127         CC = X86::GetOppositeBranchCondition(CC);
41128         std::swap(TrueOp, FalseOp);
41129       }
41130 
41131       if (CC == X86::COND_E &&
41132           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
41133         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
41134                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
41135         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
41136       }
41137     }
41138   }
41139 
41140   // Fold and/or of setcc's to double CMOV:
41141   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
41142   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
41143   //
41144   // This combine lets us generate:
41145   //   cmovcc1 (jcc1 if we don't have CMOV)
41146   //   cmovcc2 (same)
41147   // instead of:
41148   //   setcc1
41149   //   setcc2
41150   //   and/or
41151   //   cmovne (jne if we don't have CMOV)
41152   // When we can't use the CMOV instruction, it might increase branch
41153   // mispredicts.
41154   // When we can use CMOV, or when there is no mispredict, this improves
41155   // throughput and reduces register pressure.
41156   //
41157   if (CC == X86::COND_NE) {
41158     SDValue Flags;
41159     X86::CondCode CC0, CC1;
41160     bool isAndSetCC;
41161     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
41162       if (isAndSetCC) {
41163         std::swap(FalseOp, TrueOp);
41164         CC0 = X86::GetOppositeBranchCondition(CC0);
41165         CC1 = X86::GetOppositeBranchCondition(CC1);
41166       }
41167 
41168       SDValue LOps[] = {FalseOp, TrueOp,
41169                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
41170       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
41171       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
41172                        Flags};
41173       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
41174       return CMOV;
41175     }
41176   }
41177 
41178   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
41179   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
41180   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
41181   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
41182   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
41183       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
41184     SDValue Add = TrueOp;
41185     SDValue Const = FalseOp;
41186     // Canonicalize the condition code for easier matching and output.
41187     if (CC == X86::COND_E)
41188       std::swap(Add, Const);
41189 
41190     // We might have replaced the constant in the cmov with the LHS of the
41191     // compare. If so change it to the RHS of the compare.
41192     if (Const == Cond.getOperand(0))
41193       Const = Cond.getOperand(1);
41194 
41195     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
41196     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
41197         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
41198         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
41199          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
41200         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
41201       EVT VT = N->getValueType(0);
41202       // This should constant fold.
41203       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
41204       SDValue CMov =
41205           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
41206                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
41207       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
41208     }
41209   }
41210 
41211   return SDValue();
41212 }
41213 
41214 /// Different mul shrinking modes.
41215 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
41216 
canReduceVMulWidth(SDNode * N,SelectionDAG & DAG,ShrinkMode & Mode)41217 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
41218   EVT VT = N->getOperand(0).getValueType();
41219   if (VT.getScalarSizeInBits() != 32)
41220     return false;
41221 
41222   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
41223   unsigned SignBits[2] = {1, 1};
41224   bool IsPositive[2] = {false, false};
41225   for (unsigned i = 0; i < 2; i++) {
41226     SDValue Opd = N->getOperand(i);
41227 
41228     SignBits[i] = DAG.ComputeNumSignBits(Opd);
41229     IsPositive[i] = DAG.SignBitIsZero(Opd);
41230   }
41231 
41232   bool AllPositive = IsPositive[0] && IsPositive[1];
41233   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
41234   // When ranges are from -128 ~ 127, use MULS8 mode.
41235   if (MinSignBits >= 25)
41236     Mode = ShrinkMode::MULS8;
41237   // When ranges are from 0 ~ 255, use MULU8 mode.
41238   else if (AllPositive && MinSignBits >= 24)
41239     Mode = ShrinkMode::MULU8;
41240   // When ranges are from -32768 ~ 32767, use MULS16 mode.
41241   else if (MinSignBits >= 17)
41242     Mode = ShrinkMode::MULS16;
41243   // When ranges are from 0 ~ 65535, use MULU16 mode.
41244   else if (AllPositive && MinSignBits >= 16)
41245     Mode = ShrinkMode::MULU16;
41246   else
41247     return false;
41248   return true;
41249 }
41250 
41251 /// When the operands of vector mul are extended from smaller size values,
41252 /// like i8 and i16, the type of mul may be shrinked to generate more
41253 /// efficient code. Two typical patterns are handled:
41254 /// Pattern1:
41255 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
41256 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
41257 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
41258 ///     %5 = mul <N x i32> %2, %4
41259 ///
41260 /// Pattern2:
41261 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
41262 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
41263 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
41264 ///     %5 = mul <N x i32> %2, %4
41265 ///
41266 /// There are four mul shrinking modes:
41267 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
41268 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
41269 /// generate pmullw+sext32 for it (MULS8 mode).
41270 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
41271 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
41272 /// generate pmullw+zext32 for it (MULU8 mode).
41273 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
41274 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
41275 /// generate pmullw+pmulhw for it (MULS16 mode).
41276 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
41277 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
41278 /// generate pmullw+pmulhuw for it (MULU16 mode).
reduceVMULWidth(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41279 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
41280                                const X86Subtarget &Subtarget) {
41281   // Check for legality
41282   // pmullw/pmulhw are not supported by SSE.
41283   if (!Subtarget.hasSSE2())
41284     return SDValue();
41285 
41286   // Check for profitability
41287   // pmulld is supported since SSE41. It is better to use pmulld
41288   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
41289   // the expansion.
41290   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
41291   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
41292     return SDValue();
41293 
41294   ShrinkMode Mode;
41295   if (!canReduceVMulWidth(N, DAG, Mode))
41296     return SDValue();
41297 
41298   SDLoc DL(N);
41299   SDValue N0 = N->getOperand(0);
41300   SDValue N1 = N->getOperand(1);
41301   EVT VT = N->getOperand(0).getValueType();
41302   unsigned NumElts = VT.getVectorNumElements();
41303   if ((NumElts % 2) != 0)
41304     return SDValue();
41305 
41306   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
41307 
41308   // Shrink the operands of mul.
41309   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
41310   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
41311 
41312   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
41313   // lower part is needed.
41314   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
41315   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
41316     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
41317                                                    : ISD::SIGN_EXTEND,
41318                        DL, VT, MulLo);
41319 
41320   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
41321   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
41322   // the higher part is also needed.
41323   SDValue MulHi =
41324       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
41325                   ReducedVT, NewN0, NewN1);
41326 
41327   // Repack the lower part and higher part result of mul into a wider
41328   // result.
41329   // Generate shuffle functioning as punpcklwd.
41330   SmallVector<int, 16> ShuffleMask(NumElts);
41331   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
41332     ShuffleMask[2 * i] = i;
41333     ShuffleMask[2 * i + 1] = i + NumElts;
41334   }
41335   SDValue ResLo =
41336       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
41337   ResLo = DAG.getBitcast(ResVT, ResLo);
41338   // Generate shuffle functioning as punpckhwd.
41339   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
41340     ShuffleMask[2 * i] = i + NumElts / 2;
41341     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
41342   }
41343   SDValue ResHi =
41344       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
41345   ResHi = DAG.getBitcast(ResVT, ResHi);
41346   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
41347 }
41348 
combineMulSpecial(uint64_t MulAmt,SDNode * N,SelectionDAG & DAG,EVT VT,const SDLoc & DL)41349 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
41350                                  EVT VT, const SDLoc &DL) {
41351 
41352   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
41353     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
41354                                  DAG.getConstant(Mult, DL, VT));
41355     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
41356                          DAG.getConstant(Shift, DL, MVT::i8));
41357     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
41358                          N->getOperand(0));
41359     return Result;
41360   };
41361 
41362   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
41363     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
41364                                  DAG.getConstant(Mul1, DL, VT));
41365     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
41366                          DAG.getConstant(Mul2, DL, VT));
41367     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
41368                          N->getOperand(0));
41369     return Result;
41370   };
41371 
41372   switch (MulAmt) {
41373   default:
41374     break;
41375   case 11:
41376     // mul x, 11 => add ((shl (mul x, 5), 1), x)
41377     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
41378   case 21:
41379     // mul x, 21 => add ((shl (mul x, 5), 2), x)
41380     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
41381   case 41:
41382     // mul x, 41 => add ((shl (mul x, 5), 3), x)
41383     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
41384   case 22:
41385     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
41386     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
41387                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
41388   case 19:
41389     // mul x, 19 => add ((shl (mul x, 9), 1), x)
41390     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
41391   case 37:
41392     // mul x, 37 => add ((shl (mul x, 9), 2), x)
41393     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
41394   case 73:
41395     // mul x, 73 => add ((shl (mul x, 9), 3), x)
41396     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
41397   case 13:
41398     // mul x, 13 => add ((shl (mul x, 3), 2), x)
41399     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
41400   case 23:
41401     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
41402     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
41403   case 26:
41404     // mul x, 26 => add ((mul (mul x, 5), 5), x)
41405     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
41406   case 28:
41407     // mul x, 28 => add ((mul (mul x, 9), 3), x)
41408     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
41409   case 29:
41410     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
41411     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
41412                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
41413   }
41414 
41415   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
41416   // by a single LEA.
41417   // First check if this a sum of two power of 2s because that's easy. Then
41418   // count how many zeros are up to the first bit.
41419   // TODO: We can do this even without LEA at a cost of two shifts and an add.
41420   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
41421     unsigned ScaleShift = countTrailingZeros(MulAmt);
41422     if (ScaleShift >= 1 && ScaleShift < 4) {
41423       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
41424       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41425                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
41426       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41427                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
41428       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
41429     }
41430   }
41431 
41432   return SDValue();
41433 }
41434 
41435 // If the upper 17 bits of each element are zero then we can use PMADDWD,
41436 // which is always at least as quick as PMULLD, except on KNL.
combineMulToPMADDWD(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41437 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
41438                                    const X86Subtarget &Subtarget) {
41439   if (!Subtarget.hasSSE2())
41440     return SDValue();
41441 
41442   if (Subtarget.isPMADDWDSlow())
41443     return SDValue();
41444 
41445   EVT VT = N->getValueType(0);
41446 
41447   // Only support vXi32 vectors.
41448   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
41449     return SDValue();
41450 
41451   // Make sure the type is legal or will be widened to a legal type.
41452   if (VT != MVT::v2i32 && !DAG.getTargetLoweringInfo().isTypeLegal(VT))
41453     return SDValue();
41454 
41455   MVT WVT = MVT::getVectorVT(MVT::i16, 2 * VT.getVectorNumElements());
41456 
41457   // Without BWI, we would need to split v32i16.
41458   if (WVT == MVT::v32i16 && !Subtarget.hasBWI())
41459     return SDValue();
41460 
41461   SDValue N0 = N->getOperand(0);
41462   SDValue N1 = N->getOperand(1);
41463 
41464   // If we are zero extending two steps without SSE4.1, its better to reduce
41465   // the vmul width instead.
41466   if (!Subtarget.hasSSE41() &&
41467       (N0.getOpcode() == ISD::ZERO_EXTEND &&
41468        N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
41469       (N1.getOpcode() == ISD::ZERO_EXTEND &&
41470        N1.getOperand(0).getScalarValueSizeInBits() <= 8))
41471     return SDValue();
41472 
41473   APInt Mask17 = APInt::getHighBitsSet(32, 17);
41474   if (!DAG.MaskedValueIsZero(N1, Mask17) ||
41475       !DAG.MaskedValueIsZero(N0, Mask17))
41476     return SDValue();
41477 
41478   // Use SplitOpsAndApply to handle AVX splitting.
41479   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41480                            ArrayRef<SDValue> Ops) {
41481     MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
41482     return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
41483   };
41484   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
41485                           { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
41486                           PMADDWDBuilder);
41487 }
41488 
combineMulToPMULDQ(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41489 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
41490                                   const X86Subtarget &Subtarget) {
41491   if (!Subtarget.hasSSE2())
41492     return SDValue();
41493 
41494   EVT VT = N->getValueType(0);
41495 
41496   // Only support vXi64 vectors.
41497   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
41498       VT.getVectorNumElements() < 2 ||
41499       !isPowerOf2_32(VT.getVectorNumElements()))
41500     return SDValue();
41501 
41502   SDValue N0 = N->getOperand(0);
41503   SDValue N1 = N->getOperand(1);
41504 
41505   // MULDQ returns the 64-bit result of the signed multiplication of the lower
41506   // 32-bits. We can lower with this if the sign bits stretch that far.
41507   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
41508       DAG.ComputeNumSignBits(N1) > 32) {
41509     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41510                             ArrayRef<SDValue> Ops) {
41511       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
41512     };
41513     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
41514                             PMULDQBuilder, /*CheckBWI*/false);
41515   }
41516 
41517   // If the upper bits are zero we can use a single pmuludq.
41518   APInt Mask = APInt::getHighBitsSet(64, 32);
41519   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
41520     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
41521                              ArrayRef<SDValue> Ops) {
41522       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
41523     };
41524     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
41525                             PMULUDQBuilder, /*CheckBWI*/false);
41526   }
41527 
41528   return SDValue();
41529 }
41530 
41531 /// Optimize a single multiply with constant into two operations in order to
41532 /// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
combineMul(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41533 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
41534                           TargetLowering::DAGCombinerInfo &DCI,
41535                           const X86Subtarget &Subtarget) {
41536   EVT VT = N->getValueType(0);
41537 
41538   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
41539     return V;
41540 
41541   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
41542     return V;
41543 
41544   if (DCI.isBeforeLegalize() && VT.isVector())
41545     return reduceVMULWidth(N, DAG, Subtarget);
41546 
41547   if (!MulConstantOptimization)
41548     return SDValue();
41549   // An imul is usually smaller than the alternative sequence.
41550   if (DAG.getMachineFunction().getFunction().hasMinSize())
41551     return SDValue();
41552 
41553   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
41554     return SDValue();
41555 
41556   if (VT != MVT::i64 && VT != MVT::i32)
41557     return SDValue();
41558 
41559   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
41560   if (!C)
41561     return SDValue();
41562   if (isPowerOf2_64(C->getZExtValue()))
41563     return SDValue();
41564 
41565   int64_t SignMulAmt = C->getSExtValue();
41566   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
41567   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
41568 
41569   SDLoc DL(N);
41570   if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
41571     SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
41572                                  DAG.getConstant(AbsMulAmt, DL, VT));
41573     if (SignMulAmt < 0)
41574       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
41575                            NewMul);
41576 
41577     return NewMul;
41578   }
41579 
41580   uint64_t MulAmt1 = 0;
41581   uint64_t MulAmt2 = 0;
41582   if ((AbsMulAmt % 9) == 0) {
41583     MulAmt1 = 9;
41584     MulAmt2 = AbsMulAmt / 9;
41585   } else if ((AbsMulAmt % 5) == 0) {
41586     MulAmt1 = 5;
41587     MulAmt2 = AbsMulAmt / 5;
41588   } else if ((AbsMulAmt % 3) == 0) {
41589     MulAmt1 = 3;
41590     MulAmt2 = AbsMulAmt / 3;
41591   }
41592 
41593   SDValue NewMul;
41594   // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
41595   if (MulAmt2 &&
41596       (isPowerOf2_64(MulAmt2) ||
41597        (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
41598 
41599     if (isPowerOf2_64(MulAmt2) &&
41600         !(SignMulAmt >= 0 && N->hasOneUse() &&
41601           N->use_begin()->getOpcode() == ISD::ADD))
41602       // If second multiplifer is pow2, issue it first. We want the multiply by
41603       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
41604       // is an add. Only do this for positive multiply amounts since the
41605       // negate would prevent it from being used as an address mode anyway.
41606       std::swap(MulAmt1, MulAmt2);
41607 
41608     if (isPowerOf2_64(MulAmt1))
41609       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41610                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
41611     else
41612       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
41613                            DAG.getConstant(MulAmt1, DL, VT));
41614 
41615     if (isPowerOf2_64(MulAmt2))
41616       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
41617                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
41618     else
41619       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
41620                            DAG.getConstant(MulAmt2, DL, VT));
41621 
41622     // Negate the result.
41623     if (SignMulAmt < 0)
41624       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
41625                            NewMul);
41626   } else if (!Subtarget.slowLEA())
41627     NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
41628 
41629   if (!NewMul) {
41630     assert(C->getZExtValue() != 0 &&
41631            C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&
41632            "Both cases that could cause potential overflows should have "
41633            "already been handled.");
41634     if (isPowerOf2_64(AbsMulAmt - 1)) {
41635       // (mul x, 2^N + 1) => (add (shl x, N), x)
41636       NewMul = DAG.getNode(
41637           ISD::ADD, DL, VT, N->getOperand(0),
41638           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41639                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
41640                                       MVT::i8)));
41641       // To negate, subtract the number from zero
41642       if (SignMulAmt < 0)
41643         NewMul = DAG.getNode(ISD::SUB, DL, VT,
41644                              DAG.getConstant(0, DL, VT), NewMul);
41645     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
41646       // (mul x, 2^N - 1) => (sub (shl x, N), x)
41647       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41648                            DAG.getConstant(Log2_64(AbsMulAmt + 1),
41649                                            DL, MVT::i8));
41650       // To negate, reverse the operands of the subtract.
41651       if (SignMulAmt < 0)
41652         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
41653       else
41654         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
41655     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
41656       // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
41657       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41658                            DAG.getConstant(Log2_64(AbsMulAmt - 2),
41659                                            DL, MVT::i8));
41660       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
41661       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
41662     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
41663       // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
41664       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
41665                            DAG.getConstant(Log2_64(AbsMulAmt + 2),
41666                                            DL, MVT::i8));
41667       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
41668       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
41669     }
41670   }
41671 
41672   return NewMul;
41673 }
41674 
41675 // Try to form a MULHU or MULHS node by looking for
41676 // (srl (mul ext, ext), 16)
41677 // TODO: This is X86 specific because we want to be able to handle wide types
41678 // before type legalization. But we can only do it if the vector will be
41679 // legalized via widening/splitting. Type legalization can't handle promotion
41680 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
41681 // combiner.
combineShiftToPMULH(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41682 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
41683                                    const X86Subtarget &Subtarget) {
41684   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
41685            "SRL or SRA node is required here!");
41686   SDLoc DL(N);
41687 
41688   // Only do this with SSE4.1. On earlier targets reduceVMULWidth will expand
41689   // the multiply.
41690   if (!Subtarget.hasSSE41())
41691     return SDValue();
41692 
41693   // The operation feeding into the shift must be a multiply.
41694   SDValue ShiftOperand = N->getOperand(0);
41695   if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
41696     return SDValue();
41697 
41698   // Input type should be at least vXi32.
41699   EVT VT = N->getValueType(0);
41700   if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
41701     return SDValue();
41702 
41703   // Need a shift by 16.
41704   APInt ShiftAmt;
41705   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
41706       ShiftAmt != 16)
41707     return SDValue();
41708 
41709   SDValue LHS = ShiftOperand.getOperand(0);
41710   SDValue RHS = ShiftOperand.getOperand(1);
41711 
41712   unsigned ExtOpc = LHS.getOpcode();
41713   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
41714       RHS.getOpcode() != ExtOpc)
41715     return SDValue();
41716 
41717   // Peek through the extends.
41718   LHS = LHS.getOperand(0);
41719   RHS = RHS.getOperand(0);
41720 
41721   // Ensure the input types match.
41722   EVT MulVT = LHS.getValueType();
41723   if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
41724     return SDValue();
41725 
41726   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
41727   SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
41728 
41729   ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
41730   return DAG.getNode(ExtOpc, DL, VT, Mulh);
41731 }
41732 
combineShiftLeft(SDNode * N,SelectionDAG & DAG)41733 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
41734   SDValue N0 = N->getOperand(0);
41735   SDValue N1 = N->getOperand(1);
41736   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
41737   EVT VT = N0.getValueType();
41738 
41739   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
41740   // since the result of setcc_c is all zero's or all ones.
41741   if (VT.isInteger() && !VT.isVector() &&
41742       N1C && N0.getOpcode() == ISD::AND &&
41743       N0.getOperand(1).getOpcode() == ISD::Constant) {
41744     SDValue N00 = N0.getOperand(0);
41745     APInt Mask = N0.getConstantOperandAPInt(1);
41746     Mask <<= N1C->getAPIntValue();
41747     bool MaskOK = false;
41748     // We can handle cases concerning bit-widening nodes containing setcc_c if
41749     // we carefully interrogate the mask to make sure we are semantics
41750     // preserving.
41751     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
41752     // of the underlying setcc_c operation if the setcc_c was zero extended.
41753     // Consider the following example:
41754     //   zext(setcc_c)                 -> i32 0x0000FFFF
41755     //   c1                            -> i32 0x0000FFFF
41756     //   c2                            -> i32 0x00000001
41757     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
41758     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
41759     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
41760       MaskOK = true;
41761     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
41762                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
41763       MaskOK = true;
41764     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
41765                 N00.getOpcode() == ISD::ANY_EXTEND) &&
41766                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
41767       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
41768     }
41769     if (MaskOK && Mask != 0) {
41770       SDLoc DL(N);
41771       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
41772     }
41773   }
41774 
41775   // Hardware support for vector shifts is sparse which makes us scalarize the
41776   // vector operations in many cases. Also, on sandybridge ADD is faster than
41777   // shl.
41778   // (shl V, 1) -> add V,V
41779   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
41780     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
41781       assert(N0.getValueType().isVector() && "Invalid vector shift type");
41782       // We shift all of the values by one. In many cases we do not have
41783       // hardware support for this operation. This is better expressed as an ADD
41784       // of two values.
41785       if (N1SplatC->isOne())
41786         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
41787     }
41788 
41789   return SDValue();
41790 }
41791 
combineShiftRightArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)41792 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
41793                                            const X86Subtarget &Subtarget) {
41794   SDValue N0 = N->getOperand(0);
41795   SDValue N1 = N->getOperand(1);
41796   EVT VT = N0.getValueType();
41797   unsigned Size = VT.getSizeInBits();
41798 
41799   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
41800     return V;
41801 
41802   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
41803   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
41804   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
41805   // depending on sign of (SarConst - [56,48,32,24,16])
41806 
41807   // sexts in X86 are MOVs. The MOVs have the same code size
41808   // as above SHIFTs (only SHIFT on 1 has lower code size).
41809   // However the MOVs have 2 advantages to a SHIFT:
41810   // 1. MOVs can write to a register that differs from source
41811   // 2. MOVs accept memory operands
41812 
41813   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
41814       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
41815       N0.getOperand(1).getOpcode() != ISD::Constant)
41816     return SDValue();
41817 
41818   SDValue N00 = N0.getOperand(0);
41819   SDValue N01 = N0.getOperand(1);
41820   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
41821   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
41822   EVT CVT = N1.getValueType();
41823 
41824   if (SarConst.isNegative())
41825     return SDValue();
41826 
41827   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
41828     unsigned ShiftSize = SVT.getSizeInBits();
41829     // skipping types without corresponding sext/zext and
41830     // ShlConst that is not one of [56,48,32,24,16]
41831     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
41832       continue;
41833     SDLoc DL(N);
41834     SDValue NN =
41835         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
41836     SarConst = SarConst - (Size - ShiftSize);
41837     if (SarConst == 0)
41838       return NN;
41839     else if (SarConst.isNegative())
41840       return DAG.getNode(ISD::SHL, DL, VT, NN,
41841                          DAG.getConstant(-SarConst, DL, CVT));
41842     else
41843       return DAG.getNode(ISD::SRA, DL, VT, NN,
41844                          DAG.getConstant(SarConst, DL, CVT));
41845   }
41846   return SDValue();
41847 }
41848 
combineShiftRightLogical(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41849 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
41850                                         TargetLowering::DAGCombinerInfo &DCI,
41851                                         const X86Subtarget &Subtarget) {
41852   SDValue N0 = N->getOperand(0);
41853   SDValue N1 = N->getOperand(1);
41854   EVT VT = N0.getValueType();
41855 
41856   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
41857     return V;
41858 
41859   // Only do this on the last DAG combine as it can interfere with other
41860   // combines.
41861   if (!DCI.isAfterLegalizeDAG())
41862     return SDValue();
41863 
41864   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
41865   // TODO: This is a generic DAG combine that became an x86-only combine to
41866   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
41867   // and-not ('andn').
41868   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
41869     return SDValue();
41870 
41871   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
41872   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
41873   if (!ShiftC || !AndC)
41874     return SDValue();
41875 
41876   // If we can shrink the constant mask below 8-bits or 32-bits, then this
41877   // transform should reduce code size. It may also enable secondary transforms
41878   // from improved known-bits analysis or instruction selection.
41879   APInt MaskVal = AndC->getAPIntValue();
41880 
41881   // If this can be matched by a zero extend, don't optimize.
41882   if (MaskVal.isMask()) {
41883     unsigned TO = MaskVal.countTrailingOnes();
41884     if (TO >= 8 && isPowerOf2_32(TO))
41885       return SDValue();
41886   }
41887 
41888   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
41889   unsigned OldMaskSize = MaskVal.getMinSignedBits();
41890   unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
41891   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
41892       (OldMaskSize > 32 && NewMaskSize <= 32)) {
41893     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
41894     SDLoc DL(N);
41895     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
41896     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
41897     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
41898   }
41899   return SDValue();
41900 }
41901 
combineVectorPackWithShuffle(SDNode * N,SelectionDAG & DAG)41902 static SDValue combineVectorPackWithShuffle(SDNode *N, SelectionDAG &DAG) {
41903   unsigned Opcode = N->getOpcode();
41904   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
41905          "Unexpected pack opcode");
41906 
41907   EVT VT = N->getValueType(0);
41908   SDValue N0 = N->getOperand(0);
41909   SDValue N1 = N->getOperand(1);
41910   unsigned NumDstElts = VT.getVectorNumElements();
41911 
41912   // Attempt to fold PACK(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
41913   // to SHUFFLE(PACK(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
41914   // truncation trees that help us avoid lane crossing shuffles.
41915   // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
41916   if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41917       N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41918       N0.getConstantOperandAPInt(1) == 0 &&
41919       N1.getConstantOperandAPInt(1) == (NumDstElts / 2) &&
41920       N0.getOperand(0) == N1.getOperand(0) && VT.is128BitVector() &&
41921       N0.getOperand(0).getValueType().is256BitVector()) {
41922     // TODO - support target/faux shuffles.
41923     SDValue Vec = peekThroughBitcasts(N0.getOperand(0));
41924     if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Vec)) {
41925       // To keep the PACK LHS/RHS coherency, we must be able to scale the unary
41926       // shuffle to a vXi64 width - we can probably relax this in the future.
41927       SmallVector<int, 4> ShuffleMask;
41928       if (SVN->getOperand(1).isUndef() &&
41929           scaleShuffleElements(SVN->getMask(), 4, ShuffleMask)) {
41930         SDLoc DL(N);
41931         SDValue Lo, Hi;
41932         std::tie(Lo, Hi) = DAG.SplitVector(SVN->getOperand(0), DL);
41933         Lo = DAG.getBitcast(N0.getValueType(), Lo);
41934         Hi = DAG.getBitcast(N1.getValueType(), Hi);
41935         SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
41936         Res = DAG.getBitcast(MVT::v4i32, Res);
41937         Res = DAG.getVectorShuffle(MVT::v4i32, DL, Res, Res, ShuffleMask);
41938         return DAG.getBitcast(VT, Res);
41939       }
41940     }
41941   }
41942 
41943   // Attempt to fold PACK(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(PACK(X,Y)).
41944   // TODO: Relax shuffle scaling to support sub-128-bit subvector shuffles.
41945   if (VT.is256BitVector()) {
41946     if (auto *SVN0 = dyn_cast<ShuffleVectorSDNode>(N0)) {
41947       if (auto *SVN1 = dyn_cast<ShuffleVectorSDNode>(N1)) {
41948         SmallVector<int, 2> ShuffleMask0, ShuffleMask1;
41949         if (scaleShuffleElements(SVN0->getMask(), 2, ShuffleMask0) &&
41950             scaleShuffleElements(SVN1->getMask(), 2, ShuffleMask1)) {
41951           SDValue Op00 = SVN0->getOperand(0);
41952           SDValue Op01 = SVN0->getOperand(1);
41953           SDValue Op10 = SVN1->getOperand(0);
41954           SDValue Op11 = SVN1->getOperand(1);
41955           if ((Op00 == Op11) && (Op01 == Op10)) {
41956             std::swap(Op10, Op11);
41957             ShuffleVectorSDNode::commuteMask(ShuffleMask1);
41958           }
41959           if ((Op00 == Op10) && (Op01 == Op11)) {
41960             SmallVector<int, 4> ShuffleMask;
41961             ShuffleMask.append(ShuffleMask0.begin(), ShuffleMask0.end());
41962             ShuffleMask.append(ShuffleMask1.begin(), ShuffleMask1.end());
41963             SDLoc DL(N);
41964             SDValue Res = DAG.getNode(Opcode, DL, VT, Op00, Op01);
41965             Res = DAG.getBitcast(MVT::v4i64, Res);
41966             Res = DAG.getVectorShuffle(MVT::v4i64, DL, Res, Res, ShuffleMask);
41967             return DAG.getBitcast(VT, Res);
41968           }
41969         }
41970       }
41971     }
41972   }
41973 
41974   return SDValue();
41975 }
41976 
combineVectorPack(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)41977 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
41978                                  TargetLowering::DAGCombinerInfo &DCI,
41979                                  const X86Subtarget &Subtarget) {
41980   unsigned Opcode = N->getOpcode();
41981   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
41982          "Unexpected pack opcode");
41983 
41984   EVT VT = N->getValueType(0);
41985   SDValue N0 = N->getOperand(0);
41986   SDValue N1 = N->getOperand(1);
41987   unsigned NumDstElts = VT.getVectorNumElements();
41988   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
41989   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
41990   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
41991          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
41992          "Unexpected PACKSS/PACKUS input type");
41993 
41994   bool IsSigned = (X86ISD::PACKSS == Opcode);
41995 
41996   // Constant Folding.
41997   APInt UndefElts0, UndefElts1;
41998   SmallVector<APInt, 32> EltBits0, EltBits1;
41999   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
42000       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
42001       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
42002       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
42003     unsigned NumLanes = VT.getSizeInBits() / 128;
42004     unsigned NumSrcElts = NumDstElts / 2;
42005     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
42006     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
42007 
42008     APInt Undefs(NumDstElts, 0);
42009     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getNullValue(DstBitsPerElt));
42010     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
42011       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
42012         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
42013         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
42014         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
42015 
42016         if (UndefElts[SrcIdx]) {
42017           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
42018           continue;
42019         }
42020 
42021         APInt &Val = EltBits[SrcIdx];
42022         if (IsSigned) {
42023           // PACKSS: Truncate signed value with signed saturation.
42024           // Source values less than dst minint are saturated to minint.
42025           // Source values greater than dst maxint are saturated to maxint.
42026           if (Val.isSignedIntN(DstBitsPerElt))
42027             Val = Val.trunc(DstBitsPerElt);
42028           else if (Val.isNegative())
42029             Val = APInt::getSignedMinValue(DstBitsPerElt);
42030           else
42031             Val = APInt::getSignedMaxValue(DstBitsPerElt);
42032         } else {
42033           // PACKUS: Truncate signed value with unsigned saturation.
42034           // Source values less than zero are saturated to zero.
42035           // Source values greater than dst maxuint are saturated to maxuint.
42036           if (Val.isIntN(DstBitsPerElt))
42037             Val = Val.trunc(DstBitsPerElt);
42038           else if (Val.isNegative())
42039             Val = APInt::getNullValue(DstBitsPerElt);
42040           else
42041             Val = APInt::getAllOnesValue(DstBitsPerElt);
42042         }
42043         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
42044       }
42045     }
42046 
42047     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
42048   }
42049 
42050   // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
42051   if (SDValue V = combineVectorPackWithShuffle(N, DAG))
42052     return V;
42053 
42054   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
42055   // truncate to create a larger truncate.
42056   if (Subtarget.hasAVX512() &&
42057       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
42058       N0.getOperand(0).getValueType() == MVT::v8i32) {
42059     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
42060         (!IsSigned &&
42061          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
42062       if (Subtarget.hasVLX())
42063         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
42064 
42065       // Widen input to v16i32 so we can truncate that.
42066       SDLoc dl(N);
42067       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
42068                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
42069       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
42070     }
42071   }
42072 
42073   // Attempt to combine as shuffle.
42074   SDValue Op(N, 0);
42075   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
42076     return Res;
42077 
42078   return SDValue();
42079 }
42080 
combineVectorShiftVar(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42081 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
42082                                      TargetLowering::DAGCombinerInfo &DCI,
42083                                      const X86Subtarget &Subtarget) {
42084   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
42085           X86ISD::VSRL == N->getOpcode()) &&
42086          "Unexpected shift opcode");
42087   EVT VT = N->getValueType(0);
42088   SDValue N0 = N->getOperand(0);
42089   SDValue N1 = N->getOperand(1);
42090 
42091   // Shift zero -> zero.
42092   if (ISD::isBuildVectorAllZeros(N0.getNode()))
42093     return DAG.getConstant(0, SDLoc(N), VT);
42094 
42095   // Detect constant shift amounts.
42096   APInt UndefElts;
42097   SmallVector<APInt, 32> EltBits;
42098   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
42099     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
42100     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
42101                                       EltBits[0].getZExtValue(), DAG);
42102   }
42103 
42104   APInt KnownUndef, KnownZero;
42105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42106   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
42107   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
42108                                      KnownZero, DCI))
42109     return SDValue(N, 0);
42110 
42111   return SDValue();
42112 }
42113 
combineVectorShiftImm(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42114 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
42115                                      TargetLowering::DAGCombinerInfo &DCI,
42116                                      const X86Subtarget &Subtarget) {
42117   unsigned Opcode = N->getOpcode();
42118   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
42119           X86ISD::VSRLI == Opcode) &&
42120          "Unexpected shift opcode");
42121   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
42122   EVT VT = N->getValueType(0);
42123   SDValue N0 = N->getOperand(0);
42124   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
42125   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
42126          "Unexpected value type");
42127   assert(N->getOperand(1).getValueType() == MVT::i8 &&
42128          "Unexpected shift amount type");
42129 
42130   // Out of range logical bit shifts are guaranteed to be zero.
42131   // Out of range arithmetic bit shifts splat the sign bit.
42132   unsigned ShiftVal = N->getConstantOperandVal(1);
42133   if (ShiftVal >= NumBitsPerElt) {
42134     if (LogicalShift)
42135       return DAG.getConstant(0, SDLoc(N), VT);
42136     ShiftVal = NumBitsPerElt - 1;
42137   }
42138 
42139   // (shift X, 0) -> X
42140   if (!ShiftVal)
42141     return N0;
42142 
42143   // (shift 0, C) -> 0
42144   if (ISD::isBuildVectorAllZeros(N0.getNode()))
42145     // N0 is all zeros or undef. We guarantee that the bits shifted into the
42146     // result are all zeros, not undef.
42147     return DAG.getConstant(0, SDLoc(N), VT);
42148 
42149   // (VSRAI -1, C) -> -1
42150   if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
42151     // N0 is all ones or undef. We guarantee that the bits shifted into the
42152     // result are all ones, not undef.
42153     return DAG.getConstant(-1, SDLoc(N), VT);
42154 
42155   // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
42156   if (Opcode == N0.getOpcode()) {
42157     unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
42158     unsigned NewShiftVal = ShiftVal + ShiftVal2;
42159     if (NewShiftVal >= NumBitsPerElt) {
42160       // Out of range logical bit shifts are guaranteed to be zero.
42161       // Out of range arithmetic bit shifts splat the sign bit.
42162       if (LogicalShift)
42163         return DAG.getConstant(0, SDLoc(N), VT);
42164       NewShiftVal = NumBitsPerElt - 1;
42165     }
42166     return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
42167                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
42168   }
42169 
42170   // We can decode 'whole byte' logical bit shifts as shuffles.
42171   if (LogicalShift && (ShiftVal % 8) == 0) {
42172     SDValue Op(N, 0);
42173     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
42174       return Res;
42175   }
42176 
42177   // Constant Folding.
42178   APInt UndefElts;
42179   SmallVector<APInt, 32> EltBits;
42180   if (N->isOnlyUserOf(N0.getNode()) &&
42181       getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
42182     assert(EltBits.size() == VT.getVectorNumElements() &&
42183            "Unexpected shift value type");
42184     // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
42185     // created an undef input due to no input bits being demanded, but user
42186     // still expects 0 in other bits.
42187     for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
42188       APInt &Elt = EltBits[i];
42189       if (UndefElts[i])
42190         Elt = 0;
42191       else if (X86ISD::VSHLI == Opcode)
42192         Elt <<= ShiftVal;
42193       else if (X86ISD::VSRAI == Opcode)
42194         Elt.ashrInPlace(ShiftVal);
42195       else
42196         Elt.lshrInPlace(ShiftVal);
42197     }
42198     // Reset undef elements since they were zeroed above.
42199     UndefElts = 0;
42200     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
42201   }
42202 
42203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42204   if (TLI.SimplifyDemandedBits(SDValue(N, 0),
42205                                APInt::getAllOnesValue(NumBitsPerElt), DCI))
42206     return SDValue(N, 0);
42207 
42208   return SDValue();
42209 }
42210 
combineVectorInsert(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42211 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
42212                                    TargetLowering::DAGCombinerInfo &DCI,
42213                                    const X86Subtarget &Subtarget) {
42214   EVT VT = N->getValueType(0);
42215   assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||
42216           (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) ||
42217           N->getOpcode() == ISD::INSERT_VECTOR_ELT) &&
42218          "Unexpected vector insertion");
42219 
42220   if (N->getOpcode() == X86ISD::PINSRB || N->getOpcode() == X86ISD::PINSRW) {
42221     unsigned NumBitsPerElt = VT.getScalarSizeInBits();
42222     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42223     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
42224                                  APInt::getAllOnesValue(NumBitsPerElt), DCI))
42225       return SDValue(N, 0);
42226   }
42227 
42228   // Attempt to combine insertion patterns to a shuffle.
42229   if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
42230     SDValue Op(N, 0);
42231     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
42232       return Res;
42233   }
42234 
42235   return SDValue();
42236 }
42237 
42238 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
42239 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
42240 /// OR -> CMPNEQSS.
combineCompareEqual(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42241 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
42242                                    TargetLowering::DAGCombinerInfo &DCI,
42243                                    const X86Subtarget &Subtarget) {
42244   unsigned opcode;
42245 
42246   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
42247   // we're requiring SSE2 for both.
42248   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
42249     SDValue N0 = N->getOperand(0);
42250     SDValue N1 = N->getOperand(1);
42251     SDValue CMP0 = N0.getOperand(1);
42252     SDValue CMP1 = N1.getOperand(1);
42253     SDLoc DL(N);
42254 
42255     // The SETCCs should both refer to the same CMP.
42256     if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
42257       return SDValue();
42258 
42259     SDValue CMP00 = CMP0->getOperand(0);
42260     SDValue CMP01 = CMP0->getOperand(1);
42261     EVT     VT    = CMP00.getValueType();
42262 
42263     if (VT == MVT::f32 || VT == MVT::f64) {
42264       bool ExpectingFlags = false;
42265       // Check for any users that want flags:
42266       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
42267            !ExpectingFlags && UI != UE; ++UI)
42268         switch (UI->getOpcode()) {
42269         default:
42270         case ISD::BR_CC:
42271         case ISD::BRCOND:
42272         case ISD::SELECT:
42273           ExpectingFlags = true;
42274           break;
42275         case ISD::CopyToReg:
42276         case ISD::SIGN_EXTEND:
42277         case ISD::ZERO_EXTEND:
42278         case ISD::ANY_EXTEND:
42279           break;
42280         }
42281 
42282       if (!ExpectingFlags) {
42283         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
42284         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
42285 
42286         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
42287           X86::CondCode tmp = cc0;
42288           cc0 = cc1;
42289           cc1 = tmp;
42290         }
42291 
42292         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
42293             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
42294           // FIXME: need symbolic constants for these magic numbers.
42295           // See X86ATTInstPrinter.cpp:printSSECC().
42296           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
42297           if (Subtarget.hasAVX512()) {
42298             SDValue FSetCC =
42299                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
42300                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
42301             // Need to fill with zeros to ensure the bitcast will produce zeroes
42302             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
42303             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
42304                                       DAG.getConstant(0, DL, MVT::v16i1),
42305                                       FSetCC, DAG.getIntPtrConstant(0, DL));
42306             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
42307                                       N->getSimpleValueType(0));
42308           }
42309           SDValue OnesOrZeroesF =
42310               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
42311                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
42312 
42313           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
42314           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
42315 
42316           if (is64BitFP && !Subtarget.is64Bit()) {
42317             // On a 32-bit target, we cannot bitcast the 64-bit float to a
42318             // 64-bit integer, since that's not a legal type. Since
42319             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
42320             // bits, but can do this little dance to extract the lowest 32 bits
42321             // and work with those going forward.
42322             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
42323                                            OnesOrZeroesF);
42324             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
42325             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
42326                                         Vector32, DAG.getIntPtrConstant(0, DL));
42327             IntVT = MVT::i32;
42328           }
42329 
42330           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
42331           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
42332                                       DAG.getConstant(1, DL, IntVT));
42333           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
42334                                               ANDed);
42335           return OneBitOfTruth;
42336         }
42337       }
42338     }
42339   }
42340   return SDValue();
42341 }
42342 
42343 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
combineANDXORWithAllOnesIntoANDNP(SDNode * N,SelectionDAG & DAG)42344 static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
42345   assert(N->getOpcode() == ISD::AND);
42346 
42347   MVT VT = N->getSimpleValueType(0);
42348   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
42349     return SDValue();
42350 
42351   SDValue X, Y;
42352   SDValue N0 = N->getOperand(0);
42353   SDValue N1 = N->getOperand(1);
42354 
42355   auto GetNot = [&VT, &DAG](SDValue V) {
42356     // Basic X = NOT(Y) detection.
42357     if (SDValue Not = IsNOT(V, DAG))
42358       return Not;
42359     // Fold BROADCAST(NOT(Y)) -> BROADCAST(Y).
42360     if (V.getOpcode() == X86ISD::VBROADCAST) {
42361       SDValue Src = V.getOperand(0);
42362       EVT SrcVT = Src.getValueType();
42363       if (!SrcVT.isVector())
42364         return SDValue();
42365       if (SDValue Not = IsNOT(Src, DAG))
42366         return DAG.getNode(X86ISD::VBROADCAST, SDLoc(V), VT,
42367                            DAG.getBitcast(SrcVT, Not));
42368     }
42369     return SDValue();
42370   };
42371 
42372   if (SDValue Not = GetNot(N0)) {
42373     X = Not;
42374     Y = N1;
42375   } else if (SDValue Not = GetNot(N1)) {
42376     X = Not;
42377     Y = N0;
42378   } else
42379     return SDValue();
42380 
42381   X = DAG.getBitcast(VT, X);
42382   Y = DAG.getBitcast(VT, Y);
42383   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
42384 }
42385 
42386 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
42387 // logical operations, like in the example below.
42388 //   or (and (truncate x, truncate y)),
42389 //      (xor (truncate z, build_vector (constants)))
42390 // Given a target type \p VT, we generate
42391 //   or (and x, y), (xor z, zext(build_vector (constants)))
42392 // given x, y and z are of type \p VT. We can do so, if operands are either
42393 // truncates from VT types, the second operand is a vector of constants or can
42394 // be recursively promoted.
PromoteMaskArithmetic(SDNode * N,EVT VT,SelectionDAG & DAG,unsigned Depth)42395 static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
42396                                      unsigned Depth) {
42397   // Limit recursion to avoid excessive compile times.
42398   if (Depth >= SelectionDAG::MaxRecursionDepth)
42399     return SDValue();
42400 
42401   if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
42402       N->getOpcode() != ISD::OR)
42403     return SDValue();
42404 
42405   SDValue N0 = N->getOperand(0);
42406   SDValue N1 = N->getOperand(1);
42407   SDLoc DL(N);
42408 
42409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42410   if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
42411     return SDValue();
42412 
42413   if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
42414     N0 = NN0;
42415   else {
42416     // The Left side has to be a trunc.
42417     if (N0.getOpcode() != ISD::TRUNCATE)
42418       return SDValue();
42419 
42420     // The type of the truncated inputs.
42421     if (N0.getOperand(0).getValueType() != VT)
42422       return SDValue();
42423 
42424     N0 = N0.getOperand(0);
42425   }
42426 
42427   if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
42428     N1 = NN1;
42429   else {
42430     // The right side has to be a 'trunc' or a constant vector.
42431     bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
42432                     N1.getOperand(0).getValueType() == VT;
42433     if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
42434       return SDValue();
42435 
42436     if (RHSTrunc)
42437       N1 = N1.getOperand(0);
42438     else
42439       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
42440   }
42441 
42442   return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
42443 }
42444 
42445 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
42446 // register. In most cases we actually compare or select YMM-sized registers
42447 // and mixing the two types creates horrible code. This method optimizes
42448 // some of the transition sequences.
42449 // Even with AVX-512 this is still useful for removing casts around logical
42450 // operations on vXi1 mask types.
PromoteMaskArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42451 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
42452                                      const X86Subtarget &Subtarget) {
42453   EVT VT = N->getValueType(0);
42454   assert(VT.isVector() && "Expected vector type");
42455 
42456   SDLoc DL(N);
42457   assert((N->getOpcode() == ISD::ANY_EXTEND ||
42458           N->getOpcode() == ISD::ZERO_EXTEND ||
42459           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
42460 
42461   SDValue Narrow = N->getOperand(0);
42462   EVT NarrowVT = Narrow.getValueType();
42463 
42464   // Generate the wide operation.
42465   SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
42466   if (!Op)
42467     return SDValue();
42468   switch (N->getOpcode()) {
42469   default: llvm_unreachable("Unexpected opcode");
42470   case ISD::ANY_EXTEND:
42471     return Op;
42472   case ISD::ZERO_EXTEND:
42473     return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
42474   case ISD::SIGN_EXTEND:
42475     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
42476                        Op, DAG.getValueType(NarrowVT));
42477   }
42478 }
42479 
convertIntLogicToFPLogicOpcode(unsigned Opcode)42480 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
42481   unsigned FPOpcode;
42482   switch (Opcode) {
42483   default: llvm_unreachable("Unexpected input node for FP logic conversion");
42484   case ISD::AND: FPOpcode = X86ISD::FAND; break;
42485   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
42486   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
42487   }
42488   return FPOpcode;
42489 }
42490 
42491 /// If both input operands of a logic op are being cast from floating point
42492 /// types, try to convert this into a floating point logic node to avoid
42493 /// unnecessary moves from SSE to integer registers.
convertIntLogicToFPLogic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42494 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
42495                                         const X86Subtarget &Subtarget) {
42496   EVT VT = N->getValueType(0);
42497   SDValue N0 = N->getOperand(0);
42498   SDValue N1 = N->getOperand(1);
42499   SDLoc DL(N);
42500 
42501   if (N0.getOpcode() != ISD::BITCAST || N1.getOpcode() != ISD::BITCAST)
42502     return SDValue();
42503 
42504   SDValue N00 = N0.getOperand(0);
42505   SDValue N10 = N1.getOperand(0);
42506   EVT N00Type = N00.getValueType();
42507   EVT N10Type = N10.getValueType();
42508 
42509   // Ensure that both types are the same and are legal scalar fp types.
42510   if (N00Type != N10Type ||
42511       !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
42512         (Subtarget.hasSSE2() && N00Type == MVT::f64)))
42513     return SDValue();
42514 
42515   unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
42516   SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
42517   return DAG.getBitcast(VT, FPLogic);
42518 }
42519 
42520 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
42521 // to reduce XMM->GPR traffic.
combineBitOpWithMOVMSK(SDNode * N,SelectionDAG & DAG)42522 static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
42523   unsigned Opc = N->getOpcode();
42524   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
42525          "Unexpected bit opcode");
42526 
42527   SDValue N0 = N->getOperand(0);
42528   SDValue N1 = N->getOperand(1);
42529 
42530   // Both operands must be single use MOVMSK.
42531   if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
42532       N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
42533     return SDValue();
42534 
42535   SDValue Vec0 = N0.getOperand(0);
42536   SDValue Vec1 = N1.getOperand(0);
42537   EVT VecVT0 = Vec0.getValueType();
42538   EVT VecVT1 = Vec1.getValueType();
42539 
42540   // Both MOVMSK operands must be from vectors of the same size and same element
42541   // size, but its OK for a fp/int diff.
42542   if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
42543       VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
42544     return SDValue();
42545 
42546   SDLoc DL(N);
42547   unsigned VecOpc =
42548       VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
42549   SDValue Result =
42550       DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
42551   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42552 }
42553 
42554 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
42555 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
42556 /// with a shift-right to eliminate loading the vector constant mask value.
combineAndMaskToShift(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42557 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
42558                                      const X86Subtarget &Subtarget) {
42559   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
42560   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
42561   EVT VT0 = Op0.getValueType();
42562   EVT VT1 = Op1.getValueType();
42563 
42564   if (VT0 != VT1 || !VT0.isSimple() || !VT0.isInteger())
42565     return SDValue();
42566 
42567   APInt SplatVal;
42568   if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
42569       !SplatVal.isMask())
42570     return SDValue();
42571 
42572   // Don't prevent creation of ANDN.
42573   if (isBitwiseNot(Op0))
42574     return SDValue();
42575 
42576   if (!SupportedVectorShiftWithImm(VT0.getSimpleVT(), Subtarget, ISD::SRL))
42577     return SDValue();
42578 
42579   unsigned EltBitWidth = VT0.getScalarSizeInBits();
42580   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
42581     return SDValue();
42582 
42583   SDLoc DL(N);
42584   unsigned ShiftVal = SplatVal.countTrailingOnes();
42585   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
42586   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
42587   return DAG.getBitcast(N->getValueType(0), Shift);
42588 }
42589 
42590 // Get the index node from the lowered DAG of a GEP IR instruction with one
42591 // indexing dimension.
getIndexFromUnindexedLoad(LoadSDNode * Ld)42592 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
42593   if (Ld->isIndexed())
42594     return SDValue();
42595 
42596   SDValue Base = Ld->getBasePtr();
42597 
42598   if (Base.getOpcode() != ISD::ADD)
42599     return SDValue();
42600 
42601   SDValue ShiftedIndex = Base.getOperand(0);
42602 
42603   if (ShiftedIndex.getOpcode() != ISD::SHL)
42604     return SDValue();
42605 
42606   return ShiftedIndex.getOperand(0);
42607 
42608 }
42609 
hasBZHI(const X86Subtarget & Subtarget,MVT VT)42610 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
42611   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
42612     switch (VT.getSizeInBits()) {
42613     default: return false;
42614     case 64: return Subtarget.is64Bit() ? true : false;
42615     case 32: return true;
42616     }
42617   }
42618   return false;
42619 }
42620 
42621 // This function recognizes cases where X86 bzhi instruction can replace and
42622 // 'and-load' sequence.
42623 // In case of loading integer value from an array of constants which is defined
42624 // as follows:
42625 //
42626 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
42627 //
42628 // then applying a bitwise and on the result with another input.
42629 // It's equivalent to performing bzhi (zero high bits) on the input, with the
42630 // same index of the load.
combineAndLoadToBZHI(SDNode * Node,SelectionDAG & DAG,const X86Subtarget & Subtarget)42631 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
42632                                     const X86Subtarget &Subtarget) {
42633   MVT VT = Node->getSimpleValueType(0);
42634   SDLoc dl(Node);
42635 
42636   // Check if subtarget has BZHI instruction for the node's type
42637   if (!hasBZHI(Subtarget, VT))
42638     return SDValue();
42639 
42640   // Try matching the pattern for both operands.
42641   for (unsigned i = 0; i < 2; i++) {
42642     SDValue N = Node->getOperand(i);
42643     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
42644 
42645      // continue if the operand is not a load instruction
42646     if (!Ld)
42647       return SDValue();
42648 
42649     const Value *MemOp = Ld->getMemOperand()->getValue();
42650 
42651     if (!MemOp)
42652       return SDValue();
42653 
42654     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
42655       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
42656         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
42657 
42658           Constant *Init = GV->getInitializer();
42659           Type *Ty = Init->getType();
42660           if (!isa<ConstantDataArray>(Init) ||
42661               !Ty->getArrayElementType()->isIntegerTy() ||
42662               Ty->getArrayElementType()->getScalarSizeInBits() !=
42663                   VT.getSizeInBits() ||
42664               Ty->getArrayNumElements() >
42665                   Ty->getArrayElementType()->getScalarSizeInBits())
42666             continue;
42667 
42668           // Check if the array's constant elements are suitable to our case.
42669           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
42670           bool ConstantsMatch = true;
42671           for (uint64_t j = 0; j < ArrayElementCount; j++) {
42672             ConstantInt *Elem =
42673                 dyn_cast<ConstantInt>(Init->getAggregateElement(j));
42674             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
42675               ConstantsMatch = false;
42676               break;
42677             }
42678           }
42679           if (!ConstantsMatch)
42680             continue;
42681 
42682           // Do the transformation (For 32-bit type):
42683           // -> (and (load arr[idx]), inp)
42684           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
42685           //    that will be replaced with one bzhi instruction.
42686           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
42687           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
42688 
42689           // Get the Node which indexes into the array.
42690           SDValue Index = getIndexFromUnindexedLoad(Ld);
42691           if (!Index)
42692             return SDValue();
42693           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
42694 
42695           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
42696           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
42697 
42698           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
42699           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
42700 
42701           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
42702         }
42703       }
42704     }
42705   }
42706   return SDValue();
42707 }
42708 
42709 // Look for (and (ctpop X), 1) which is the IR form of __builtin_parity.
42710 // Turn it into series of XORs and a setnp.
combineParity(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42711 static SDValue combineParity(SDNode *N, SelectionDAG &DAG,
42712                              const X86Subtarget &Subtarget) {
42713   EVT VT = N->getValueType(0);
42714 
42715   // We only support 64-bit and 32-bit. 64-bit requires special handling
42716   // unless the 64-bit popcnt instruction is legal.
42717   if (VT != MVT::i32 && VT != MVT::i64)
42718     return SDValue();
42719 
42720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42721   if (TLI.isTypeLegal(VT) && TLI.isOperationLegal(ISD::CTPOP, VT))
42722     return SDValue();
42723 
42724   SDValue N0 = N->getOperand(0);
42725   SDValue N1 = N->getOperand(1);
42726 
42727   // LHS needs to be a single use CTPOP.
42728   if (N0.getOpcode() != ISD::CTPOP || !N0.hasOneUse())
42729     return SDValue();
42730 
42731   // RHS needs to be 1.
42732   if (!isOneConstant(N1))
42733     return SDValue();
42734 
42735   SDLoc DL(N);
42736   SDValue X = N0.getOperand(0);
42737 
42738   // If this is 64-bit, its always best to xor the two 32-bit pieces together
42739   // even if we have popcnt.
42740   if (VT == MVT::i64) {
42741     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
42742                              DAG.getNode(ISD::SRL, DL, VT, X,
42743                                          DAG.getConstant(32, DL, MVT::i8)));
42744     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
42745     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
42746     // Generate a 32-bit parity idiom. This will bring us back here if we need
42747     // to expand it too.
42748     SDValue Parity = DAG.getNode(ISD::AND, DL, MVT::i32,
42749                                  DAG.getNode(ISD::CTPOP, DL, MVT::i32, X),
42750                                  DAG.getConstant(1, DL, MVT::i32));
42751     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Parity);
42752   }
42753   assert(VT == MVT::i32 && "Unexpected VT!");
42754 
42755   // Xor the high and low 16-bits together using a 32-bit operation.
42756   SDValue Hi16 = DAG.getNode(ISD::SRL, DL, VT, X,
42757                              DAG.getConstant(16, DL, MVT::i8));
42758   X = DAG.getNode(ISD::XOR, DL, VT, X, Hi16);
42759 
42760   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
42761   // This should allow an h-reg to be used to save a shift.
42762   // FIXME: We only get an h-reg in 32-bit mode.
42763   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
42764                            DAG.getNode(ISD::SRL, DL, VT, X,
42765                                        DAG.getConstant(8, DL, MVT::i8)));
42766   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
42767   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
42768   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
42769 
42770   // Copy the inverse of the parity flag into a register with setcc.
42771   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
42772   // Zero extend to original type.
42773   return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0), Setnp);
42774 }
42775 
42776 
42777 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
42778 // Where C is a mask containing the same number of bits as the setcc and
42779 // where the setcc will freely 0 upper bits of k-register. We can replace the
42780 // undef in the concat with 0s and remove the AND. This mainly helps with
42781 // v2i1/v4i1 setcc being casted to scalar.
combineScalarAndWithMaskSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42782 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
42783                                              const X86Subtarget &Subtarget) {
42784   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
42785 
42786   EVT VT = N->getValueType(0);
42787 
42788   // Make sure this is an AND with constant. We will check the value of the
42789   // constant later.
42790   if (!isa<ConstantSDNode>(N->getOperand(1)))
42791     return SDValue();
42792 
42793   // This is implied by the ConstantSDNode.
42794   assert(!VT.isVector() && "Expected scalar VT!");
42795 
42796   if (N->getOperand(0).getOpcode() != ISD::BITCAST ||
42797       !N->getOperand(0).hasOneUse() ||
42798       !N->getOperand(0).getOperand(0).hasOneUse())
42799     return SDValue();
42800 
42801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42802   SDValue Src = N->getOperand(0).getOperand(0);
42803   EVT SrcVT = Src.getValueType();
42804   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
42805       !TLI.isTypeLegal(SrcVT))
42806     return SDValue();
42807 
42808   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
42809     return SDValue();
42810 
42811   // We only care about the first subvector of the concat, we expect the
42812   // other subvectors to be ignored due to the AND if we make the change.
42813   SDValue SubVec = Src.getOperand(0);
42814   EVT SubVecVT = SubVec.getValueType();
42815 
42816   // First subvector should be a setcc with a legal result type. The RHS of the
42817   // AND should be a mask with this many bits.
42818   if (SubVec.getOpcode() != ISD::SETCC || !TLI.isTypeLegal(SubVecVT) ||
42819       !N->getConstantOperandAPInt(1).isMask(SubVecVT.getVectorNumElements()))
42820     return SDValue();
42821 
42822   EVT SetccVT = SubVec.getOperand(0).getValueType();
42823   if (!TLI.isTypeLegal(SetccVT) ||
42824       !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
42825     return SDValue();
42826 
42827   if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
42828     return SDValue();
42829 
42830   // We passed all the checks. Rebuild the concat_vectors with zeroes
42831   // and cast it back to VT.
42832   SDLoc dl(N);
42833   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
42834                               DAG.getConstant(0, dl, SubVecVT));
42835   Ops[0] = SubVec;
42836   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
42837                                Ops);
42838   return DAG.getBitcast(VT, Concat);
42839 }
42840 
combineAnd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)42841 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
42842                           TargetLowering::DAGCombinerInfo &DCI,
42843                           const X86Subtarget &Subtarget) {
42844   EVT VT = N->getValueType(0);
42845 
42846   // If this is SSE1 only convert to FAND to avoid scalarization.
42847   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
42848     return DAG.getBitcast(
42849         MVT::v4i32, DAG.getNode(X86ISD::FAND, SDLoc(N), MVT::v4f32,
42850                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
42851                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
42852   }
42853 
42854   // Use a 32-bit and+zext if upper bits known zero.
42855   if (VT == MVT::i64 && Subtarget.is64Bit() &&
42856       !isa<ConstantSDNode>(N->getOperand(1))) {
42857     APInt HiMask = APInt::getHighBitsSet(64, 32);
42858     if (DAG.MaskedValueIsZero(N->getOperand(1), HiMask) ||
42859         DAG.MaskedValueIsZero(N->getOperand(0), HiMask)) {
42860       SDLoc dl(N);
42861       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(0));
42862       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(1));
42863       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
42864                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
42865     }
42866   }
42867 
42868   // This must be done before legalization has expanded the ctpop.
42869   if (SDValue V = combineParity(N, DAG, Subtarget))
42870     return V;
42871 
42872   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
42873   // TODO: Support multiple SrcOps.
42874   if (VT == MVT::i1) {
42875     SmallVector<SDValue, 2> SrcOps;
42876     SmallVector<APInt, 2> SrcPartials;
42877     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
42878         SrcOps.size() == 1) {
42879       SDLoc dl(N);
42880       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
42881       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
42882       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
42883       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
42884       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
42885         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
42886       if (Mask) {
42887         assert(SrcPartials[0].getBitWidth() == NumElts &&
42888                "Unexpected partial reduction mask");
42889         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
42890         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
42891         return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
42892       }
42893     }
42894   }
42895 
42896   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
42897     return V;
42898 
42899   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
42900     return R;
42901 
42902   if (DCI.isBeforeLegalizeOps())
42903     return SDValue();
42904 
42905   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
42906     return R;
42907 
42908   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
42909     return FPLogic;
42910 
42911   if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
42912     return R;
42913 
42914   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
42915     return ShiftRight;
42916 
42917   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
42918     return R;
42919 
42920   // Attempt to recursively combine a bitmask AND with shuffles.
42921   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
42922     SDValue Op(N, 0);
42923     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
42924       return Res;
42925   }
42926 
42927   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
42928   if ((VT.getScalarSizeInBits() % 8) == 0 &&
42929       N->getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
42930       isa<ConstantSDNode>(N->getOperand(0).getOperand(1))) {
42931     SDValue BitMask = N->getOperand(1);
42932     SDValue SrcVec = N->getOperand(0).getOperand(0);
42933     EVT SrcVecVT = SrcVec.getValueType();
42934 
42935     // Check that the constant bitmask masks whole bytes.
42936     APInt UndefElts;
42937     SmallVector<APInt, 64> EltBits;
42938     if (VT == SrcVecVT.getScalarType() &&
42939         N->getOperand(0)->isOnlyUserOf(SrcVec.getNode()) &&
42940         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
42941         llvm::all_of(EltBits, [](APInt M) {
42942           return M.isNullValue() || M.isAllOnesValue();
42943         })) {
42944       unsigned NumElts = SrcVecVT.getVectorNumElements();
42945       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
42946       unsigned Idx = N->getOperand(0).getConstantOperandVal(1);
42947 
42948       // Create a root shuffle mask from the byte mask and the extracted index.
42949       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
42950       for (unsigned i = 0; i != Scale; ++i) {
42951         if (UndefElts[i])
42952           continue;
42953         int VecIdx = Scale * Idx + i;
42954         ShuffleMask[VecIdx] =
42955             EltBits[i].isNullValue() ? SM_SentinelZero : VecIdx;
42956       }
42957 
42958       if (SDValue Shuffle = combineX86ShufflesRecursively(
42959               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
42960               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
42961         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), VT, Shuffle,
42962                            N->getOperand(0).getOperand(1));
42963     }
42964   }
42965 
42966   return SDValue();
42967 }
42968 
42969 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
canonicalizeBitSelect(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)42970 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
42971                                      const X86Subtarget &Subtarget) {
42972   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
42973 
42974   MVT VT = N->getSimpleValueType(0);
42975   if (!VT.isVector() || (VT.getScalarSizeInBits() % 8) != 0)
42976     return SDValue();
42977 
42978   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
42979   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
42980   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
42981     return SDValue();
42982 
42983   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
42984   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
42985   bool UseVPTERNLOG = (Subtarget.hasAVX512() && VT.is512BitVector()) ||
42986                       Subtarget.hasVLX();
42987   if (!(Subtarget.hasXOP() || UseVPTERNLOG ||
42988         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
42989     return SDValue();
42990 
42991   // Attempt to extract constant byte masks.
42992   APInt UndefElts0, UndefElts1;
42993   SmallVector<APInt, 32> EltBits0, EltBits1;
42994   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
42995                                      false, false))
42996     return SDValue();
42997   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
42998                                      false, false))
42999     return SDValue();
43000 
43001   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
43002     // TODO - add UNDEF elts support.
43003     if (UndefElts0[i] || UndefElts1[i])
43004       return SDValue();
43005     if (EltBits0[i] != ~EltBits1[i])
43006       return SDValue();
43007   }
43008 
43009   SDLoc DL(N);
43010 
43011   if (UseVPTERNLOG) {
43012     // Emit a VPTERNLOG node directly.
43013     SDValue A = DAG.getBitcast(VT, N0.getOperand(1));
43014     SDValue B = DAG.getBitcast(VT, N0.getOperand(0));
43015     SDValue C = DAG.getBitcast(VT, N1.getOperand(0));
43016     SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
43017     return DAG.getNode(X86ISD::VPTERNLOG, DL, VT, A, B, C, Imm);
43018   }
43019 
43020   SDValue X = N->getOperand(0);
43021   SDValue Y =
43022       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
43023                   DAG.getBitcast(VT, N1.getOperand(0)));
43024   return DAG.getNode(ISD::OR, DL, VT, X, Y);
43025 }
43026 
43027 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
matchLogicBlend(SDNode * N,SDValue & X,SDValue & Y,SDValue & Mask)43028 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
43029   if (N->getOpcode() != ISD::OR)
43030     return false;
43031 
43032   SDValue N0 = N->getOperand(0);
43033   SDValue N1 = N->getOperand(1);
43034 
43035   // Canonicalize AND to LHS.
43036   if (N1.getOpcode() == ISD::AND)
43037     std::swap(N0, N1);
43038 
43039   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
43040   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
43041     return false;
43042 
43043   Mask = N1.getOperand(0);
43044   X = N1.getOperand(1);
43045 
43046   // Check to see if the mask appeared in both the AND and ANDNP.
43047   if (N0.getOperand(0) == Mask)
43048     Y = N0.getOperand(1);
43049   else if (N0.getOperand(1) == Mask)
43050     Y = N0.getOperand(0);
43051   else
43052     return false;
43053 
43054   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
43055   // ANDNP combine allows other combines to happen that prevent matching.
43056   return true;
43057 }
43058 
43059 // Try to fold:
43060 //   (or (and (m, y), (pandn m, x)))
43061 // into:
43062 //   (vselect m, x, y)
43063 // As a special case, try to fold:
43064 //   (or (and (m, (sub 0, x)), (pandn m, x)))
43065 // into:
43066 //   (sub (xor X, M), M)
combineLogicBlendIntoPBLENDV(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)43067 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
43068                                             const X86Subtarget &Subtarget) {
43069   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
43070 
43071   EVT VT = N->getValueType(0);
43072   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
43073         (VT.is256BitVector() && Subtarget.hasInt256())))
43074     return SDValue();
43075 
43076   SDValue X, Y, Mask;
43077   if (!matchLogicBlend(N, X, Y, Mask))
43078     return SDValue();
43079 
43080   // Validate that X, Y, and Mask are bitcasts, and see through them.
43081   Mask = peekThroughBitcasts(Mask);
43082   X = peekThroughBitcasts(X);
43083   Y = peekThroughBitcasts(Y);
43084 
43085   EVT MaskVT = Mask.getValueType();
43086   unsigned EltBits = MaskVT.getScalarSizeInBits();
43087 
43088   // TODO: Attempt to handle floating point cases as well?
43089   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
43090     return SDValue();
43091 
43092   SDLoc DL(N);
43093 
43094   // Attempt to combine to conditional negate: (sub (xor X, M), M)
43095   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
43096                                                            DAG, Subtarget))
43097     return Res;
43098 
43099   // PBLENDVB is only available on SSE 4.1.
43100   if (!Subtarget.hasSSE41())
43101     return SDValue();
43102 
43103   // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
43104   if (Subtarget.hasVLX())
43105     return SDValue();
43106 
43107   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
43108 
43109   X = DAG.getBitcast(BlendVT, X);
43110   Y = DAG.getBitcast(BlendVT, Y);
43111   Mask = DAG.getBitcast(BlendVT, Mask);
43112   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
43113   return DAG.getBitcast(VT, Mask);
43114 }
43115 
43116 // Helper function for combineOrCmpEqZeroToCtlzSrl
43117 // Transforms:
43118 //   seteq(cmp x, 0)
43119 //   into:
43120 //   srl(ctlz x), log2(bitsize(x))
43121 // Input pattern is checked by caller.
lowerX86CmpEqZeroToCtlzSrl(SDValue Op,EVT ExtTy,SelectionDAG & DAG)43122 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
43123                                           SelectionDAG &DAG) {
43124   SDValue Cmp = Op.getOperand(1);
43125   EVT VT = Cmp.getOperand(0).getValueType();
43126   unsigned Log2b = Log2_32(VT.getSizeInBits());
43127   SDLoc dl(Op);
43128   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
43129   // The result of the shift is true or false, and on X86, the 32-bit
43130   // encoding of shr and lzcnt is more desirable.
43131   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
43132   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
43133                             DAG.getConstant(Log2b, dl, MVT::i8));
43134   return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
43135 }
43136 
43137 // Try to transform:
43138 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
43139 //   into:
43140 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
43141 // Will also attempt to match more generic cases, eg:
43142 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
43143 // Only applies if the target supports the FastLZCNT feature.
combineOrCmpEqZeroToCtlzSrl(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43144 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
43145                                            TargetLowering::DAGCombinerInfo &DCI,
43146                                            const X86Subtarget &Subtarget) {
43147   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
43148     return SDValue();
43149 
43150   auto isORCandidate = [](SDValue N) {
43151     return (N->getOpcode() == ISD::OR && N->hasOneUse());
43152   };
43153 
43154   // Check the zero extend is extending to 32-bit or more. The code generated by
43155   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
43156   // instructions to clear the upper bits.
43157   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
43158       !isORCandidate(N->getOperand(0)))
43159     return SDValue();
43160 
43161   // Check the node matches: setcc(eq, cmp 0)
43162   auto isSetCCCandidate = [](SDValue N) {
43163     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
43164            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
43165            N->getOperand(1).getOpcode() == X86ISD::CMP &&
43166            isNullConstant(N->getOperand(1).getOperand(1)) &&
43167            N->getOperand(1).getValueType().bitsGE(MVT::i32);
43168   };
43169 
43170   SDNode *OR = N->getOperand(0).getNode();
43171   SDValue LHS = OR->getOperand(0);
43172   SDValue RHS = OR->getOperand(1);
43173 
43174   // Save nodes matching or(or, setcc(eq, cmp 0)).
43175   SmallVector<SDNode *, 2> ORNodes;
43176   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
43177           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
43178     ORNodes.push_back(OR);
43179     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
43180     LHS = OR->getOperand(0);
43181     RHS = OR->getOperand(1);
43182   }
43183 
43184   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
43185   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
43186       !isORCandidate(SDValue(OR, 0)))
43187     return SDValue();
43188 
43189   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
43190   // to
43191   // or(srl(ctlz),srl(ctlz)).
43192   // The dag combiner can then fold it into:
43193   // srl(or(ctlz, ctlz)).
43194   EVT VT = OR->getValueType(0);
43195   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
43196   SDValue Ret, NewRHS;
43197   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
43198     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
43199 
43200   if (!Ret)
43201     return SDValue();
43202 
43203   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
43204   while (ORNodes.size() > 0) {
43205     OR = ORNodes.pop_back_val();
43206     LHS = OR->getOperand(0);
43207     RHS = OR->getOperand(1);
43208     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
43209     if (RHS->getOpcode() == ISD::OR)
43210       std::swap(LHS, RHS);
43211     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
43212     if (!NewRHS)
43213       return SDValue();
43214     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
43215   }
43216 
43217   if (Ret)
43218     Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
43219 
43220   return Ret;
43221 }
43222 
combineOr(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43223 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
43224                          TargetLowering::DAGCombinerInfo &DCI,
43225                          const X86Subtarget &Subtarget) {
43226   SDValue N0 = N->getOperand(0);
43227   SDValue N1 = N->getOperand(1);
43228   EVT VT = N->getValueType(0);
43229 
43230   // If this is SSE1 only convert to FOR to avoid scalarization.
43231   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
43232     return DAG.getBitcast(MVT::v4i32,
43233                           DAG.getNode(X86ISD::FOR, SDLoc(N), MVT::v4f32,
43234                                       DAG.getBitcast(MVT::v4f32, N0),
43235                                       DAG.getBitcast(MVT::v4f32, N1)));
43236   }
43237 
43238   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
43239   // TODO: Support multiple SrcOps.
43240   if (VT == MVT::i1) {
43241     SmallVector<SDValue, 2> SrcOps;
43242     SmallVector<APInt, 2> SrcPartials;
43243     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
43244         SrcOps.size() == 1) {
43245       SDLoc dl(N);
43246       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43247       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
43248       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
43249       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
43250       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
43251         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
43252       if (Mask) {
43253         assert(SrcPartials[0].getBitWidth() == NumElts &&
43254                "Unexpected partial reduction mask");
43255         SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
43256         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
43257         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
43258         return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
43259       }
43260     }
43261   }
43262 
43263   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
43264     return R;
43265 
43266   if (DCI.isBeforeLegalizeOps())
43267     return SDValue();
43268 
43269   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
43270     return R;
43271 
43272   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
43273     return FPLogic;
43274 
43275   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
43276     return R;
43277 
43278   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
43279     return R;
43280 
43281   // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
43282   // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
43283   // iff the upper elements of the non-shifted arg are zero.
43284   // KUNPCK require 16+ bool vector elements.
43285   if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
43286     unsigned NumElts = VT.getVectorNumElements();
43287     unsigned HalfElts = NumElts / 2;
43288     APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
43289     if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
43290         N1.getConstantOperandAPInt(1) == HalfElts &&
43291         DAG.MaskedValueIsZero(N0, APInt(1, 1), UpperElts)) {
43292       SDLoc dl(N);
43293       return DAG.getNode(
43294           ISD::CONCAT_VECTORS, dl, VT,
43295           extractSubVector(N0, 0, DAG, dl, HalfElts),
43296           extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
43297     }
43298     if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
43299         N0.getConstantOperandAPInt(1) == HalfElts &&
43300         DAG.MaskedValueIsZero(N1, APInt(1, 1), UpperElts)) {
43301       SDLoc dl(N);
43302       return DAG.getNode(
43303           ISD::CONCAT_VECTORS, dl, VT,
43304           extractSubVector(N1, 0, DAG, dl, HalfElts),
43305           extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
43306     }
43307   }
43308 
43309   // Attempt to recursively combine an OR of shuffles.
43310   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
43311     SDValue Op(N, 0);
43312     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43313       return Res;
43314   }
43315 
43316   return SDValue();
43317 }
43318 
43319 /// Try to turn tests against the signbit in the form of:
43320 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
43321 /// into:
43322 ///   SETGT(X, -1)
foldXorTruncShiftIntoCmp(SDNode * N,SelectionDAG & DAG)43323 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
43324   // This is only worth doing if the output type is i8 or i1.
43325   EVT ResultType = N->getValueType(0);
43326   if (ResultType != MVT::i8 && ResultType != MVT::i1)
43327     return SDValue();
43328 
43329   SDValue N0 = N->getOperand(0);
43330   SDValue N1 = N->getOperand(1);
43331 
43332   // We should be performing an xor against a truncated shift.
43333   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
43334     return SDValue();
43335 
43336   // Make sure we are performing an xor against one.
43337   if (!isOneConstant(N1))
43338     return SDValue();
43339 
43340   // SetCC on x86 zero extends so only act on this if it's a logical shift.
43341   SDValue Shift = N0.getOperand(0);
43342   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
43343     return SDValue();
43344 
43345   // Make sure we are truncating from one of i16, i32 or i64.
43346   EVT ShiftTy = Shift.getValueType();
43347   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
43348     return SDValue();
43349 
43350   // Make sure the shift amount extracts the sign bit.
43351   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
43352       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
43353     return SDValue();
43354 
43355   // Create a greater-than comparison against -1.
43356   // N.B. Using SETGE against 0 works but we want a canonical looking
43357   // comparison, using SETGT matches up with what TranslateX86CC.
43358   SDLoc DL(N);
43359   SDValue ShiftOp = Shift.getOperand(0);
43360   EVT ShiftOpTy = ShiftOp.getValueType();
43361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43362   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
43363                                                *DAG.getContext(), ResultType);
43364   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
43365                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
43366   if (SetCCResultType != ResultType)
43367     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
43368   return Cond;
43369 }
43370 
43371 /// Turn vector tests of the signbit in the form of:
43372 ///   xor (sra X, elt_size(X)-1), -1
43373 /// into:
43374 ///   pcmpgt X, -1
43375 ///
43376 /// This should be called before type legalization because the pattern may not
43377 /// persist after that.
foldVectorXorShiftIntoCmp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)43378 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
43379                                          const X86Subtarget &Subtarget) {
43380   EVT VT = N->getValueType(0);
43381   if (!VT.isSimple())
43382     return SDValue();
43383 
43384   switch (VT.getSimpleVT().SimpleTy) {
43385   default: return SDValue();
43386   case MVT::v16i8:
43387   case MVT::v8i16:
43388   case MVT::v4i32:
43389   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
43390   case MVT::v32i8:
43391   case MVT::v16i16:
43392   case MVT::v8i32:
43393   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
43394   }
43395 
43396   // There must be a shift right algebraic before the xor, and the xor must be a
43397   // 'not' operation.
43398   SDValue Shift = N->getOperand(0);
43399   SDValue Ones = N->getOperand(1);
43400   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
43401       !ISD::isBuildVectorAllOnes(Ones.getNode()))
43402     return SDValue();
43403 
43404   // The shift should be smearing the sign bit across each vector element.
43405   auto *ShiftAmt =
43406       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
43407   if (!ShiftAmt ||
43408       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
43409     return SDValue();
43410 
43411   // Create a greater-than comparison against -1. We don't use the more obvious
43412   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
43413   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
43414 }
43415 
43416 /// Detect patterns of truncation with unsigned saturation:
43417 ///
43418 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
43419 ///   Return the source value x to be truncated or SDValue() if the pattern was
43420 ///   not matched.
43421 ///
43422 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
43423 ///   where C1 >= 0 and C2 is unsigned max of destination type.
43424 ///
43425 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
43426 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
43427 ///
43428 ///   These two patterns are equivalent to:
43429 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
43430 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
43431 ///   pattern was not matched.
detectUSatPattern(SDValue In,EVT VT,SelectionDAG & DAG,const SDLoc & DL)43432 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
43433                                  const SDLoc &DL) {
43434   EVT InVT = In.getValueType();
43435 
43436   // Saturation with truncation. We truncate from InVT to VT.
43437   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
43438          "Unexpected types for truncate operation");
43439 
43440   // Match min/max and return limit value as a parameter.
43441   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
43442     if (V.getOpcode() == Opcode &&
43443         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
43444       return V.getOperand(0);
43445     return SDValue();
43446   };
43447 
43448   APInt C1, C2;
43449   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
43450     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
43451     // the element size of the destination type.
43452     if (C2.isMask(VT.getScalarSizeInBits()))
43453       return UMin;
43454 
43455   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
43456     if (MatchMinMax(SMin, ISD::SMAX, C1))
43457       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
43458         return SMin;
43459 
43460   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
43461     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
43462       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
43463           C2.uge(C1)) {
43464         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
43465       }
43466 
43467   return SDValue();
43468 }
43469 
43470 /// Detect patterns of truncation with signed saturation:
43471 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
43472 ///                  signed_max_of_dest_type)) to dest_type)
43473 /// or:
43474 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
43475 ///                  signed_min_of_dest_type)) to dest_type).
43476 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
43477 /// Return the source value to be truncated or SDValue() if the pattern was not
43478 /// matched.
detectSSatPattern(SDValue In,EVT VT,bool MatchPackUS=false)43479 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
43480   unsigned NumDstBits = VT.getScalarSizeInBits();
43481   unsigned NumSrcBits = In.getScalarValueSizeInBits();
43482   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
43483 
43484   auto MatchMinMax = [](SDValue V, unsigned Opcode,
43485                         const APInt &Limit) -> SDValue {
43486     APInt C;
43487     if (V.getOpcode() == Opcode &&
43488         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
43489       return V.getOperand(0);
43490     return SDValue();
43491   };
43492 
43493   APInt SignedMax, SignedMin;
43494   if (MatchPackUS) {
43495     SignedMax = APInt::getAllOnesValue(NumDstBits).zext(NumSrcBits);
43496     SignedMin = APInt(NumSrcBits, 0);
43497   } else {
43498     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
43499     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
43500   }
43501 
43502   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
43503     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
43504       return SMax;
43505 
43506   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
43507     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
43508       return SMin;
43509 
43510   return SDValue();
43511 }
43512 
combineTruncateWithSat(SDValue In,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)43513 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
43514                                       SelectionDAG &DAG,
43515                                       const X86Subtarget &Subtarget) {
43516   if (!Subtarget.hasSSE2() || !VT.isVector())
43517     return SDValue();
43518 
43519   EVT SVT = VT.getVectorElementType();
43520   EVT InVT = In.getValueType();
43521   EVT InSVT = InVT.getVectorElementType();
43522 
43523   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
43524   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
43525   // and concatenate at the same time. Then we can use a final vpmovuswb to
43526   // clip to 0-255.
43527   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
43528       InVT == MVT::v16i32 && VT == MVT::v16i8) {
43529     if (auto USatVal = detectSSatPattern(In, VT, true)) {
43530       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
43531       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
43532                                            DL, DAG, Subtarget);
43533       assert(Mid && "Failed to pack!");
43534       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
43535     }
43536   }
43537 
43538   // vXi32 truncate instructions are available with AVX512F.
43539   // vXi16 truncate instructions are only available with AVX512BW.
43540   // For 256-bit or smaller vectors, we require VLX.
43541   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
43542   // If the result type is 256-bits or larger and we have disable 512-bit
43543   // registers, we should go ahead and use the pack instructions if possible.
43544   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
43545                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
43546                       (InVT.getSizeInBits() > 128) &&
43547                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
43548                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
43549 
43550   if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
43551       VT.getSizeInBits() >= 64 &&
43552       (SVT == MVT::i8 || SVT == MVT::i16) &&
43553       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
43554     if (auto USatVal = detectSSatPattern(In, VT, true)) {
43555       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
43556       // Only do this when the result is at least 64 bits or we'll leaving
43557       // dangling PACKSSDW nodes.
43558       if (SVT == MVT::i8 && InSVT == MVT::i32) {
43559         EVT MidVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
43560                                      VT.getVectorNumElements());
43561         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
43562                                              DAG, Subtarget);
43563         assert(Mid && "Failed to pack!");
43564         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
43565                                            Subtarget);
43566         assert(V && "Failed to pack!");
43567         return V;
43568       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
43569         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
43570                                       Subtarget);
43571     }
43572     if (auto SSatVal = detectSSatPattern(In, VT))
43573       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
43574                                     Subtarget);
43575   }
43576 
43577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43578   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
43579       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI())) {
43580     unsigned TruncOpc = 0;
43581     SDValue SatVal;
43582     if (auto SSatVal = detectSSatPattern(In, VT)) {
43583       SatVal = SSatVal;
43584       TruncOpc = X86ISD::VTRUNCS;
43585     } else if (auto USatVal = detectUSatPattern(In, VT, DAG, DL)) {
43586       SatVal = USatVal;
43587       TruncOpc = X86ISD::VTRUNCUS;
43588     }
43589     if (SatVal) {
43590       unsigned ResElts = VT.getVectorNumElements();
43591       // If the input type is less than 512 bits and we don't have VLX, we need
43592       // to widen to 512 bits.
43593       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
43594         unsigned NumConcats = 512 / InVT.getSizeInBits();
43595         ResElts *= NumConcats;
43596         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
43597         ConcatOps[0] = SatVal;
43598         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
43599                                 NumConcats * InVT.getVectorNumElements());
43600         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
43601       }
43602       // Widen the result if its narrower than 128 bits.
43603       if (ResElts * SVT.getSizeInBits() < 128)
43604         ResElts = 128 / SVT.getSizeInBits();
43605       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
43606       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
43607       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
43608                          DAG.getIntPtrConstant(0, DL));
43609     }
43610   }
43611 
43612   return SDValue();
43613 }
43614 
43615 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
43616 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
43617 /// X86ISD::AVG instruction.
detectAVGPattern(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)43618 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
43619                                 const X86Subtarget &Subtarget,
43620                                 const SDLoc &DL) {
43621   if (!VT.isVector())
43622     return SDValue();
43623   EVT InVT = In.getValueType();
43624   unsigned NumElems = VT.getVectorNumElements();
43625 
43626   EVT ScalarVT = VT.getVectorElementType();
43627   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
43628         NumElems >= 2 && isPowerOf2_32(NumElems)))
43629     return SDValue();
43630 
43631   // InScalarVT is the intermediate type in AVG pattern and it should be greater
43632   // than the original input type (i8/i16).
43633   EVT InScalarVT = InVT.getVectorElementType();
43634   if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
43635     return SDValue();
43636 
43637   if (!Subtarget.hasSSE2())
43638     return SDValue();
43639 
43640   // Detect the following pattern:
43641   //
43642   //   %1 = zext <N x i8> %a to <N x i32>
43643   //   %2 = zext <N x i8> %b to <N x i32>
43644   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
43645   //   %4 = add nuw nsw <N x i32> %3, %2
43646   //   %5 = lshr <N x i32> %N, <i32 1 x N>
43647   //   %6 = trunc <N x i32> %5 to <N x i8>
43648   //
43649   // In AVX512, the last instruction can also be a trunc store.
43650   if (In.getOpcode() != ISD::SRL)
43651     return SDValue();
43652 
43653   // A lambda checking the given SDValue is a constant vector and each element
43654   // is in the range [Min, Max].
43655   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
43656     return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
43657       return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
43658     });
43659   };
43660 
43661   // Check if each element of the vector is right-shifted by one.
43662   auto LHS = In.getOperand(0);
43663   auto RHS = In.getOperand(1);
43664   if (!IsConstVectorInRange(RHS, 1, 1))
43665     return SDValue();
43666   if (LHS.getOpcode() != ISD::ADD)
43667     return SDValue();
43668 
43669   // Detect a pattern of a + b + 1 where the order doesn't matter.
43670   SDValue Operands[3];
43671   Operands[0] = LHS.getOperand(0);
43672   Operands[1] = LHS.getOperand(1);
43673 
43674   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
43675                        ArrayRef<SDValue> Ops) {
43676     return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
43677   };
43678 
43679   // Take care of the case when one of the operands is a constant vector whose
43680   // element is in the range [1, 256].
43681   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
43682       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
43683       Operands[0].getOperand(0).getValueType() == VT) {
43684     // The pattern is detected. Subtract one from the constant vector, then
43685     // demote it and emit X86ISD::AVG instruction.
43686     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
43687     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
43688     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
43689     return SplitOpsAndApply(DAG, Subtarget, DL, VT,
43690                             { Operands[0].getOperand(0), Operands[1] },
43691                             AVGBuilder);
43692   }
43693 
43694   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
43695   // Match the or case only if its 'add-like' - can be replaced by an add.
43696   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
43697     if (ISD::ADD == V.getOpcode()) {
43698       Op0 = V.getOperand(0);
43699       Op1 = V.getOperand(1);
43700       return true;
43701     }
43702     if (ISD::ZERO_EXTEND != V.getOpcode())
43703       return false;
43704     V = V.getOperand(0);
43705     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
43706         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
43707       return false;
43708     Op0 = V.getOperand(0);
43709     Op1 = V.getOperand(1);
43710     return true;
43711   };
43712 
43713   SDValue Op0, Op1;
43714   if (FindAddLike(Operands[0], Op0, Op1))
43715     std::swap(Operands[0], Operands[1]);
43716   else if (!FindAddLike(Operands[1], Op0, Op1))
43717     return SDValue();
43718   Operands[2] = Op0;
43719   Operands[1] = Op1;
43720 
43721   // Now we have three operands of two additions. Check that one of them is a
43722   // constant vector with ones, and the other two can be promoted from i8/i16.
43723   for (int i = 0; i < 3; ++i) {
43724     if (!IsConstVectorInRange(Operands[i], 1, 1))
43725       continue;
43726     std::swap(Operands[i], Operands[2]);
43727 
43728     // Check if Operands[0] and Operands[1] are results of type promotion.
43729     for (int j = 0; j < 2; ++j)
43730       if (Operands[j].getValueType() != VT) {
43731         if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
43732             Operands[j].getOperand(0).getValueType() != VT)
43733           return SDValue();
43734         Operands[j] = Operands[j].getOperand(0);
43735       }
43736 
43737     // The pattern is detected, emit X86ISD::AVG instruction(s).
43738     return SplitOpsAndApply(DAG, Subtarget, DL, VT, {Operands[0], Operands[1]},
43739                             AVGBuilder);
43740   }
43741 
43742   return SDValue();
43743 }
43744 
combineLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43745 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
43746                            TargetLowering::DAGCombinerInfo &DCI,
43747                            const X86Subtarget &Subtarget) {
43748   LoadSDNode *Ld = cast<LoadSDNode>(N);
43749   EVT RegVT = Ld->getValueType(0);
43750   EVT MemVT = Ld->getMemoryVT();
43751   SDLoc dl(Ld);
43752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43753 
43754   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
43755   // into two 16-byte operations. Also split non-temporal aligned loads on
43756   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
43757   ISD::LoadExtType Ext = Ld->getExtensionType();
43758   bool Fast;
43759   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
43760       Ext == ISD::NON_EXTLOAD &&
43761       ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
43762         Ld->getAlignment() >= 16) ||
43763        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
43764                                *Ld->getMemOperand(), &Fast) &&
43765         !Fast))) {
43766     unsigned NumElems = RegVT.getVectorNumElements();
43767     if (NumElems < 2)
43768       return SDValue();
43769 
43770     unsigned HalfOffset = 16;
43771     SDValue Ptr1 = Ld->getBasePtr();
43772     SDValue Ptr2 = DAG.getMemBasePlusOffset(Ptr1, HalfOffset, dl);
43773     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
43774                                   NumElems / 2);
43775     SDValue Load1 =
43776         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
43777                     Ld->getOriginalAlign(),
43778                     Ld->getMemOperand()->getFlags());
43779     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
43780                                 Ld->getPointerInfo().getWithOffset(HalfOffset),
43781                                 Ld->getOriginalAlign(),
43782                                 Ld->getMemOperand()->getFlags());
43783     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
43784                              Load1.getValue(1), Load2.getValue(1));
43785 
43786     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
43787     return DCI.CombineTo(N, NewVec, TF, true);
43788   }
43789 
43790   // Bool vector load - attempt to cast to an integer, as we have good
43791   // (vXiY *ext(vXi1 bitcast(iX))) handling.
43792   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
43793       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
43794     unsigned NumElts = RegVT.getVectorNumElements();
43795     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
43796     if (TLI.isTypeLegal(IntVT)) {
43797       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
43798                                     Ld->getPointerInfo(),
43799                                     Ld->getOriginalAlign(),
43800                                     Ld->getMemOperand()->getFlags());
43801       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
43802       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
43803     }
43804   }
43805 
43806   // Cast ptr32 and ptr64 pointers to the default address space before a load.
43807   unsigned AddrSpace = Ld->getAddressSpace();
43808   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
43809       AddrSpace == X86AS::PTR32_UPTR) {
43810     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
43811     if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
43812       SDValue Cast =
43813           DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
43814       return DAG.getLoad(RegVT, dl, Ld->getChain(), Cast, Ld->getPointerInfo(),
43815                          Ld->getOriginalAlign(),
43816                          Ld->getMemOperand()->getFlags());
43817     }
43818   }
43819 
43820   return SDValue();
43821 }
43822 
43823 /// If V is a build vector of boolean constants and exactly one of those
43824 /// constants is true, return the operand index of that true element.
43825 /// Otherwise, return -1.
getOneTrueElt(SDValue V)43826 static int getOneTrueElt(SDValue V) {
43827   // This needs to be a build vector of booleans.
43828   // TODO: Checking for the i1 type matches the IR definition for the mask,
43829   // but the mask check could be loosened to i8 or other types. That might
43830   // also require checking more than 'allOnesValue'; eg, the x86 HW
43831   // instructions only require that the MSB is set for each mask element.
43832   // The ISD::MSTORE comments/definition do not specify how the mask operand
43833   // is formatted.
43834   auto *BV = dyn_cast<BuildVectorSDNode>(V);
43835   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
43836     return -1;
43837 
43838   int TrueIndex = -1;
43839   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
43840   for (unsigned i = 0; i < NumElts; ++i) {
43841     const SDValue &Op = BV->getOperand(i);
43842     if (Op.isUndef())
43843       continue;
43844     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
43845     if (!ConstNode)
43846       return -1;
43847     if (ConstNode->getAPIntValue().isAllOnesValue()) {
43848       // If we already found a one, this is too many.
43849       if (TrueIndex >= 0)
43850         return -1;
43851       TrueIndex = i;
43852     }
43853   }
43854   return TrueIndex;
43855 }
43856 
43857 /// Given a masked memory load/store operation, return true if it has one mask
43858 /// bit set. If it has one mask bit set, then also return the memory address of
43859 /// the scalar element to load/store, the vector index to insert/extract that
43860 /// scalar element, and the alignment for the scalar memory access.
getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode * MaskedOp,SelectionDAG & DAG,SDValue & Addr,SDValue & Index,unsigned & Alignment)43861 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
43862                                          SelectionDAG &DAG, SDValue &Addr,
43863                                          SDValue &Index, unsigned &Alignment) {
43864   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
43865   if (TrueMaskElt < 0)
43866     return false;
43867 
43868   // Get the address of the one scalar element that is specified by the mask
43869   // using the appropriate offset from the base pointer.
43870   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
43871   Addr = MaskedOp->getBasePtr();
43872   if (TrueMaskElt != 0) {
43873     unsigned Offset = TrueMaskElt * EltVT.getStoreSize();
43874     Addr = DAG.getMemBasePlusOffset(Addr, Offset, SDLoc(MaskedOp));
43875   }
43876 
43877   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
43878   Alignment = MinAlign(MaskedOp->getAlignment(), EltVT.getStoreSize());
43879   return true;
43880 }
43881 
43882 /// If exactly one element of the mask is set for a non-extending masked load,
43883 /// it is a scalar load and vector insert.
43884 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
43885 /// mask have already been optimized in IR, so we don't bother with those here.
43886 static SDValue
reduceMaskedLoadToScalarLoad(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43887 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
43888                              TargetLowering::DAGCombinerInfo &DCI) {
43889   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
43890   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
43891   // However, some target hooks may need to be added to know when the transform
43892   // is profitable. Endianness would also have to be considered.
43893 
43894   SDValue Addr, VecIndex;
43895   unsigned Alignment;
43896   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment))
43897     return SDValue();
43898 
43899   // Load the one scalar element that is specified by the mask using the
43900   // appropriate offset from the base pointer.
43901   SDLoc DL(ML);
43902   EVT VT = ML->getValueType(0);
43903   EVT EltVT = VT.getVectorElementType();
43904   SDValue Load =
43905       DAG.getLoad(EltVT, DL, ML->getChain(), Addr, ML->getPointerInfo(),
43906                   Alignment, ML->getMemOperand()->getFlags());
43907 
43908   // Insert the loaded element into the appropriate place in the vector.
43909   SDValue Insert = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
43910                                ML->getPassThru(), Load, VecIndex);
43911   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
43912 }
43913 
43914 static SDValue
combineMaskedLoadConstantMask(MaskedLoadSDNode * ML,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)43915 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
43916                               TargetLowering::DAGCombinerInfo &DCI) {
43917   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
43918   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
43919     return SDValue();
43920 
43921   SDLoc DL(ML);
43922   EVT VT = ML->getValueType(0);
43923 
43924   // If we are loading the first and last elements of a vector, it is safe and
43925   // always faster to load the whole vector. Replace the masked load with a
43926   // vector load and select.
43927   unsigned NumElts = VT.getVectorNumElements();
43928   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
43929   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
43930   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
43931   if (LoadFirstElt && LoadLastElt) {
43932     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
43933                                 ML->getMemOperand());
43934     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
43935                                   ML->getPassThru());
43936     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
43937   }
43938 
43939   // Convert a masked load with a constant mask into a masked load and a select.
43940   // This allows the select operation to use a faster kind of select instruction
43941   // (for example, vblendvps -> vblendps).
43942 
43943   // Don't try this if the pass-through operand is already undefined. That would
43944   // cause an infinite loop because that's what we're about to create.
43945   if (ML->getPassThru().isUndef())
43946     return SDValue();
43947 
43948   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
43949     return SDValue();
43950 
43951   // The new masked load has an undef pass-through operand. The select uses the
43952   // original pass-through operand.
43953   SDValue NewML = DAG.getMaskedLoad(
43954       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
43955       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
43956       ML->getAddressingMode(), ML->getExtensionType());
43957   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
43958                                 ML->getPassThru());
43959 
43960   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
43961 }
43962 
combineMaskedLoad(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)43963 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
43964                                  TargetLowering::DAGCombinerInfo &DCI,
43965                                  const X86Subtarget &Subtarget) {
43966   auto *Mld = cast<MaskedLoadSDNode>(N);
43967 
43968   // TODO: Expanding load with constant mask may be optimized as well.
43969   if (Mld->isExpandingLoad())
43970     return SDValue();
43971 
43972   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
43973     if (SDValue ScalarLoad = reduceMaskedLoadToScalarLoad(Mld, DAG, DCI))
43974       return ScalarLoad;
43975 
43976     // TODO: Do some AVX512 subsets benefit from this transform?
43977     if (!Subtarget.hasAVX512())
43978       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
43979         return Blend;
43980   }
43981 
43982   // If the mask value has been legalized to a non-boolean vector, try to
43983   // simplify ops leading up to it. We only demand the MSB of each lane.
43984   SDValue Mask = Mld->getMask();
43985   if (Mask.getScalarValueSizeInBits() != 1) {
43986     EVT VT = Mld->getValueType(0);
43987     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43988     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
43989     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
43990       if (N->getOpcode() != ISD::DELETED_NODE)
43991         DCI.AddToWorklist(N);
43992       return SDValue(N, 0);
43993     }
43994     if (SDValue NewMask =
43995             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
43996       return DAG.getMaskedLoad(
43997           VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
43998           NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
43999           Mld->getAddressingMode(), Mld->getExtensionType());
44000   }
44001 
44002   return SDValue();
44003 }
44004 
44005 /// If exactly one element of the mask is set for a non-truncating masked store,
44006 /// it is a vector extract and scalar store.
44007 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
44008 /// mask have already been optimized in IR, so we don't bother with those here.
reduceMaskedStoreToScalarStore(MaskedStoreSDNode * MS,SelectionDAG & DAG)44009 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
44010                                               SelectionDAG &DAG) {
44011   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
44012   // However, some target hooks may need to be added to know when the transform
44013   // is profitable. Endianness would also have to be considered.
44014 
44015   SDValue Addr, VecIndex;
44016   unsigned Alignment;
44017   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment))
44018     return SDValue();
44019 
44020   // Extract the one scalar element that is actually being stored.
44021   SDLoc DL(MS);
44022   EVT VT = MS->getValue().getValueType();
44023   EVT EltVT = VT.getVectorElementType();
44024   SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
44025                                 MS->getValue(), VecIndex);
44026 
44027   // Store that element at the appropriate offset from the base pointer.
44028   return DAG.getStore(MS->getChain(), DL, Extract, Addr, MS->getPointerInfo(),
44029                       Alignment, MS->getMemOperand()->getFlags());
44030 }
44031 
combineMaskedStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44032 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
44033                                   TargetLowering::DAGCombinerInfo &DCI,
44034                                   const X86Subtarget &Subtarget) {
44035   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
44036   if (Mst->isCompressingStore())
44037     return SDValue();
44038 
44039   EVT VT = Mst->getValue().getValueType();
44040   SDLoc dl(Mst);
44041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44042 
44043   if (Mst->isTruncatingStore())
44044     return SDValue();
44045 
44046   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG))
44047     return ScalarStore;
44048 
44049   // If the mask value has been legalized to a non-boolean vector, try to
44050   // simplify ops leading up to it. We only demand the MSB of each lane.
44051   SDValue Mask = Mst->getMask();
44052   if (Mask.getScalarValueSizeInBits() != 1) {
44053     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
44054     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
44055       if (N->getOpcode() != ISD::DELETED_NODE)
44056         DCI.AddToWorklist(N);
44057       return SDValue(N, 0);
44058     }
44059     if (SDValue NewMask =
44060             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
44061       return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
44062                                 Mst->getBasePtr(), Mst->getOffset(), NewMask,
44063                                 Mst->getMemoryVT(), Mst->getMemOperand(),
44064                                 Mst->getAddressingMode());
44065   }
44066 
44067   SDValue Value = Mst->getValue();
44068   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
44069       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
44070                             Mst->getMemoryVT())) {
44071     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
44072                               Mst->getBasePtr(), Mst->getOffset(), Mask,
44073                               Mst->getMemoryVT(), Mst->getMemOperand(),
44074                               Mst->getAddressingMode(), true);
44075   }
44076 
44077   return SDValue();
44078 }
44079 
combineStore(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44080 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
44081                             TargetLowering::DAGCombinerInfo &DCI,
44082                             const X86Subtarget &Subtarget) {
44083   StoreSDNode *St = cast<StoreSDNode>(N);
44084   EVT StVT = St->getMemoryVT();
44085   SDLoc dl(St);
44086   SDValue StoredVal = St->getValue();
44087   EVT VT = StoredVal.getValueType();
44088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44089 
44090   // Convert a store of vXi1 into a store of iX and a bitcast.
44091   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
44092       VT.getVectorElementType() == MVT::i1) {
44093 
44094     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
44095     StoredVal = DAG.getBitcast(NewVT, StoredVal);
44096 
44097     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
44098                         St->getPointerInfo(), St->getOriginalAlign(),
44099                         St->getMemOperand()->getFlags());
44100   }
44101 
44102   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
44103   // This will avoid a copy to k-register.
44104   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
44105       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
44106       StoredVal.getOperand(0).getValueType() == MVT::i8) {
44107     return DAG.getStore(St->getChain(), dl, StoredVal.getOperand(0),
44108                         St->getBasePtr(), St->getPointerInfo(),
44109                         St->getOriginalAlign(),
44110                         St->getMemOperand()->getFlags());
44111   }
44112 
44113   // Widen v2i1/v4i1 stores to v8i1.
44114   if ((VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
44115       Subtarget.hasAVX512()) {
44116     unsigned NumConcats = 8 / VT.getVectorNumElements();
44117     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(VT));
44118     Ops[0] = StoredVal;
44119     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
44120     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
44121                         St->getPointerInfo(), St->getOriginalAlign(),
44122                         St->getMemOperand()->getFlags());
44123   }
44124 
44125   // Turn vXi1 stores of constants into a scalar store.
44126   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
44127        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
44128       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
44129     // If its a v64i1 store without 64-bit support, we need two stores.
44130     if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
44131       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
44132                                       StoredVal->ops().slice(0, 32));
44133       Lo = combinevXi1ConstantToInteger(Lo, DAG);
44134       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
44135                                       StoredVal->ops().slice(32, 32));
44136       Hi = combinevXi1ConstantToInteger(Hi, DAG);
44137 
44138       SDValue Ptr0 = St->getBasePtr();
44139       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 4, dl);
44140 
44141       SDValue Ch0 =
44142           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
44143                        St->getOriginalAlign(),
44144                        St->getMemOperand()->getFlags());
44145       SDValue Ch1 =
44146           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
44147                        St->getPointerInfo().getWithOffset(4),
44148                        St->getOriginalAlign(),
44149                        St->getMemOperand()->getFlags());
44150       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
44151     }
44152 
44153     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
44154     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
44155                         St->getPointerInfo(), St->getOriginalAlign(),
44156                         St->getMemOperand()->getFlags());
44157   }
44158 
44159   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
44160   // Sandy Bridge, perform two 16-byte stores.
44161   bool Fast;
44162   if (VT.is256BitVector() && StVT == VT &&
44163       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
44164                              *St->getMemOperand(), &Fast) &&
44165       !Fast) {
44166     unsigned NumElems = VT.getVectorNumElements();
44167     if (NumElems < 2)
44168       return SDValue();
44169 
44170     return splitVectorStore(St, DAG);
44171   }
44172 
44173   // Split under-aligned vector non-temporal stores.
44174   if (St->isNonTemporal() && StVT == VT &&
44175       St->getAlignment() < VT.getStoreSize()) {
44176     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
44177     // vectors or the legalizer can scalarize it to use MOVNTI.
44178     if (VT.is256BitVector() || VT.is512BitVector()) {
44179       unsigned NumElems = VT.getVectorNumElements();
44180       if (NumElems < 2)
44181         return SDValue();
44182       return splitVectorStore(St, DAG);
44183     }
44184 
44185     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
44186     // to use MOVNTI.
44187     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
44188       MVT NTVT = Subtarget.hasSSE4A()
44189                      ? MVT::v2f64
44190                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
44191       return scalarizeVectorStore(St, NTVT, DAG);
44192     }
44193   }
44194 
44195   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
44196   // supported, but avx512f is by extending to v16i32 and truncating.
44197   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
44198       St->getValue().getOpcode() == ISD::TRUNCATE &&
44199       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
44200       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
44201       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
44202     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32, St->getValue());
44203     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
44204                              MVT::v16i8, St->getMemOperand());
44205   }
44206 
44207   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
44208   if (!St->isTruncatingStore() && StoredVal.hasOneUse() &&
44209       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
44210        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
44211       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
44212     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
44213     return EmitTruncSStore(IsSigned, St->getChain(),
44214                            dl, StoredVal.getOperand(0), St->getBasePtr(),
44215                            VT, St->getMemOperand(), DAG);
44216   }
44217 
44218   // Optimize trunc store (of multiple scalars) to shuffle and store.
44219   // First, pack all of the elements in one place. Next, store to memory
44220   // in fewer chunks.
44221   if (St->isTruncatingStore() && VT.isVector()) {
44222     // Check if we can detect an AVG pattern from the truncation. If yes,
44223     // replace the trunc store by a normal store with the result of X86ISD::AVG
44224     // instruction.
44225     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
44226       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
44227                                          Subtarget, dl))
44228         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
44229                             St->getPointerInfo(), St->getOriginalAlign(),
44230                             St->getMemOperand()->getFlags());
44231 
44232     if (TLI.isTruncStoreLegal(VT, StVT)) {
44233       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
44234         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
44235                                dl, Val, St->getBasePtr(),
44236                                St->getMemoryVT(), St->getMemOperand(), DAG);
44237       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
44238                                           DAG, dl))
44239         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
44240                                dl, Val, St->getBasePtr(),
44241                                St->getMemoryVT(), St->getMemOperand(), DAG);
44242     }
44243 
44244     return SDValue();
44245   }
44246 
44247   // Cast ptr32 and ptr64 pointers to the default address space before a store.
44248   unsigned AddrSpace = St->getAddressSpace();
44249   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
44250       AddrSpace == X86AS::PTR32_UPTR) {
44251     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
44252     if (PtrVT != St->getBasePtr().getSimpleValueType()) {
44253       SDValue Cast =
44254           DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
44255       return DAG.getStore(St->getChain(), dl, StoredVal, Cast,
44256                           St->getPointerInfo(), St->getOriginalAlign(),
44257                           St->getMemOperand()->getFlags(), St->getAAInfo());
44258     }
44259   }
44260 
44261   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
44262   // the FP state in cases where an emms may be missing.
44263   // A preferable solution to the general problem is to figure out the right
44264   // places to insert EMMS.  This qualifies as a quick hack.
44265 
44266   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
44267   if (VT.getSizeInBits() != 64)
44268     return SDValue();
44269 
44270   const Function &F = DAG.getMachineFunction().getFunction();
44271   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
44272   bool F64IsLegal =
44273       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
44274   if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
44275       isa<LoadSDNode>(St->getValue()) &&
44276       cast<LoadSDNode>(St->getValue())->isSimple() &&
44277       St->getChain().hasOneUse() && St->isSimple()) {
44278     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
44279 
44280     if (!ISD::isNormalLoad(Ld))
44281       return SDValue();
44282 
44283     // Avoid the transformation if there are multiple uses of the loaded value.
44284     if (!Ld->hasNUsesOfValue(1, 0))
44285       return SDValue();
44286 
44287     SDLoc LdDL(Ld);
44288     SDLoc StDL(N);
44289     // Lower to a single movq load/store pair.
44290     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
44291                                 Ld->getBasePtr(), Ld->getMemOperand());
44292 
44293     // Make sure new load is placed in same chain order.
44294     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
44295     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
44296                         St->getMemOperand());
44297   }
44298 
44299   // This is similar to the above case, but here we handle a scalar 64-bit
44300   // integer store that is extracted from a vector on a 32-bit target.
44301   // If we have SSE2, then we can treat it like a floating-point double
44302   // to get past legalization. The execution dependencies fixup pass will
44303   // choose the optimal machine instruction for the store if this really is
44304   // an integer or v2f32 rather than an f64.
44305   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
44306       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
44307     SDValue OldExtract = St->getOperand(1);
44308     SDValue ExtOp0 = OldExtract.getOperand(0);
44309     unsigned VecSize = ExtOp0.getValueSizeInBits();
44310     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
44311     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
44312     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
44313                                      BitCast, OldExtract.getOperand(1));
44314     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
44315                         St->getPointerInfo(), St->getOriginalAlign(),
44316                         St->getMemOperand()->getFlags());
44317   }
44318 
44319   return SDValue();
44320 }
44321 
combineVEXTRACT_STORE(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)44322 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
44323                                      TargetLowering::DAGCombinerInfo &DCI,
44324                                      const X86Subtarget &Subtarget) {
44325   auto *St = cast<MemIntrinsicSDNode>(N);
44326 
44327   SDValue StoredVal = N->getOperand(1);
44328   MVT VT = StoredVal.getSimpleValueType();
44329   EVT MemVT = St->getMemoryVT();
44330 
44331   // Figure out which elements we demand.
44332   unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
44333   APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
44334 
44335   APInt KnownUndef, KnownZero;
44336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44337   if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, KnownUndef,
44338                                      KnownZero, DCI)) {
44339     if (N->getOpcode() != ISD::DELETED_NODE)
44340       DCI.AddToWorklist(N);
44341     return SDValue(N, 0);
44342   }
44343 
44344   return SDValue();
44345 }
44346 
44347 /// Return 'true' if this vector operation is "horizontal"
44348 /// and return the operands for the horizontal operation in LHS and RHS.  A
44349 /// horizontal operation performs the binary operation on successive elements
44350 /// of its first operand, then on successive elements of its second operand,
44351 /// returning the resulting values in a vector.  For example, if
44352 ///   A = < float a0, float a1, float a2, float a3 >
44353 /// and
44354 ///   B = < float b0, float b1, float b2, float b3 >
44355 /// then the result of doing a horizontal operation on A and B is
44356 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
44357 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
44358 /// A horizontal-op B, for some already available A and B, and if so then LHS is
44359 /// set to A, RHS to B, and the routine returns 'true'.
isHorizontalBinOp(SDValue & LHS,SDValue & RHS,SelectionDAG & DAG,const X86Subtarget & Subtarget,bool IsCommutative)44360 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, SelectionDAG &DAG,
44361                               const X86Subtarget &Subtarget,
44362                               bool IsCommutative) {
44363   // If either operand is undef, bail out. The binop should be simplified.
44364   if (LHS.isUndef() || RHS.isUndef())
44365     return false;
44366 
44367   // Look for the following pattern:
44368   //   A = < float a0, float a1, float a2, float a3 >
44369   //   B = < float b0, float b1, float b2, float b3 >
44370   // and
44371   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
44372   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
44373   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
44374   // which is A horizontal-op B.
44375 
44376   MVT VT = LHS.getSimpleValueType();
44377   assert((VT.is128BitVector() || VT.is256BitVector()) &&
44378          "Unsupported vector type for horizontal add/sub");
44379   unsigned NumElts = VT.getVectorNumElements();
44380 
44381   // TODO - can we make a general helper method that does all of this for us?
44382   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
44383                         SmallVectorImpl<int> &ShuffleMask) {
44384     if (Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
44385       if (!Op.getOperand(0).isUndef())
44386         N0 = Op.getOperand(0);
44387       if (!Op.getOperand(1).isUndef())
44388         N1 = Op.getOperand(1);
44389       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
44390       ShuffleMask.append(Mask.begin(), Mask.end());
44391       return;
44392     }
44393     bool UseSubVector = false;
44394     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
44395         Op.getOperand(0).getValueType().is256BitVector() &&
44396         llvm::isNullConstant(Op.getOperand(1))) {
44397       Op = Op.getOperand(0);
44398       UseSubVector = true;
44399     }
44400     bool IsUnary;
44401     SmallVector<SDValue, 2> SrcOps;
44402     SmallVector<int, 16> SrcShuffleMask;
44403     SDValue BC = peekThroughBitcasts(Op);
44404     if (isTargetShuffle(BC.getOpcode()) &&
44405         getTargetShuffleMask(BC.getNode(), BC.getSimpleValueType(), false,
44406                              SrcOps, SrcShuffleMask, IsUnary)) {
44407       if (!UseSubVector && SrcShuffleMask.size() == NumElts &&
44408           SrcOps.size() <= 2) {
44409         N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
44410         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
44411         ShuffleMask.append(SrcShuffleMask.begin(), SrcShuffleMask.end());
44412       }
44413       if (UseSubVector && (SrcShuffleMask.size() == (NumElts * 2)) &&
44414           SrcOps.size() == 1) {
44415         N0 = extract128BitVector(SrcOps[0], 0, DAG, SDLoc(Op));
44416         N1 = extract128BitVector(SrcOps[0], NumElts, DAG, SDLoc(Op));
44417         ArrayRef<int> Mask = ArrayRef<int>(SrcShuffleMask).slice(0, NumElts);
44418         ShuffleMask.append(Mask.begin(), Mask.end());
44419       }
44420     }
44421   };
44422 
44423   // View LHS in the form
44424   //   LHS = VECTOR_SHUFFLE A, B, LMask
44425   // If LHS is not a shuffle, then pretend it is the identity shuffle:
44426   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
44427   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
44428   SDValue A, B;
44429   SmallVector<int, 16> LMask;
44430   GetShuffle(LHS, A, B, LMask);
44431 
44432   // Likewise, view RHS in the form
44433   //   RHS = VECTOR_SHUFFLE C, D, RMask
44434   SDValue C, D;
44435   SmallVector<int, 16> RMask;
44436   GetShuffle(RHS, C, D, RMask);
44437 
44438   // At least one of the operands should be a vector shuffle.
44439   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
44440   if (NumShuffles == 0)
44441     return false;
44442 
44443   if (LMask.empty()) {
44444     A = LHS;
44445     for (unsigned i = 0; i != NumElts; ++i)
44446       LMask.push_back(i);
44447   }
44448 
44449   if (RMask.empty()) {
44450     C = RHS;
44451     for (unsigned i = 0; i != NumElts; ++i)
44452       RMask.push_back(i);
44453   }
44454 
44455   // If A and B occur in reverse order in RHS, then canonicalize by commuting
44456   // RHS operands and shuffle mask.
44457   if (A != C) {
44458     std::swap(C, D);
44459     ShuffleVectorSDNode::commuteMask(RMask);
44460   }
44461   // Check that the shuffles are both shuffling the same vectors.
44462   if (!(A == C && B == D))
44463     return false;
44464 
44465   // LHS and RHS are now:
44466   //   LHS = shuffle A, B, LMask
44467   //   RHS = shuffle A, B, RMask
44468   // Check that the masks correspond to performing a horizontal operation.
44469   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
44470   // so we just repeat the inner loop if this is a 256-bit op.
44471   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
44472   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
44473   assert((NumEltsPer128BitChunk % 2 == 0) &&
44474          "Vector type should have an even number of elements in each lane");
44475   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
44476     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
44477       // Ignore undefined components.
44478       int LIdx = LMask[i + j], RIdx = RMask[i + j];
44479       if (LIdx < 0 || RIdx < 0 ||
44480           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
44481           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
44482         continue;
44483 
44484       // The  low half of the 128-bit result must choose from A.
44485       // The high half of the 128-bit result must choose from B,
44486       // unless B is undef. In that case, we are always choosing from A.
44487       unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
44488       unsigned Src = B.getNode() ? i >= NumEltsPer64BitChunk : 0;
44489 
44490       // Check that successive elements are being operated on. If not, this is
44491       // not a horizontal operation.
44492       int Index = 2 * (i % NumEltsPer64BitChunk) + NumElts * Src + j;
44493       if (!(LIdx == Index && RIdx == Index + 1) &&
44494           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
44495         return false;
44496     }
44497   }
44498 
44499   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
44500   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
44501 
44502   if (!shouldUseHorizontalOp(LHS == RHS && NumShuffles < 2, DAG, Subtarget))
44503     return false;
44504 
44505   LHS = DAG.getBitcast(VT, LHS);
44506   RHS = DAG.getBitcast(VT, RHS);
44507   return true;
44508 }
44509 
44510 /// Do target-specific dag combines on floating-point adds/subs.
combineFaddFsub(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44511 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
44512                                const X86Subtarget &Subtarget) {
44513   EVT VT = N->getValueType(0);
44514   SDValue LHS = N->getOperand(0);
44515   SDValue RHS = N->getOperand(1);
44516   bool IsFadd = N->getOpcode() == ISD::FADD;
44517   auto HorizOpcode = IsFadd ? X86ISD::FHADD : X86ISD::FHSUB;
44518   assert((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode");
44519 
44520   // Try to synthesize horizontal add/sub from adds/subs of shuffles.
44521   if (((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
44522        (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
44523       isHorizontalBinOp(LHS, RHS, DAG, Subtarget, IsFadd))
44524     return DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
44525 
44526   return SDValue();
44527 }
44528 
44529 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
44530 /// the codegen.
44531 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
44532 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
44533 ///       anything that is guaranteed to be transformed by DAGCombiner.
combineTruncatedArithmetic(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)44534 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
44535                                           const X86Subtarget &Subtarget,
44536                                           const SDLoc &DL) {
44537   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
44538   SDValue Src = N->getOperand(0);
44539   unsigned SrcOpcode = Src.getOpcode();
44540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44541 
44542   EVT VT = N->getValueType(0);
44543   EVT SrcVT = Src.getValueType();
44544 
44545   auto IsFreeTruncation = [VT](SDValue Op) {
44546     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
44547 
44548     // See if this has been extended from a smaller/equal size to
44549     // the truncation size, allowing a truncation to combine with the extend.
44550     unsigned Opcode = Op.getOpcode();
44551     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
44552          Opcode == ISD::ZERO_EXTEND) &&
44553         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
44554       return true;
44555 
44556     // See if this is a single use constant which can be constant folded.
44557     // NOTE: We don't peek throught bitcasts here because there is currently
44558     // no support for constant folding truncate+bitcast+vector_of_constants. So
44559     // we'll just send up with a truncate on both operands which will
44560     // get turned back into (truncate (binop)) causing an infinite loop.
44561     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
44562   };
44563 
44564   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
44565     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
44566     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
44567     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
44568   };
44569 
44570   // Don't combine if the operation has other uses.
44571   if (!Src.hasOneUse())
44572     return SDValue();
44573 
44574   // Only support vector truncation for now.
44575   // TODO: i64 scalar math would benefit as well.
44576   if (!VT.isVector())
44577     return SDValue();
44578 
44579   // In most cases its only worth pre-truncating if we're only facing the cost
44580   // of one truncation.
44581   // i.e. if one of the inputs will constant fold or the input is repeated.
44582   switch (SrcOpcode) {
44583   case ISD::MUL:
44584     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
44585     // better to truncate if we have the chance.
44586     if (SrcVT.getScalarType() == MVT::i64 &&
44587         TLI.isOperationLegal(SrcOpcode, VT) &&
44588         !TLI.isOperationLegal(SrcOpcode, SrcVT))
44589       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
44590     LLVM_FALLTHROUGH;
44591   case ISD::AND:
44592   case ISD::XOR:
44593   case ISD::OR:
44594   case ISD::ADD:
44595   case ISD::SUB: {
44596     SDValue Op0 = Src.getOperand(0);
44597     SDValue Op1 = Src.getOperand(1);
44598     if (TLI.isOperationLegal(SrcOpcode, VT) &&
44599         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
44600       return TruncateArithmetic(Op0, Op1);
44601     break;
44602   }
44603   }
44604 
44605   return SDValue();
44606 }
44607 
44608 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
44609 /// e.g. trunc <8 x i32> X to <8 x i16> -->
44610 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
44611 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
combineVectorTruncationWithPACKUS(SDNode * N,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)44612 static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
44613                                                  const X86Subtarget &Subtarget,
44614                                                  SelectionDAG &DAG) {
44615   SDValue In = N->getOperand(0);
44616   EVT InVT = In.getValueType();
44617   EVT OutVT = N->getValueType(0);
44618 
44619   APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
44620                                     OutVT.getScalarSizeInBits());
44621   In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
44622   return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
44623 }
44624 
44625 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
combineVectorTruncationWithPACKSS(SDNode * N,const SDLoc & DL,const X86Subtarget & Subtarget,SelectionDAG & DAG)44626 static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
44627                                                  const X86Subtarget &Subtarget,
44628                                                  SelectionDAG &DAG) {
44629   SDValue In = N->getOperand(0);
44630   EVT InVT = In.getValueType();
44631   EVT OutVT = N->getValueType(0);
44632   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
44633                    DAG.getValueType(OutVT));
44634   return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
44635 }
44636 
44637 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
44638 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
44639 /// legalization the truncation will be translated into a BUILD_VECTOR with each
44640 /// element that is extracted from a vector and then truncated, and it is
44641 /// difficult to do this optimization based on them.
combineVectorTruncation(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44642 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
44643                                        const X86Subtarget &Subtarget) {
44644   EVT OutVT = N->getValueType(0);
44645   if (!OutVT.isVector())
44646     return SDValue();
44647 
44648   SDValue In = N->getOperand(0);
44649   if (!In.getValueType().isSimple())
44650     return SDValue();
44651 
44652   EVT InVT = In.getValueType();
44653   unsigned NumElems = OutVT.getVectorNumElements();
44654 
44655   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
44656   // SSE2, and we need to take care of it specially.
44657   // AVX512 provides vpmovdb.
44658   if (!Subtarget.hasSSE2() || Subtarget.hasAVX2())
44659     return SDValue();
44660 
44661   EVT OutSVT = OutVT.getVectorElementType();
44662   EVT InSVT = InVT.getVectorElementType();
44663   if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
44664         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
44665         NumElems >= 8))
44666     return SDValue();
44667 
44668   // SSSE3's pshufb results in less instructions in the cases below.
44669   if (Subtarget.hasSSSE3() && NumElems == 8 &&
44670       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
44671        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
44672     return SDValue();
44673 
44674   SDLoc DL(N);
44675   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
44676   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
44677   // truncate 2 x v4i32 to v8i16.
44678   if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
44679     return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
44680   if (InSVT == MVT::i32)
44681     return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
44682 
44683   return SDValue();
44684 }
44685 
44686 /// This function transforms vector truncation of 'extended sign-bits' or
44687 /// 'extended zero-bits' values.
44688 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
combineVectorSignBitsTruncation(SDNode * N,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)44689 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
44690                                                SelectionDAG &DAG,
44691                                                const X86Subtarget &Subtarget) {
44692   // Requires SSE2.
44693   if (!Subtarget.hasSSE2())
44694     return SDValue();
44695 
44696   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
44697     return SDValue();
44698 
44699   SDValue In = N->getOperand(0);
44700   if (!In.getValueType().isSimple())
44701     return SDValue();
44702 
44703   MVT VT = N->getValueType(0).getSimpleVT();
44704   MVT SVT = VT.getScalarType();
44705 
44706   MVT InVT = In.getValueType().getSimpleVT();
44707   MVT InSVT = InVT.getScalarType();
44708 
44709   // Check we have a truncation suited for PACKSS/PACKUS.
44710   if (!isPowerOf2_32(VT.getVectorNumElements()))
44711     return SDValue();
44712   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
44713     return SDValue();
44714   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
44715     return SDValue();
44716 
44717   // Truncation to sub-128bit vXi32 can be better handled with shuffles.
44718   if (SVT == MVT::i32 && VT.getSizeInBits() < 128)
44719     return SDValue();
44720 
44721   // AVX512 has fast truncate, but if the input is already going to be split,
44722   // there's no harm in trying pack.
44723   if (Subtarget.hasAVX512() &&
44724       !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
44725         InVT.is512BitVector()))
44726     return SDValue();
44727 
44728   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
44729   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
44730 
44731   // Use PACKUS if the input has zero-bits that extend all the way to the
44732   // packed/truncated value. e.g. masks, zext_in_reg, etc.
44733   KnownBits Known = DAG.computeKnownBits(In);
44734   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
44735   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
44736     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
44737 
44738   // Use PACKSS if the input has sign-bits that extend all the way to the
44739   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
44740   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
44741 
44742   // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
44743   // a sign splat. ComputeNumSignBits struggles to see through BITCASTs later
44744   // on and combines/simplifications can't then use it.
44745   if (SVT == MVT::i32 && NumSignBits != InSVT.getSizeInBits())
44746     return SDValue();
44747 
44748   if (NumSignBits > (InSVT.getSizeInBits() - NumPackedSignBits))
44749     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
44750 
44751   return SDValue();
44752 }
44753 
44754 // Try to form a MULHU or MULHS node by looking for
44755 // (trunc (srl (mul ext, ext), 16))
44756 // TODO: This is X86 specific because we want to be able to handle wide types
44757 // before type legalization. But we can only do it if the vector will be
44758 // legalized via widening/splitting. Type legalization can't handle promotion
44759 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
44760 // combiner.
combinePMULH(SDValue Src,EVT VT,const SDLoc & DL,SelectionDAG & DAG,const X86Subtarget & Subtarget)44761 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
44762                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
44763   // First instruction should be a right shift of a multiply.
44764   if (Src.getOpcode() != ISD::SRL ||
44765       Src.getOperand(0).getOpcode() != ISD::MUL)
44766     return SDValue();
44767 
44768   if (!Subtarget.hasSSE2())
44769     return SDValue();
44770 
44771   // Only handle vXi16 types that are at least 128-bits unless they will be
44772   // widened.
44773   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
44774     return SDValue();
44775 
44776   // Input type should be at least vXi32.
44777   EVT InVT = Src.getValueType();
44778   if (InVT.getVectorElementType().getSizeInBits() < 32)
44779     return SDValue();
44780 
44781   // Need a shift by 16.
44782   APInt ShiftAmt;
44783   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
44784       ShiftAmt != 16)
44785     return SDValue();
44786 
44787   SDValue LHS = Src.getOperand(0).getOperand(0);
44788   SDValue RHS = Src.getOperand(0).getOperand(1);
44789 
44790   unsigned ExtOpc = LHS.getOpcode();
44791   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
44792       RHS.getOpcode() != ExtOpc)
44793     return SDValue();
44794 
44795   // Peek through the extends.
44796   LHS = LHS.getOperand(0);
44797   RHS = RHS.getOperand(0);
44798 
44799   // Ensure the input types match.
44800   if (LHS.getValueType() != VT || RHS.getValueType() != VT)
44801     return SDValue();
44802 
44803   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
44804   return DAG.getNode(Opc, DL, VT, LHS, RHS);
44805 }
44806 
44807 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
44808 // from one vector with signed bytes from another vector, adds together
44809 // adjacent pairs of 16-bit products, and saturates the result before
44810 // truncating to 16-bits.
44811 //
44812 // Which looks something like this:
44813 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
44814 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
detectPMADDUBSW(SDValue In,EVT VT,SelectionDAG & DAG,const X86Subtarget & Subtarget,const SDLoc & DL)44815 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
44816                                const X86Subtarget &Subtarget,
44817                                const SDLoc &DL) {
44818   if (!VT.isVector() || !Subtarget.hasSSSE3())
44819     return SDValue();
44820 
44821   unsigned NumElems = VT.getVectorNumElements();
44822   EVT ScalarVT = VT.getVectorElementType();
44823   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
44824     return SDValue();
44825 
44826   SDValue SSatVal = detectSSatPattern(In, VT);
44827   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
44828     return SDValue();
44829 
44830   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
44831   // of multiplies from even/odd elements.
44832   SDValue N0 = SSatVal.getOperand(0);
44833   SDValue N1 = SSatVal.getOperand(1);
44834 
44835   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
44836     return SDValue();
44837 
44838   SDValue N00 = N0.getOperand(0);
44839   SDValue N01 = N0.getOperand(1);
44840   SDValue N10 = N1.getOperand(0);
44841   SDValue N11 = N1.getOperand(1);
44842 
44843   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
44844   // Canonicalize zero_extend to LHS.
44845   if (N01.getOpcode() == ISD::ZERO_EXTEND)
44846     std::swap(N00, N01);
44847   if (N11.getOpcode() == ISD::ZERO_EXTEND)
44848     std::swap(N10, N11);
44849 
44850   // Ensure we have a zero_extend and a sign_extend.
44851   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
44852       N01.getOpcode() != ISD::SIGN_EXTEND ||
44853       N10.getOpcode() != ISD::ZERO_EXTEND ||
44854       N11.getOpcode() != ISD::SIGN_EXTEND)
44855     return SDValue();
44856 
44857   // Peek through the extends.
44858   N00 = N00.getOperand(0);
44859   N01 = N01.getOperand(0);
44860   N10 = N10.getOperand(0);
44861   N11 = N11.getOperand(0);
44862 
44863   // Ensure the extend is from vXi8.
44864   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
44865       N01.getValueType().getVectorElementType() != MVT::i8 ||
44866       N10.getValueType().getVectorElementType() != MVT::i8 ||
44867       N11.getValueType().getVectorElementType() != MVT::i8)
44868     return SDValue();
44869 
44870   // All inputs should be build_vectors.
44871   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
44872       N01.getOpcode() != ISD::BUILD_VECTOR ||
44873       N10.getOpcode() != ISD::BUILD_VECTOR ||
44874       N11.getOpcode() != ISD::BUILD_VECTOR)
44875     return SDValue();
44876 
44877   // N00/N10 are zero extended. N01/N11 are sign extended.
44878 
44879   // For each element, we need to ensure we have an odd element from one vector
44880   // multiplied by the odd element of another vector and the even element from
44881   // one of the same vectors being multiplied by the even element from the
44882   // other vector. So we need to make sure for each element i, this operator
44883   // is being performed:
44884   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
44885   SDValue ZExtIn, SExtIn;
44886   for (unsigned i = 0; i != NumElems; ++i) {
44887     SDValue N00Elt = N00.getOperand(i);
44888     SDValue N01Elt = N01.getOperand(i);
44889     SDValue N10Elt = N10.getOperand(i);
44890     SDValue N11Elt = N11.getOperand(i);
44891     // TODO: Be more tolerant to undefs.
44892     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44893         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44894         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
44895         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
44896       return SDValue();
44897     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
44898     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
44899     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
44900     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
44901     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
44902       return SDValue();
44903     unsigned IdxN00 = ConstN00Elt->getZExtValue();
44904     unsigned IdxN01 = ConstN01Elt->getZExtValue();
44905     unsigned IdxN10 = ConstN10Elt->getZExtValue();
44906     unsigned IdxN11 = ConstN11Elt->getZExtValue();
44907     // Add is commutative so indices can be reordered.
44908     if (IdxN00 > IdxN10) {
44909       std::swap(IdxN00, IdxN10);
44910       std::swap(IdxN01, IdxN11);
44911     }
44912     // N0 indices be the even element. N1 indices must be the next odd element.
44913     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
44914         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
44915       return SDValue();
44916     SDValue N00In = N00Elt.getOperand(0);
44917     SDValue N01In = N01Elt.getOperand(0);
44918     SDValue N10In = N10Elt.getOperand(0);
44919     SDValue N11In = N11Elt.getOperand(0);
44920     // First time we find an input capture it.
44921     if (!ZExtIn) {
44922       ZExtIn = N00In;
44923       SExtIn = N01In;
44924     }
44925     if (ZExtIn != N00In || SExtIn != N01In ||
44926         ZExtIn != N10In || SExtIn != N11In)
44927       return SDValue();
44928   }
44929 
44930   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44931                          ArrayRef<SDValue> Ops) {
44932     // Shrink by adding truncate nodes and let DAGCombine fold with the
44933     // sources.
44934     EVT InVT = Ops[0].getValueType();
44935     assert(InVT.getScalarType() == MVT::i8 &&
44936            "Unexpected scalar element type");
44937     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
44938     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
44939                                  InVT.getVectorNumElements() / 2);
44940     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
44941   };
44942   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
44943                           PMADDBuilder);
44944 }
44945 
combineTruncate(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)44946 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
44947                                const X86Subtarget &Subtarget) {
44948   EVT VT = N->getValueType(0);
44949   SDValue Src = N->getOperand(0);
44950   SDLoc DL(N);
44951 
44952   // Attempt to pre-truncate inputs to arithmetic ops instead.
44953   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
44954     return V;
44955 
44956   // Try to detect AVG pattern first.
44957   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
44958     return Avg;
44959 
44960   // Try to detect PMADD
44961   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
44962     return PMAdd;
44963 
44964   // Try to combine truncation with signed/unsigned saturation.
44965   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
44966     return Val;
44967 
44968   // Try to combine PMULHUW/PMULHW for vXi16.
44969   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
44970     return V;
44971 
44972   // The bitcast source is a direct mmx result.
44973   // Detect bitcasts between i32 to x86mmx
44974   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
44975     SDValue BCSrc = Src.getOperand(0);
44976     if (BCSrc.getValueType() == MVT::x86mmx)
44977       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
44978   }
44979 
44980   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
44981   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
44982     return V;
44983 
44984   return combineVectorTruncation(N, DAG, Subtarget);
44985 }
44986 
combineVTRUNC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)44987 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
44988                              TargetLowering::DAGCombinerInfo &DCI) {
44989   EVT VT = N->getValueType(0);
44990   SDValue In = N->getOperand(0);
44991   SDLoc DL(N);
44992 
44993   if (auto SSatVal = detectSSatPattern(In, VT))
44994     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
44995   if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
44996     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
44997 
44998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44999   APInt DemandedMask(APInt::getAllOnesValue(VT.getScalarSizeInBits()));
45000   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
45001     return SDValue(N, 0);
45002 
45003   return SDValue();
45004 }
45005 
45006 /// Returns the negated value if the node \p N flips sign of FP value.
45007 ///
45008 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
45009 /// or FSUB(0, x)
45010 /// AVX512F does not have FXOR, so FNEG is lowered as
45011 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
45012 /// In this case we go though all bitcasts.
45013 /// This also recognizes splat of a negated value and returns the splat of that
45014 /// value.
isFNEG(SelectionDAG & DAG,SDNode * N,unsigned Depth=0)45015 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
45016   if (N->getOpcode() == ISD::FNEG)
45017     return N->getOperand(0);
45018 
45019   // Don't recurse exponentially.
45020   if (Depth > SelectionDAG::MaxRecursionDepth)
45021     return SDValue();
45022 
45023   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
45024 
45025   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
45026   EVT VT = Op->getValueType(0);
45027 
45028   // Make sure the element size doesn't change.
45029   if (VT.getScalarSizeInBits() != ScalarSize)
45030     return SDValue();
45031 
45032   unsigned Opc = Op.getOpcode();
45033   switch (Opc) {
45034   case ISD::VECTOR_SHUFFLE: {
45035     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
45036     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
45037     if (!Op.getOperand(1).isUndef())
45038       return SDValue();
45039     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
45040       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
45041         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
45042                                     cast<ShuffleVectorSDNode>(Op)->getMask());
45043     break;
45044   }
45045   case ISD::INSERT_VECTOR_ELT: {
45046     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
45047     // -V, INDEX).
45048     SDValue InsVector = Op.getOperand(0);
45049     SDValue InsVal = Op.getOperand(1);
45050     if (!InsVector.isUndef())
45051       return SDValue();
45052     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
45053       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
45054         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
45055                            NegInsVal, Op.getOperand(2));
45056     break;
45057   }
45058   case ISD::FSUB:
45059   case ISD::XOR:
45060   case X86ISD::FXOR: {
45061     SDValue Op1 = Op.getOperand(1);
45062     SDValue Op0 = Op.getOperand(0);
45063 
45064     // For XOR and FXOR, we want to check if constant
45065     // bits of Op1 are sign bit masks. For FSUB, we
45066     // have to check if constant bits of Op0 are sign
45067     // bit masks and hence we swap the operands.
45068     if (Opc == ISD::FSUB)
45069       std::swap(Op0, Op1);
45070 
45071     APInt UndefElts;
45072     SmallVector<APInt, 16> EltBits;
45073     // Extract constant bits and see if they are all
45074     // sign bit masks. Ignore the undef elements.
45075     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
45076                                       /* AllowWholeUndefs */ true,
45077                                       /* AllowPartialUndefs */ false)) {
45078       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
45079         if (!UndefElts[I] && !EltBits[I].isSignMask())
45080           return SDValue();
45081 
45082       return peekThroughBitcasts(Op0);
45083     }
45084   }
45085   }
45086 
45087   return SDValue();
45088 }
45089 
negateFMAOpcode(unsigned Opcode,bool NegMul,bool NegAcc,bool NegRes)45090 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
45091                                 bool NegRes) {
45092   if (NegMul) {
45093     switch (Opcode) {
45094     default: llvm_unreachable("Unexpected opcode");
45095     case ISD::FMA:              Opcode = X86ISD::FNMADD;        break;
45096     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FNMADD; break;
45097     case X86ISD::FMADD_RND:     Opcode = X86ISD::FNMADD_RND;    break;
45098     case X86ISD::FMSUB:         Opcode = X86ISD::FNMSUB;        break;
45099     case X86ISD::STRICT_FMSUB:  Opcode = X86ISD::STRICT_FNMSUB; break;
45100     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FNMSUB_RND;    break;
45101     case X86ISD::FNMADD:        Opcode = ISD::FMA;              break;
45102     case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA;       break;
45103     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FMADD_RND;     break;
45104     case X86ISD::FNMSUB:        Opcode = X86ISD::FMSUB;         break;
45105     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB;  break;
45106     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FMSUB_RND;     break;
45107     }
45108   }
45109 
45110   if (NegAcc) {
45111     switch (Opcode) {
45112     default: llvm_unreachable("Unexpected opcode");
45113     case ISD::FMA:              Opcode = X86ISD::FMSUB;         break;
45114     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FMSUB;  break;
45115     case X86ISD::FMADD_RND:     Opcode = X86ISD::FMSUB_RND;     break;
45116     case X86ISD::FMSUB:         Opcode = ISD::FMA;              break;
45117     case X86ISD::STRICT_FMSUB:  Opcode = ISD::STRICT_FMA;       break;
45118     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FMADD_RND;     break;
45119     case X86ISD::FNMADD:        Opcode = X86ISD::FNMSUB;        break;
45120     case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
45121     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FNMSUB_RND;    break;
45122     case X86ISD::FNMSUB:        Opcode = X86ISD::FNMADD;        break;
45123     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
45124     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FNMADD_RND;    break;
45125     case X86ISD::FMADDSUB:      Opcode = X86ISD::FMSUBADD;      break;
45126     case X86ISD::FMADDSUB_RND:  Opcode = X86ISD::FMSUBADD_RND;  break;
45127     case X86ISD::FMSUBADD:      Opcode = X86ISD::FMADDSUB;      break;
45128     case X86ISD::FMSUBADD_RND:  Opcode = X86ISD::FMADDSUB_RND;  break;
45129     }
45130   }
45131 
45132   if (NegRes) {
45133     switch (Opcode) {
45134     // For accuracy reason, we never combine fneg and fma under strict FP.
45135     default: llvm_unreachable("Unexpected opcode");
45136     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
45137     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
45138     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
45139     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
45140     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
45141     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
45142     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
45143     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
45144     }
45145   }
45146 
45147   return Opcode;
45148 }
45149 
45150 /// Do target-specific dag combines on floating point negations.
combineFneg(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45151 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
45152                            TargetLowering::DAGCombinerInfo &DCI,
45153                            const X86Subtarget &Subtarget) {
45154   EVT OrigVT = N->getValueType(0);
45155   SDValue Arg = isFNEG(DAG, N);
45156   if (!Arg)
45157     return SDValue();
45158 
45159   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45160   EVT VT = Arg.getValueType();
45161   EVT SVT = VT.getScalarType();
45162   SDLoc DL(N);
45163 
45164   // Let legalize expand this if it isn't a legal type yet.
45165   if (!TLI.isTypeLegal(VT))
45166     return SDValue();
45167 
45168   // If we're negating a FMUL node on a target with FMA, then we can avoid the
45169   // use of a constant by performing (-0 - A*B) instead.
45170   // FIXME: Check rounding control flags as well once it becomes available.
45171   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
45172       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
45173     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
45174     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
45175                                   Arg.getOperand(1), Zero);
45176     return DAG.getBitcast(OrigVT, NewNode);
45177   }
45178 
45179   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
45180   bool LegalOperations = !DCI.isBeforeLegalizeOps();
45181   if (SDValue NegArg =
45182           TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
45183     return DAG.getBitcast(OrigVT, NegArg);
45184 
45185   return SDValue();
45186 }
45187 
getNegatedExpression(SDValue Op,SelectionDAG & DAG,bool LegalOperations,bool ForCodeSize,NegatibleCost & Cost,unsigned Depth) const45188 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
45189                                                 bool LegalOperations,
45190                                                 bool ForCodeSize,
45191                                                 NegatibleCost &Cost,
45192                                                 unsigned Depth) const {
45193   // fneg patterns are removable even if they have multiple uses.
45194   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
45195     Cost = NegatibleCost::Cheaper;
45196     return DAG.getBitcast(Op.getValueType(), Arg);
45197   }
45198 
45199   EVT VT = Op.getValueType();
45200   EVT SVT = VT.getScalarType();
45201   unsigned Opc = Op.getOpcode();
45202   switch (Opc) {
45203   case ISD::FMA:
45204   case X86ISD::FMSUB:
45205   case X86ISD::FNMADD:
45206   case X86ISD::FNMSUB:
45207   case X86ISD::FMADD_RND:
45208   case X86ISD::FMSUB_RND:
45209   case X86ISD::FNMADD_RND:
45210   case X86ISD::FNMSUB_RND: {
45211     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
45212         !(SVT == MVT::f32 || SVT == MVT::f64) ||
45213         !isOperationLegal(ISD::FMA, VT))
45214       break;
45215 
45216     // This is always negatible for free but we might be able to remove some
45217     // extra operand negations as well.
45218     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
45219     for (int i = 0; i != 3; ++i)
45220       NewOps[i] = getCheaperNegatedExpression(
45221           Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
45222 
45223     bool NegA = !!NewOps[0];
45224     bool NegB = !!NewOps[1];
45225     bool NegC = !!NewOps[2];
45226     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
45227 
45228     Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
45229                                   : NegatibleCost::Neutral;
45230 
45231     // Fill in the non-negated ops with the original values.
45232     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
45233       if (!NewOps[i])
45234         NewOps[i] = Op.getOperand(i);
45235     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
45236   }
45237   case X86ISD::FRCP:
45238     if (SDValue NegOp0 =
45239             getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
45240                                  ForCodeSize, Cost, Depth + 1))
45241       return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
45242     break;
45243   }
45244 
45245   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
45246                                               ForCodeSize, Cost, Depth);
45247 }
45248 
lowerX86FPLogicOp(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45249 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
45250                                  const X86Subtarget &Subtarget) {
45251   MVT VT = N->getSimpleValueType(0);
45252   // If we have integer vector types available, use the integer opcodes.
45253   if (!VT.isVector() || !Subtarget.hasSSE2())
45254     return SDValue();
45255 
45256   SDLoc dl(N);
45257 
45258   unsigned IntBits = VT.getScalarSizeInBits();
45259   MVT IntSVT = MVT::getIntegerVT(IntBits);
45260   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
45261 
45262   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
45263   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
45264   unsigned IntOpcode;
45265   switch (N->getOpcode()) {
45266   default: llvm_unreachable("Unexpected FP logic op");
45267   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
45268   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
45269   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
45270   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
45271   }
45272   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
45273   return DAG.getBitcast(VT, IntOp);
45274 }
45275 
45276 
45277 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
foldXor1SetCC(SDNode * N,SelectionDAG & DAG)45278 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
45279   if (N->getOpcode() != ISD::XOR)
45280     return SDValue();
45281 
45282   SDValue LHS = N->getOperand(0);
45283   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
45284     return SDValue();
45285 
45286   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
45287       X86::CondCode(LHS->getConstantOperandVal(0)));
45288   SDLoc DL(N);
45289   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
45290 }
45291 
combineXor(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45292 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
45293                           TargetLowering::DAGCombinerInfo &DCI,
45294                           const X86Subtarget &Subtarget) {
45295   // If this is SSE1 only convert to FXOR to avoid scalarization.
45296   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() &&
45297       N->getValueType(0) == MVT::v4i32) {
45298     return DAG.getBitcast(
45299         MVT::v4i32, DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
45300                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
45301                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
45302   }
45303 
45304   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
45305     return Cmp;
45306 
45307   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
45308     return R;
45309 
45310   if (DCI.isBeforeLegalizeOps())
45311     return SDValue();
45312 
45313   if (SDValue SetCC = foldXor1SetCC(N, DAG))
45314     return SetCC;
45315 
45316   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
45317     return RV;
45318 
45319   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
45320     return FPLogic;
45321 
45322   return combineFneg(N, DAG, DCI, Subtarget);
45323 }
45324 
combineBEXTR(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45325 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
45326                             TargetLowering::DAGCombinerInfo &DCI,
45327                             const X86Subtarget &Subtarget) {
45328   EVT VT = N->getValueType(0);
45329   unsigned NumBits = VT.getSizeInBits();
45330 
45331   // TODO - Constant Folding.
45332 
45333   // Simplify the inputs.
45334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45335   APInt DemandedMask(APInt::getAllOnesValue(NumBits));
45336   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
45337     return SDValue(N, 0);
45338 
45339   return SDValue();
45340 }
45341 
isNullFPScalarOrVectorConst(SDValue V)45342 static bool isNullFPScalarOrVectorConst(SDValue V) {
45343   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
45344 }
45345 
45346 /// If a value is a scalar FP zero or a vector FP zero (potentially including
45347 /// undefined elements), return a zero constant that may be used to fold away
45348 /// that value. In the case of a vector, the returned constant will not contain
45349 /// undefined elements even if the input parameter does. This makes it suitable
45350 /// to be used as a replacement operand with operations (eg, bitwise-and) where
45351 /// an undef should not propagate.
getNullFPConstForNullVal(SDValue V,SelectionDAG & DAG,const X86Subtarget & Subtarget)45352 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
45353                                         const X86Subtarget &Subtarget) {
45354   if (!isNullFPScalarOrVectorConst(V))
45355     return SDValue();
45356 
45357   if (V.getValueType().isVector())
45358     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
45359 
45360   return V;
45361 }
45362 
combineFAndFNotToFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45363 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
45364                                       const X86Subtarget &Subtarget) {
45365   SDValue N0 = N->getOperand(0);
45366   SDValue N1 = N->getOperand(1);
45367   EVT VT = N->getValueType(0);
45368   SDLoc DL(N);
45369 
45370   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
45371   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
45372         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
45373         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
45374     return SDValue();
45375 
45376   auto isAllOnesConstantFP = [](SDValue V) {
45377     if (V.getSimpleValueType().isVector())
45378       return ISD::isBuildVectorAllOnes(V.getNode());
45379     auto *C = dyn_cast<ConstantFPSDNode>(V);
45380     return C && C->getConstantFPValue()->isAllOnesValue();
45381   };
45382 
45383   // fand (fxor X, -1), Y --> fandn X, Y
45384   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
45385     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
45386 
45387   // fand X, (fxor Y, -1) --> fandn Y, X
45388   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
45389     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
45390 
45391   return SDValue();
45392 }
45393 
45394 /// Do target-specific dag combines on X86ISD::FAND nodes.
combineFAnd(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45395 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
45396                            const X86Subtarget &Subtarget) {
45397   // FAND(0.0, x) -> 0.0
45398   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
45399     return V;
45400 
45401   // FAND(x, 0.0) -> 0.0
45402   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
45403     return V;
45404 
45405   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
45406     return V;
45407 
45408   return lowerX86FPLogicOp(N, DAG, Subtarget);
45409 }
45410 
45411 /// Do target-specific dag combines on X86ISD::FANDN nodes.
combineFAndn(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45412 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
45413                             const X86Subtarget &Subtarget) {
45414   // FANDN(0.0, x) -> x
45415   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
45416     return N->getOperand(1);
45417 
45418   // FANDN(x, 0.0) -> 0.0
45419   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
45420     return V;
45421 
45422   return lowerX86FPLogicOp(N, DAG, Subtarget);
45423 }
45424 
45425 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
combineFOr(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45426 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
45427                           TargetLowering::DAGCombinerInfo &DCI,
45428                           const X86Subtarget &Subtarget) {
45429   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
45430 
45431   // F[X]OR(0.0, x) -> x
45432   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
45433     return N->getOperand(1);
45434 
45435   // F[X]OR(x, 0.0) -> x
45436   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
45437     return N->getOperand(0);
45438 
45439   if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
45440     return NewVal;
45441 
45442   return lowerX86FPLogicOp(N, DAG, Subtarget);
45443 }
45444 
45445 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
combineFMinFMax(SDNode * N,SelectionDAG & DAG)45446 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
45447   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
45448 
45449   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
45450   if (!DAG.getTarget().Options.NoNaNsFPMath ||
45451       !DAG.getTarget().Options.NoSignedZerosFPMath)
45452     return SDValue();
45453 
45454   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
45455   // into FMINC and FMAXC, which are Commutative operations.
45456   unsigned NewOp = 0;
45457   switch (N->getOpcode()) {
45458     default: llvm_unreachable("unknown opcode");
45459     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
45460     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
45461   }
45462 
45463   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
45464                      N->getOperand(0), N->getOperand(1));
45465 }
45466 
combineFMinNumFMaxNum(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45467 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
45468                                      const X86Subtarget &Subtarget) {
45469   if (Subtarget.useSoftFloat())
45470     return SDValue();
45471 
45472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45473 
45474   EVT VT = N->getValueType(0);
45475   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
45476         (Subtarget.hasSSE2() && VT == MVT::f64) ||
45477         (VT.isVector() && TLI.isTypeLegal(VT))))
45478     return SDValue();
45479 
45480   SDValue Op0 = N->getOperand(0);
45481   SDValue Op1 = N->getOperand(1);
45482   SDLoc DL(N);
45483   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
45484 
45485   // If we don't have to respect NaN inputs, this is a direct translation to x86
45486   // min/max instructions.
45487   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
45488     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
45489 
45490   // If one of the operands is known non-NaN use the native min/max instructions
45491   // with the non-NaN input as second operand.
45492   if (DAG.isKnownNeverNaN(Op1))
45493     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
45494   if (DAG.isKnownNeverNaN(Op0))
45495     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
45496 
45497   // If we have to respect NaN inputs, this takes at least 3 instructions.
45498   // Favor a library call when operating on a scalar and minimizing code size.
45499   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
45500     return SDValue();
45501 
45502   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
45503                                          VT);
45504 
45505   // There are 4 possibilities involving NaN inputs, and these are the required
45506   // outputs:
45507   //                   Op1
45508   //               Num     NaN
45509   //            ----------------
45510   //       Num  |  Max  |  Op0 |
45511   // Op0        ----------------
45512   //       NaN  |  Op1  |  NaN |
45513   //            ----------------
45514   //
45515   // The SSE FP max/min instructions were not designed for this case, but rather
45516   // to implement:
45517   //   Min = Op1 < Op0 ? Op1 : Op0
45518   //   Max = Op1 > Op0 ? Op1 : Op0
45519   //
45520   // So they always return Op0 if either input is a NaN. However, we can still
45521   // use those instructions for fmaxnum by selecting away a NaN input.
45522 
45523   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
45524   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
45525   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
45526 
45527   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
45528   // are NaN, the NaN value of Op1 is the result.
45529   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
45530 }
45531 
combineX86INT_TO_FP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)45532 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
45533                                    TargetLowering::DAGCombinerInfo &DCI) {
45534   EVT VT = N->getValueType(0);
45535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45536 
45537   APInt KnownUndef, KnownZero;
45538   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
45539   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
45540                                      KnownZero, DCI))
45541     return SDValue(N, 0);
45542 
45543   // Convert a full vector load into vzload when not all bits are needed.
45544   SDValue In = N->getOperand(0);
45545   MVT InVT = In.getSimpleValueType();
45546   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
45547       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
45548     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
45549     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
45550     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
45551     MVT MemVT = MVT::getIntegerVT(NumBits);
45552     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
45553     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
45554       SDLoc dl(N);
45555       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
45556                                     DAG.getBitcast(InVT, VZLoad));
45557       DCI.CombineTo(N, Convert);
45558       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
45559       DCI.recursivelyDeleteUnusedNodes(LN);
45560       return SDValue(N, 0);
45561     }
45562   }
45563 
45564   return SDValue();
45565 }
45566 
combineCVTP2I_CVTTP2I(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)45567 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
45568                                      TargetLowering::DAGCombinerInfo &DCI) {
45569   bool IsStrict = N->isTargetStrictFPOpcode();
45570   EVT VT = N->getValueType(0);
45571 
45572   // Convert a full vector load into vzload when not all bits are needed.
45573   SDValue In = N->getOperand(IsStrict ? 1 : 0);
45574   MVT InVT = In.getSimpleValueType();
45575   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
45576       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
45577     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
45578     LoadSDNode *LN = cast<LoadSDNode>(In);
45579     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
45580     MVT MemVT = MVT::getFloatingPointVT(NumBits);
45581     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
45582     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
45583       SDLoc dl(N);
45584       if (IsStrict) {
45585         SDValue Convert =
45586             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
45587                         {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
45588         DCI.CombineTo(N, Convert, Convert.getValue(1));
45589       } else {
45590         SDValue Convert =
45591             DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
45592         DCI.CombineTo(N, Convert);
45593       }
45594       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
45595       DCI.recursivelyDeleteUnusedNodes(LN);
45596       return SDValue(N, 0);
45597     }
45598   }
45599 
45600   return SDValue();
45601 }
45602 
45603 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
combineAndnp(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45604 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
45605                             TargetLowering::DAGCombinerInfo &DCI,
45606                             const X86Subtarget &Subtarget) {
45607   MVT VT = N->getSimpleValueType(0);
45608 
45609   // ANDNP(0, x) -> x
45610   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
45611     return N->getOperand(1);
45612 
45613   // ANDNP(x, 0) -> 0
45614   if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
45615     return DAG.getConstant(0, SDLoc(N), VT);
45616 
45617   // Turn ANDNP back to AND if input is inverted.
45618   if (SDValue Not = IsNOT(N->getOperand(0), DAG))
45619     return DAG.getNode(ISD::AND, SDLoc(N), VT, DAG.getBitcast(VT, Not),
45620                        N->getOperand(1));
45621 
45622   // Attempt to recursively combine a bitmask ANDNP with shuffles.
45623   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
45624     SDValue Op(N, 0);
45625     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
45626       return Res;
45627   }
45628 
45629   return SDValue();
45630 }
45631 
combineBT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)45632 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
45633                          TargetLowering::DAGCombinerInfo &DCI) {
45634   SDValue N1 = N->getOperand(1);
45635 
45636   // BT ignores high bits in the bit index operand.
45637   unsigned BitWidth = N1.getValueSizeInBits();
45638   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
45639   if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
45640     if (N->getOpcode() != ISD::DELETED_NODE)
45641       DCI.AddToWorklist(N);
45642     return SDValue(N, 0);
45643   }
45644 
45645   return SDValue();
45646 }
45647 
combineCVTPH2PS(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)45648 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
45649                                TargetLowering::DAGCombinerInfo &DCI) {
45650   bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
45651   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
45652 
45653   if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
45654     APInt KnownUndef, KnownZero;
45655     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45656     APInt DemandedElts = APInt::getLowBitsSet(8, 4);
45657     if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
45658                                        DCI)) {
45659       if (N->getOpcode() != ISD::DELETED_NODE)
45660         DCI.AddToWorklist(N);
45661       return SDValue(N, 0);
45662     }
45663 
45664     // Convert a full vector load into vzload when not all bits are needed.
45665     if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
45666       LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
45667       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
45668         SDLoc dl(N);
45669         if (IsStrict) {
45670           SDValue Convert = DAG.getNode(
45671               N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
45672               {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
45673           DCI.CombineTo(N, Convert, Convert.getValue(1));
45674         } else {
45675           SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
45676                                         DAG.getBitcast(MVT::v8i16, VZLoad));
45677           DCI.CombineTo(N, Convert);
45678         }
45679 
45680         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
45681         DCI.recursivelyDeleteUnusedNodes(LN);
45682         return SDValue(N, 0);
45683       }
45684     }
45685   }
45686 
45687   return SDValue();
45688 }
45689 
45690 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
combineSextInRegCmov(SDNode * N,SelectionDAG & DAG)45691 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
45692   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
45693 
45694   EVT DstVT = N->getValueType(0);
45695 
45696   SDValue N0 = N->getOperand(0);
45697   SDValue N1 = N->getOperand(1);
45698   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
45699 
45700   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
45701     return SDValue();
45702 
45703   // Look through single use any_extends / truncs.
45704   SDValue IntermediateBitwidthOp;
45705   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
45706       N0.hasOneUse()) {
45707     IntermediateBitwidthOp = N0;
45708     N0 = N0.getOperand(0);
45709   }
45710 
45711   // See if we have a single use cmov.
45712   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
45713     return SDValue();
45714 
45715   SDValue CMovOp0 = N0.getOperand(0);
45716   SDValue CMovOp1 = N0.getOperand(1);
45717 
45718   // Make sure both operands are constants.
45719   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
45720       !isa<ConstantSDNode>(CMovOp1.getNode()))
45721     return SDValue();
45722 
45723   SDLoc DL(N);
45724 
45725   // If we looked through an any_extend/trunc above, add one to the constants.
45726   if (IntermediateBitwidthOp) {
45727     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
45728     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
45729     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
45730   }
45731 
45732   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
45733   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
45734 
45735   EVT CMovVT = DstVT;
45736   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
45737   if (DstVT == MVT::i16) {
45738     CMovVT = MVT::i32;
45739     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
45740     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
45741   }
45742 
45743   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
45744                              N0.getOperand(2), N0.getOperand(3));
45745 
45746   if (CMovVT != DstVT)
45747     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
45748 
45749   return CMov;
45750 }
45751 
combineSignExtendInReg(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)45752 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
45753                                       const X86Subtarget &Subtarget) {
45754   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
45755 
45756   if (SDValue V = combineSextInRegCmov(N, DAG))
45757     return V;
45758 
45759   EVT VT = N->getValueType(0);
45760   SDValue N0 = N->getOperand(0);
45761   SDValue N1 = N->getOperand(1);
45762   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
45763   SDLoc dl(N);
45764 
45765   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
45766   // both SSE and AVX2 since there is no sign-extended shift right
45767   // operation on a vector with 64-bit elements.
45768   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
45769   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
45770   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
45771                            N0.getOpcode() == ISD::SIGN_EXTEND)) {
45772     SDValue N00 = N0.getOperand(0);
45773 
45774     // EXTLOAD has a better solution on AVX2,
45775     // it may be replaced with X86ISD::VSEXT node.
45776     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
45777       if (!ISD::isNormalLoad(N00.getNode()))
45778         return SDValue();
45779 
45780     // Attempt to promote any comparison mask ops before moving the
45781     // SIGN_EXTEND_INREG in the way.
45782     if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
45783       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
45784 
45785     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
45786       SDValue Tmp =
45787           DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
45788       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
45789     }
45790   }
45791   return SDValue();
45792 }
45793 
45794 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
45795 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
45796 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
45797 /// opportunities to combine math ops, use an LEA, or use a complex addressing
45798 /// mode. This can eliminate extend, add, and shift instructions.
promoteExtBeforeAdd(SDNode * Ext,SelectionDAG & DAG,const X86Subtarget & Subtarget)45799 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
45800                                    const X86Subtarget &Subtarget) {
45801   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
45802       Ext->getOpcode() != ISD::ZERO_EXTEND)
45803     return SDValue();
45804 
45805   // TODO: This should be valid for other integer types.
45806   EVT VT = Ext->getValueType(0);
45807   if (VT != MVT::i64)
45808     return SDValue();
45809 
45810   SDValue Add = Ext->getOperand(0);
45811   if (Add.getOpcode() != ISD::ADD)
45812     return SDValue();
45813 
45814   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
45815   bool NSW = Add->getFlags().hasNoSignedWrap();
45816   bool NUW = Add->getFlags().hasNoUnsignedWrap();
45817 
45818   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
45819   // into the 'zext'
45820   if ((Sext && !NSW) || (!Sext && !NUW))
45821     return SDValue();
45822 
45823   // Having a constant operand to the 'add' ensures that we are not increasing
45824   // the instruction count because the constant is extended for free below.
45825   // A constant operand can also become the displacement field of an LEA.
45826   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
45827   if (!AddOp1)
45828     return SDValue();
45829 
45830   // Don't make the 'add' bigger if there's no hope of combining it with some
45831   // other 'add' or 'shl' instruction.
45832   // TODO: It may be profitable to generate simpler LEA instructions in place
45833   // of single 'add' instructions, but the cost model for selecting an LEA
45834   // currently has a high threshold.
45835   bool HasLEAPotential = false;
45836   for (auto *User : Ext->uses()) {
45837     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
45838       HasLEAPotential = true;
45839       break;
45840     }
45841   }
45842   if (!HasLEAPotential)
45843     return SDValue();
45844 
45845   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
45846   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
45847   SDValue AddOp0 = Add.getOperand(0);
45848   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
45849   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
45850 
45851   // The wider add is guaranteed to not wrap because both operands are
45852   // sign-extended.
45853   SDNodeFlags Flags;
45854   Flags.setNoSignedWrap(NSW);
45855   Flags.setNoUnsignedWrap(NUW);
45856   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
45857 }
45858 
45859 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
45860 // operands and the result of CMOV is not used anywhere else - promote CMOV
45861 // itself instead of promoting its result. This could be beneficial, because:
45862 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
45863 //        (or more) pseudo-CMOVs only when they go one-after-another and
45864 //        getting rid of result extension code after CMOV will help that.
45865 //     2) Promotion of constant CMOV arguments is free, hence the
45866 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
45867 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
45868 //        promotion is also good in terms of code-size.
45869 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
45870 //         promotion).
combineToExtendCMOV(SDNode * Extend,SelectionDAG & DAG)45871 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
45872   SDValue CMovN = Extend->getOperand(0);
45873   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
45874     return SDValue();
45875 
45876   EVT TargetVT = Extend->getValueType(0);
45877   unsigned ExtendOpcode = Extend->getOpcode();
45878   SDLoc DL(Extend);
45879 
45880   EVT VT = CMovN.getValueType();
45881   SDValue CMovOp0 = CMovN.getOperand(0);
45882   SDValue CMovOp1 = CMovN.getOperand(1);
45883 
45884   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
45885       !isa<ConstantSDNode>(CMovOp1.getNode()))
45886     return SDValue();
45887 
45888   // Only extend to i32 or i64.
45889   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
45890     return SDValue();
45891 
45892   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
45893   // are free.
45894   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
45895     return SDValue();
45896 
45897   // If this a zero extend to i64, we should only extend to i32 and use a free
45898   // zero extend to finish.
45899   EVT ExtendVT = TargetVT;
45900   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
45901     ExtendVT = MVT::i32;
45902 
45903   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
45904   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
45905 
45906   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
45907                             CMovN.getOperand(2), CMovN.getOperand(3));
45908 
45909   // Finish extending if needed.
45910   if (ExtendVT != TargetVT)
45911     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
45912 
45913   return Res;
45914 }
45915 
45916 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
45917 // This is more or less the reverse of combineBitcastvxi1.
45918 static SDValue
combineToExtendBoolVectorInReg(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)45919 combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
45920                                TargetLowering::DAGCombinerInfo &DCI,
45921                                const X86Subtarget &Subtarget) {
45922   unsigned Opcode = N->getOpcode();
45923   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
45924       Opcode != ISD::ANY_EXTEND)
45925     return SDValue();
45926   if (!DCI.isBeforeLegalizeOps())
45927     return SDValue();
45928   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
45929     return SDValue();
45930 
45931   SDValue N0 = N->getOperand(0);
45932   EVT VT = N->getValueType(0);
45933   EVT SVT = VT.getScalarType();
45934   EVT InSVT = N0.getValueType().getScalarType();
45935   unsigned EltSizeInBits = SVT.getSizeInBits();
45936 
45937   // Input type must be extending a bool vector (bit-casted from a scalar
45938   // integer) to legal integer types.
45939   if (!VT.isVector())
45940     return SDValue();
45941   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
45942     return SDValue();
45943   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
45944     return SDValue();
45945 
45946   SDValue N00 = N0.getOperand(0);
45947   EVT SclVT = N0.getOperand(0).getValueType();
45948   if (!SclVT.isScalarInteger())
45949     return SDValue();
45950 
45951   SDLoc DL(N);
45952   SDValue Vec;
45953   SmallVector<int, 32> ShuffleMask;
45954   unsigned NumElts = VT.getVectorNumElements();
45955   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
45956 
45957   // Broadcast the scalar integer to the vector elements.
45958   if (NumElts > EltSizeInBits) {
45959     // If the scalar integer is greater than the vector element size, then we
45960     // must split it down into sub-sections for broadcasting. For example:
45961     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
45962     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
45963     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
45964     unsigned Scale = NumElts / EltSizeInBits;
45965     EVT BroadcastVT =
45966         EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
45967     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
45968     Vec = DAG.getBitcast(VT, Vec);
45969 
45970     for (unsigned i = 0; i != Scale; ++i)
45971       ShuffleMask.append(EltSizeInBits, i);
45972     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
45973   } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
45974              (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
45975     // If we have register broadcast instructions, use the scalar size as the
45976     // element type for the shuffle. Then cast to the wider element type. The
45977     // widened bits won't be used, and this might allow the use of a broadcast
45978     // load.
45979     assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
45980     unsigned Scale = EltSizeInBits / NumElts;
45981     EVT BroadcastVT =
45982         EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
45983     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
45984     ShuffleMask.append(NumElts * Scale, 0);
45985     Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
45986     Vec = DAG.getBitcast(VT, Vec);
45987   } else {
45988     // For smaller scalar integers, we can simply any-extend it to the vector
45989     // element size (we don't care about the upper bits) and broadcast it to all
45990     // elements.
45991     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
45992     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
45993     ShuffleMask.append(NumElts, 0);
45994     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
45995   }
45996 
45997   // Now, mask the relevant bit in each element.
45998   SmallVector<SDValue, 32> Bits;
45999   for (unsigned i = 0; i != NumElts; ++i) {
46000     int BitIdx = (i % EltSizeInBits);
46001     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
46002     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
46003   }
46004   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
46005   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
46006 
46007   // Compare against the bitmask and extend the result.
46008   EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
46009   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
46010   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
46011 
46012   // For SEXT, this is now done, otherwise shift the result down for
46013   // zero-extension.
46014   if (Opcode == ISD::SIGN_EXTEND)
46015     return Vec;
46016   return DAG.getNode(ISD::SRL, DL, VT, Vec,
46017                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
46018 }
46019 
46020 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
46021 // result type.
combineExtSetcc(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46022 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
46023                                const X86Subtarget &Subtarget) {
46024   SDValue N0 = N->getOperand(0);
46025   EVT VT = N->getValueType(0);
46026   SDLoc dl(N);
46027 
46028   // Only do this combine with AVX512 for vector extends.
46029   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
46030     return SDValue();
46031 
46032   // Only combine legal element types.
46033   EVT SVT = VT.getVectorElementType();
46034   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
46035       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
46036     return SDValue();
46037 
46038   // We can only do this if the vector size in 256 bits or less.
46039   unsigned Size = VT.getSizeInBits();
46040   if (Size > 256 && Subtarget.useAVX512Regs())
46041     return SDValue();
46042 
46043   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
46044   // that's the only integer compares with we have.
46045   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
46046   if (ISD::isUnsignedIntSetCC(CC))
46047     return SDValue();
46048 
46049   // Only do this combine if the extension will be fully consumed by the setcc.
46050   EVT N00VT = N0.getOperand(0).getValueType();
46051   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
46052   if (Size != MatchingVecType.getSizeInBits())
46053     return SDValue();
46054 
46055   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
46056 
46057   if (N->getOpcode() == ISD::ZERO_EXTEND)
46058     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
46059 
46060   return Res;
46061 }
46062 
combineSext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46063 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
46064                            TargetLowering::DAGCombinerInfo &DCI,
46065                            const X86Subtarget &Subtarget) {
46066   SDValue N0 = N->getOperand(0);
46067   EVT VT = N->getValueType(0);
46068   EVT InVT = N0.getValueType();
46069   SDLoc DL(N);
46070 
46071   // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
46072   if (!DCI.isBeforeLegalizeOps() &&
46073       N0.getOpcode() == X86ISD::SETCC_CARRY) {
46074     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
46075                                  N0->getOperand(1));
46076     bool ReplaceOtherUses = !N0.hasOneUse();
46077     DCI.CombineTo(N, Setcc);
46078     // Replace other uses with a truncate of the widened setcc_carry.
46079     if (ReplaceOtherUses) {
46080       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
46081                                   N0.getValueType(), Setcc);
46082       DCI.CombineTo(N0.getNode(), Trunc);
46083     }
46084 
46085     return SDValue(N, 0);
46086   }
46087 
46088   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
46089     return NewCMov;
46090 
46091   if (!DCI.isBeforeLegalizeOps())
46092     return SDValue();
46093 
46094   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
46095     return V;
46096 
46097   if (InVT == MVT::i1 && N0.getOpcode() == ISD::XOR &&
46098       isAllOnesConstant(N0.getOperand(1)) && N0.hasOneUse()) {
46099     // Invert and sign-extend a boolean is the same as zero-extend and subtract
46100     // 1 because 0 becomes -1 and 1 becomes 0. The subtract is efficiently
46101     // lowered with an LEA or a DEC. This is the same as: select Bool, 0, -1.
46102     // sext (xor Bool, -1) --> sub (zext Bool), 1
46103     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
46104     return DAG.getNode(ISD::SUB, DL, VT, Zext, DAG.getConstant(1, DL, VT));
46105   }
46106 
46107   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
46108     return V;
46109 
46110   if (VT.isVector())
46111     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
46112       return R;
46113 
46114   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
46115     return NewAdd;
46116 
46117   return SDValue();
46118 }
46119 
combineFMA(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46120 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
46121                           TargetLowering::DAGCombinerInfo &DCI,
46122                           const X86Subtarget &Subtarget) {
46123   SDLoc dl(N);
46124   EVT VT = N->getValueType(0);
46125   bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
46126 
46127   // Let legalize expand this if it isn't a legal type yet.
46128   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46129   if (!TLI.isTypeLegal(VT))
46130     return SDValue();
46131 
46132   EVT ScalarVT = VT.getScalarType();
46133   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
46134     return SDValue();
46135 
46136   SDValue A = N->getOperand(IsStrict ? 1 : 0);
46137   SDValue B = N->getOperand(IsStrict ? 2 : 1);
46138   SDValue C = N->getOperand(IsStrict ? 3 : 2);
46139 
46140   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
46141     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
46142     bool LegalOperations = !DCI.isBeforeLegalizeOps();
46143     if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
46144                                                        CodeSize)) {
46145       V = NegV;
46146       return true;
46147     }
46148     // Look through extract_vector_elts. If it comes from an FNEG, create a
46149     // new extract from the FNEG input.
46150     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
46151         isNullConstant(V.getOperand(1))) {
46152       SDValue Vec = V.getOperand(0);
46153       if (SDValue NegV = TLI.getCheaperNegatedExpression(
46154               Vec, DAG, LegalOperations, CodeSize)) {
46155         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
46156                         NegV, V.getOperand(1));
46157         return true;
46158       }
46159     }
46160 
46161     return false;
46162   };
46163 
46164   // Do not convert the passthru input of scalar intrinsics.
46165   // FIXME: We could allow negations of the lower element only.
46166   bool NegA = invertIfNegative(A);
46167   bool NegB = invertIfNegative(B);
46168   bool NegC = invertIfNegative(C);
46169 
46170   if (!NegA && !NegB && !NegC)
46171     return SDValue();
46172 
46173   unsigned NewOpcode =
46174       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
46175 
46176   if (IsStrict) {
46177     assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
46178     return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
46179                        {N->getOperand(0), A, B, C});
46180   } else {
46181     if (N->getNumOperands() == 4)
46182       return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
46183     return DAG.getNode(NewOpcode, dl, VT, A, B, C);
46184   }
46185 }
46186 
46187 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
46188 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
combineFMADDSUB(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)46189 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
46190                                TargetLowering::DAGCombinerInfo &DCI) {
46191   SDLoc dl(N);
46192   EVT VT = N->getValueType(0);
46193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46194   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
46195   bool LegalOperations = !DCI.isBeforeLegalizeOps();
46196 
46197   SDValue N2 = N->getOperand(2);
46198 
46199   SDValue NegN2 =
46200       TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
46201   if (!NegN2)
46202     return SDValue();
46203   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
46204 
46205   if (N->getNumOperands() == 4)
46206     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
46207                        NegN2, N->getOperand(3));
46208   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
46209                      NegN2);
46210 }
46211 
combineZext(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46212 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
46213                            TargetLowering::DAGCombinerInfo &DCI,
46214                            const X86Subtarget &Subtarget) {
46215   SDLoc dl(N);
46216   SDValue N0 = N->getOperand(0);
46217   EVT VT = N->getValueType(0);
46218 
46219   // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
46220   // FIXME: Is this needed? We don't seem to have any tests for it.
46221   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
46222       N0.getOpcode() == X86ISD::SETCC_CARRY) {
46223     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
46224                                  N0->getOperand(1));
46225     bool ReplaceOtherUses = !N0.hasOneUse();
46226     DCI.CombineTo(N, Setcc);
46227     // Replace other uses with a truncate of the widened setcc_carry.
46228     if (ReplaceOtherUses) {
46229       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
46230                                   N0.getValueType(), Setcc);
46231       DCI.CombineTo(N0.getNode(), Trunc);
46232     }
46233 
46234     return SDValue(N, 0);
46235   }
46236 
46237   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
46238     return NewCMov;
46239 
46240   if (DCI.isBeforeLegalizeOps())
46241     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
46242       return V;
46243 
46244   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
46245     return V;
46246 
46247   if (VT.isVector())
46248     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
46249       return R;
46250 
46251   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
46252     return NewAdd;
46253 
46254   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
46255     return R;
46256 
46257   // TODO: Combine with any target/faux shuffle.
46258   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
46259       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
46260     SDValue N00 = N0.getOperand(0);
46261     SDValue N01 = N0.getOperand(1);
46262     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
46263     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
46264     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
46265         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
46266       return concatSubVectors(N00, N01, DAG, dl);
46267     }
46268   }
46269 
46270   return SDValue();
46271 }
46272 
46273 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
46274 /// recognizable memcmp expansion.
isOrXorXorTree(SDValue X,bool Root=true)46275 static bool isOrXorXorTree(SDValue X, bool Root = true) {
46276   if (X.getOpcode() == ISD::OR)
46277     return isOrXorXorTree(X.getOperand(0), false) &&
46278            isOrXorXorTree(X.getOperand(1), false);
46279   if (Root)
46280     return false;
46281   return X.getOpcode() == ISD::XOR;
46282 }
46283 
46284 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
46285 /// expansion.
46286 template<typename F>
emitOrXorXorTree(SDValue X,SDLoc & DL,SelectionDAG & DAG,EVT VecVT,EVT CmpVT,bool HasPT,F SToV)46287 static SDValue emitOrXorXorTree(SDValue X, SDLoc &DL, SelectionDAG &DAG,
46288                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
46289   SDValue Op0 = X.getOperand(0);
46290   SDValue Op1 = X.getOperand(1);
46291   if (X.getOpcode() == ISD::OR) {
46292     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
46293     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
46294     if (VecVT != CmpVT)
46295       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
46296     if (HasPT)
46297       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
46298     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
46299   } else if (X.getOpcode() == ISD::XOR) {
46300     SDValue A = SToV(Op0);
46301     SDValue B = SToV(Op1);
46302     if (VecVT != CmpVT)
46303       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
46304     if (HasPT)
46305       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
46306     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
46307   }
46308   llvm_unreachable("Impossible");
46309 }
46310 
46311 /// Try to map a 128-bit or larger integer comparison to vector instructions
46312 /// before type legalization splits it up into chunks.
combineVectorSizedSetCCEquality(SDNode * SetCC,SelectionDAG & DAG,const X86Subtarget & Subtarget)46313 static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
46314                                                const X86Subtarget &Subtarget) {
46315   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
46316   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
46317 
46318   // We're looking for an oversized integer equality comparison.
46319   SDValue X = SetCC->getOperand(0);
46320   SDValue Y = SetCC->getOperand(1);
46321   EVT OpVT = X.getValueType();
46322   unsigned OpSize = OpVT.getSizeInBits();
46323   if (!OpVT.isScalarInteger() || OpSize < 128)
46324     return SDValue();
46325 
46326   // Ignore a comparison with zero because that gets special treatment in
46327   // EmitTest(). But make an exception for the special case of a pair of
46328   // logically-combined vector-sized operands compared to zero. This pattern may
46329   // be generated by the memcmp expansion pass with oversized integer compares
46330   // (see PR33325).
46331   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
46332   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
46333     return SDValue();
46334 
46335   // Don't perform this combine if constructing the vector will be expensive.
46336   auto IsVectorBitCastCheap = [](SDValue X) {
46337     X = peekThroughBitcasts(X);
46338     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
46339            X.getOpcode() == ISD::LOAD;
46340   };
46341   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
46342       !IsOrXorXorTreeCCZero)
46343     return SDValue();
46344 
46345   EVT VT = SetCC->getValueType(0);
46346   SDLoc DL(SetCC);
46347 
46348   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
46349   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
46350   // Otherwise use PCMPEQ (plus AND) and mask testing.
46351   if ((OpSize == 128 && Subtarget.hasSSE2()) ||
46352       (OpSize == 256 && Subtarget.hasAVX()) ||
46353       (OpSize == 512 && Subtarget.useAVX512Regs())) {
46354     bool HasPT = Subtarget.hasSSE41();
46355 
46356     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
46357     // vector registers are essentially free. (Technically, widening registers
46358     // prevents load folding, but the tradeoff is worth it.)
46359     bool PreferKOT = Subtarget.preferMaskRegisters();
46360     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
46361 
46362     EVT VecVT = MVT::v16i8;
46363     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
46364     if (OpSize == 256) {
46365       VecVT = MVT::v32i8;
46366       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
46367     }
46368     EVT CastVT = VecVT;
46369     bool NeedsAVX512FCast = false;
46370     if (OpSize == 512 || NeedZExt) {
46371       if (Subtarget.hasBWI()) {
46372         VecVT = MVT::v64i8;
46373         CmpVT = MVT::v64i1;
46374         if (OpSize == 512)
46375           CastVT = VecVT;
46376       } else {
46377         VecVT = MVT::v16i32;
46378         CmpVT = MVT::v16i1;
46379         CastVT = OpSize == 512 ? VecVT :
46380                  OpSize == 256 ? MVT::v8i32 : MVT::v4i32;
46381         NeedsAVX512FCast = true;
46382       }
46383     }
46384 
46385     auto ScalarToVector = [&](SDValue X) -> SDValue {
46386       bool TmpZext = false;
46387       EVT TmpCastVT = CastVT;
46388       if (X.getOpcode() == ISD::ZERO_EXTEND) {
46389         SDValue OrigX = X.getOperand(0);
46390         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
46391         if (OrigSize < OpSize) {
46392           if (OrigSize == 128) {
46393             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
46394             X = OrigX;
46395             TmpZext = true;
46396           } else if (OrigSize == 256) {
46397             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
46398             X = OrigX;
46399             TmpZext = true;
46400           }
46401         }
46402       }
46403       X = DAG.getBitcast(TmpCastVT, X);
46404       if (!NeedZExt && !TmpZext)
46405         return X;
46406       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
46407                          DAG.getConstant(0, DL, VecVT), X,
46408                          DAG.getVectorIdxConstant(0, DL));
46409     };
46410 
46411     SDValue Cmp;
46412     if (IsOrXorXorTreeCCZero) {
46413       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
46414       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
46415       // Use 2 vector equality compares and 'and' the results before doing a
46416       // MOVMSK.
46417       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
46418     } else {
46419       SDValue VecX = ScalarToVector(X);
46420       SDValue VecY = ScalarToVector(Y);
46421       if (VecVT != CmpVT) {
46422         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
46423       } else if (HasPT) {
46424         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
46425       } else {
46426         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
46427       }
46428     }
46429     // AVX512 should emit a setcc that will lower to kortest.
46430     if (VecVT != CmpVT) {
46431       EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64 :
46432                    CmpVT == MVT::v32i1 ? MVT::i32 : MVT::i16;
46433       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
46434                           DAG.getConstant(0, DL, KRegVT), CC);
46435     }
46436     if (HasPT) {
46437       SDValue BCCmp = DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64,
46438                                      Cmp);
46439       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
46440       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
46441       SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
46442       return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
46443     }
46444     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
46445     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
46446     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
46447     assert(Cmp.getValueType() == MVT::v16i8 &&
46448            "Non 128-bit vector on pre-SSE41 target");
46449     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
46450     SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
46451     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
46452   }
46453 
46454   return SDValue();
46455 }
46456 
combineSetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46457 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
46458                             const X86Subtarget &Subtarget) {
46459   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
46460   const SDValue LHS = N->getOperand(0);
46461   const SDValue RHS = N->getOperand(1);
46462   EVT VT = N->getValueType(0);
46463   EVT OpVT = LHS.getValueType();
46464   SDLoc DL(N);
46465 
46466   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
46467     if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
46468       return V;
46469 
46470     if (VT == MVT::i1 && isNullConstant(RHS)) {
46471       SDValue X86CC;
46472       if (SDValue V =
46473               MatchVectorAllZeroTest(LHS, CC, DL, Subtarget, DAG, X86CC))
46474         return DAG.getNode(ISD::TRUNCATE, DL, VT,
46475                            DAG.getNode(X86ISD::SETCC, DL, MVT::i8, X86CC, V));
46476     }
46477   }
46478 
46479   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
46480       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
46481     // Using temporaries to avoid messing up operand ordering for later
46482     // transformations if this doesn't work.
46483     SDValue Op0 = LHS;
46484     SDValue Op1 = RHS;
46485     ISD::CondCode TmpCC = CC;
46486     // Put build_vector on the right.
46487     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
46488       std::swap(Op0, Op1);
46489       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
46490     }
46491 
46492     bool IsSEXT0 =
46493         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
46494         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
46495     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
46496 
46497     if (IsSEXT0 && IsVZero1) {
46498       assert(VT == Op0.getOperand(0).getValueType() &&
46499              "Unexpected operand type");
46500       if (TmpCC == ISD::SETGT)
46501         return DAG.getConstant(0, DL, VT);
46502       if (TmpCC == ISD::SETLE)
46503         return DAG.getConstant(1, DL, VT);
46504       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
46505         return DAG.getNOT(DL, Op0.getOperand(0), VT);
46506 
46507       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
46508              "Unexpected condition code!");
46509       return Op0.getOperand(0);
46510     }
46511   }
46512 
46513   // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
46514   // pre-promote its result type since vXi1 vectors don't get promoted
46515   // during type legalization.
46516   // NOTE: The element count check is to ignore operand types that need to
46517   // go through type promotion to a 128-bit vector.
46518   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
46519       VT.getVectorElementType() == MVT::i1 &&
46520       (OpVT.getVectorElementType() == MVT::i8 ||
46521        OpVT.getVectorElementType() == MVT::i16)) {
46522     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
46523     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
46524   }
46525 
46526   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
46527   // to avoid scalarization via legalization because v4i32 is not a legal type.
46528   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
46529       LHS.getValueType() == MVT::v4f32)
46530     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
46531 
46532   return SDValue();
46533 }
46534 
combineMOVMSK(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46535 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
46536                              TargetLowering::DAGCombinerInfo &DCI,
46537                              const X86Subtarget &Subtarget) {
46538   SDValue Src = N->getOperand(0);
46539   MVT SrcVT = Src.getSimpleValueType();
46540   MVT VT = N->getSimpleValueType(0);
46541   unsigned NumBits = VT.getScalarSizeInBits();
46542   unsigned NumElts = SrcVT.getVectorNumElements();
46543 
46544   // Perform constant folding.
46545   if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
46546     assert(VT == MVT::i32 && "Unexpected result type");
46547     APInt Imm(32, 0);
46548     for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
46549       if (!Src.getOperand(Idx).isUndef() &&
46550           Src.getConstantOperandAPInt(Idx).isNegative())
46551         Imm.setBit(Idx);
46552     }
46553     return DAG.getConstant(Imm, SDLoc(N), VT);
46554   }
46555 
46556   // Look through int->fp bitcasts that don't change the element width.
46557   unsigned EltWidth = SrcVT.getScalarSizeInBits();
46558   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
46559       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
46560     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
46561 
46562   // Fold movmsk(not(x)) -> not(movmsk) to improve folding of movmsk results
46563   // with scalar comparisons.
46564   if (SDValue NotSrc = IsNOT(Src, DAG)) {
46565     SDLoc DL(N);
46566     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
46567     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
46568     return DAG.getNode(ISD::XOR, DL, VT,
46569                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
46570                        DAG.getConstant(NotMask, DL, VT));
46571   }
46572 
46573   // Simplify the inputs.
46574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46575   APInt DemandedMask(APInt::getAllOnesValue(NumBits));
46576   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
46577     return SDValue(N, 0);
46578 
46579   return SDValue();
46580 }
46581 
combineX86GatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)46582 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
46583                                        TargetLowering::DAGCombinerInfo &DCI) {
46584   // With vector masks we only demand the upper bit of the mask.
46585   SDValue Mask = cast<X86MaskedGatherScatterSDNode>(N)->getMask();
46586   if (Mask.getScalarValueSizeInBits() != 1) {
46587     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46588     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
46589     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
46590       if (N->getOpcode() != ISD::DELETED_NODE)
46591         DCI.AddToWorklist(N);
46592       return SDValue(N, 0);
46593     }
46594   }
46595 
46596   return SDValue();
46597 }
46598 
rebuildGatherScatter(MaskedGatherScatterSDNode * GorS,SDValue Index,SDValue Base,SDValue Scale,SelectionDAG & DAG)46599 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
46600                                     SDValue Index, SDValue Base, SDValue Scale,
46601                                     SelectionDAG &DAG) {
46602   SDLoc DL(GorS);
46603 
46604   if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
46605     SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
46606                       Gather->getMask(), Base, Index, Scale } ;
46607     return DAG.getMaskedGather(Gather->getVTList(),
46608                                Gather->getMemoryVT(), DL, Ops,
46609                                Gather->getMemOperand(),
46610                                Gather->getIndexType());
46611   }
46612   auto *Scatter = cast<MaskedScatterSDNode>(GorS);
46613   SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
46614                     Scatter->getMask(), Base, Index, Scale };
46615   return DAG.getMaskedScatter(Scatter->getVTList(),
46616                               Scatter->getMemoryVT(), DL,
46617                               Ops, Scatter->getMemOperand(),
46618                               Scatter->getIndexType());
46619 }
46620 
combineGatherScatter(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)46621 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
46622                                     TargetLowering::DAGCombinerInfo &DCI) {
46623   SDLoc DL(N);
46624   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
46625   SDValue Index = GorS->getIndex();
46626   SDValue Base = GorS->getBasePtr();
46627   SDValue Scale = GorS->getScale();
46628 
46629   if (DCI.isBeforeLegalize()) {
46630     unsigned IndexWidth = Index.getScalarValueSizeInBits();
46631 
46632     // Shrink constant indices if they are larger than 32-bits.
46633     // Only do this before legalize types since v2i64 could become v2i32.
46634     // FIXME: We could check that the type is legal if we're after legalize
46635     // types, but then we would need to construct test cases where that happens.
46636     // FIXME: We could support more than just constant vectors, but we need to
46637     // careful with costing. A truncate that can be optimized out would be fine.
46638     // Otherwise we might only want to create a truncate if it avoids a split.
46639     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
46640       if (BV->isConstant() && IndexWidth > 32 &&
46641           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
46642         unsigned NumElts = Index.getValueType().getVectorNumElements();
46643         EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
46644         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
46645         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
46646       }
46647     }
46648 
46649     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
46650     // there are sufficient sign bits. Only do this before legalize types to
46651     // avoid creating illegal types in truncate.
46652     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
46653          Index.getOpcode() == ISD::ZERO_EXTEND) &&
46654         IndexWidth > 32 &&
46655         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
46656         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
46657       unsigned NumElts = Index.getValueType().getVectorNumElements();
46658       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
46659       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
46660       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
46661     }
46662   }
46663 
46664   if (DCI.isBeforeLegalizeOps()) {
46665     unsigned IndexWidth = Index.getScalarValueSizeInBits();
46666 
46667     // Make sure the index is either i32 or i64
46668     if (IndexWidth != 32 && IndexWidth != 64) {
46669       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
46670       EVT IndexVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
46671                                    Index.getValueType().getVectorNumElements());
46672       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
46673       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
46674     }
46675   }
46676 
46677   // With vector masks we only demand the upper bit of the mask.
46678   SDValue Mask = GorS->getMask();
46679   if (Mask.getScalarValueSizeInBits() != 1) {
46680     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46681     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
46682     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
46683       if (N->getOpcode() != ISD::DELETED_NODE)
46684         DCI.AddToWorklist(N);
46685       return SDValue(N, 0);
46686     }
46687   }
46688 
46689   return SDValue();
46690 }
46691 
46692 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
combineX86SetCC(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46693 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
46694                                const X86Subtarget &Subtarget) {
46695   SDLoc DL(N);
46696   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
46697   SDValue EFLAGS = N->getOperand(1);
46698 
46699   // Try to simplify the EFLAGS and condition code operands.
46700   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
46701     return getSETCC(CC, Flags, DL, DAG);
46702 
46703   return SDValue();
46704 }
46705 
46706 /// Optimize branch condition evaluation.
combineBrCond(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46707 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
46708                              const X86Subtarget &Subtarget) {
46709   SDLoc DL(N);
46710   SDValue EFLAGS = N->getOperand(3);
46711   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
46712 
46713   // Try to simplify the EFLAGS and condition code operands.
46714   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
46715   // RAUW them under us.
46716   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
46717     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
46718     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
46719                        N->getOperand(1), Cond, Flags);
46720   }
46721 
46722   return SDValue();
46723 }
46724 
46725 // TODO: Could we move this to DAGCombine?
combineVectorCompareAndMaskUnaryOp(SDNode * N,SelectionDAG & DAG)46726 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
46727                                                   SelectionDAG &DAG) {
46728   // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
46729   // to optimize away operation when it's from a constant.
46730   //
46731   // The general transformation is:
46732   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
46733   //       AND(VECTOR_CMP(x,y), constant2)
46734   //    constant2 = UNARYOP(constant)
46735 
46736   // Early exit if this isn't a vector operation, the operand of the
46737   // unary operation isn't a bitwise AND, or if the sizes of the operations
46738   // aren't the same.
46739   EVT VT = N->getValueType(0);
46740   bool IsStrict = N->isStrictFPOpcode();
46741   unsigned NumEltBits = VT.getScalarSizeInBits();
46742   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
46743   if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
46744       DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
46745       VT.getSizeInBits() != Op0.getValueSizeInBits())
46746     return SDValue();
46747 
46748   // Now check that the other operand of the AND is a constant. We could
46749   // make the transformation for non-constant splats as well, but it's unclear
46750   // that would be a benefit as it would not eliminate any operations, just
46751   // perform one more step in scalar code before moving to the vector unit.
46752   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
46753     // Bail out if the vector isn't a constant.
46754     if (!BV->isConstant())
46755       return SDValue();
46756 
46757     // Everything checks out. Build up the new and improved node.
46758     SDLoc DL(N);
46759     EVT IntVT = BV->getValueType(0);
46760     // Create a new constant of the appropriate type for the transformed
46761     // DAG.
46762     SDValue SourceConst;
46763     if (IsStrict)
46764       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
46765                                 {N->getOperand(0), SDValue(BV, 0)});
46766     else
46767       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
46768     // The AND node needs bitcasts to/from an integer vector type around it.
46769     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
46770     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
46771                                  MaskConst);
46772     SDValue Res = DAG.getBitcast(VT, NewAnd);
46773     if (IsStrict)
46774       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
46775     return Res;
46776   }
46777 
46778   return SDValue();
46779 }
46780 
46781 /// If we are converting a value to floating-point, try to replace scalar
46782 /// truncate of an extracted vector element with a bitcast. This tries to keep
46783 /// the sequence on XMM registers rather than moving between vector and GPRs.
combineToFPTruncExtElt(SDNode * N,SelectionDAG & DAG)46784 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
46785   // TODO: This is currently only used by combineSIntToFP, but it is generalized
46786   //       to allow being called by any similar cast opcode.
46787   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
46788   SDValue Trunc = N->getOperand(0);
46789   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
46790     return SDValue();
46791 
46792   SDValue ExtElt = Trunc.getOperand(0);
46793   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
46794       !isNullConstant(ExtElt.getOperand(1)))
46795     return SDValue();
46796 
46797   EVT TruncVT = Trunc.getValueType();
46798   EVT SrcVT = ExtElt.getValueType();
46799   unsigned DestWidth = TruncVT.getSizeInBits();
46800   unsigned SrcWidth = SrcVT.getSizeInBits();
46801   if (SrcWidth % DestWidth != 0)
46802     return SDValue();
46803 
46804   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
46805   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
46806   unsigned VecWidth = SrcVecVT.getSizeInBits();
46807   unsigned NumElts = VecWidth / DestWidth;
46808   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
46809   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
46810   SDLoc DL(N);
46811   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
46812                                   BitcastVec, ExtElt.getOperand(1));
46813   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
46814 }
46815 
combineUIntToFP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)46816 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
46817                                const X86Subtarget &Subtarget) {
46818   bool IsStrict = N->isStrictFPOpcode();
46819   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
46820   EVT VT = N->getValueType(0);
46821   EVT InVT = Op0.getValueType();
46822 
46823   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
46824   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
46825   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
46826   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
46827     SDLoc dl(N);
46828     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
46829                                  InVT.getVectorNumElements());
46830     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
46831 
46832     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
46833     if (IsStrict)
46834       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
46835                          {N->getOperand(0), P});
46836     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
46837   }
46838 
46839   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
46840   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
46841   // the optimization here.
46842   if (DAG.SignBitIsZero(Op0)) {
46843     if (IsStrict)
46844       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
46845                          {N->getOperand(0), Op0});
46846     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
46847   }
46848 
46849   return SDValue();
46850 }
46851 
combineSIntToFP(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)46852 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
46853                                TargetLowering::DAGCombinerInfo &DCI,
46854                                const X86Subtarget &Subtarget) {
46855   // First try to optimize away the conversion entirely when it's
46856   // conditionally from a constant. Vectors only.
46857   bool IsStrict = N->isStrictFPOpcode();
46858   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
46859     return Res;
46860 
46861   // Now move on to more general possibilities.
46862   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
46863   EVT VT = N->getValueType(0);
46864   EVT InVT = Op0.getValueType();
46865 
46866   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
46867   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
46868   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
46869   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
46870     SDLoc dl(N);
46871     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
46872                                  InVT.getVectorNumElements());
46873     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
46874     if (IsStrict)
46875       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
46876                          {N->getOperand(0), P});
46877     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
46878   }
46879 
46880   // Without AVX512DQ we only support i64 to float scalar conversion. For both
46881   // vectors and scalars, see if we know that the upper bits are all the sign
46882   // bit, in which case we can truncate the input to i32 and convert from that.
46883   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
46884     unsigned BitWidth = InVT.getScalarSizeInBits();
46885     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
46886     if (NumSignBits >= (BitWidth - 31)) {
46887       EVT TruncVT = MVT::i32;
46888       if (InVT.isVector())
46889         TruncVT = EVT::getVectorVT(*DAG.getContext(), TruncVT,
46890                                    InVT.getVectorNumElements());
46891       SDLoc dl(N);
46892       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
46893         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
46894         if (IsStrict)
46895           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
46896                              {N->getOperand(0), Trunc});
46897         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
46898       }
46899       // If we're after legalize and the type is v2i32 we need to shuffle and
46900       // use CVTSI2P.
46901       assert(InVT == MVT::v2i64 && "Unexpected VT!");
46902       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
46903       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
46904                                           { 0, 2, -1, -1 });
46905       if (IsStrict)
46906         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
46907                            {N->getOperand(0), Shuf});
46908       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
46909     }
46910   }
46911 
46912   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
46913   // a 32-bit target where SSE doesn't support i64->FP operations.
46914   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
46915       Op0.getOpcode() == ISD::LOAD) {
46916     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
46917 
46918     // This transformation is not supported if the result type is f16 or f128.
46919     if (VT == MVT::f16 || VT == MVT::f128)
46920       return SDValue();
46921 
46922     // If we have AVX512DQ we can use packed conversion instructions unless
46923     // the VT is f80.
46924     if (Subtarget.hasDQI() && VT != MVT::f80)
46925       return SDValue();
46926 
46927     if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
46928         Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
46929       std::pair<SDValue, SDValue> Tmp =
46930           Subtarget.getTargetLowering()->BuildFILD(
46931               VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
46932               Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
46933       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
46934       return Tmp.first;
46935     }
46936   }
46937 
46938   if (IsStrict)
46939     return SDValue();
46940 
46941   if (SDValue V = combineToFPTruncExtElt(N, DAG))
46942     return V;
46943 
46944   return SDValue();
46945 }
46946 
needCarryOrOverflowFlag(SDValue Flags)46947 static bool needCarryOrOverflowFlag(SDValue Flags) {
46948   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
46949 
46950   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
46951          UI != UE; ++UI) {
46952     SDNode *User = *UI;
46953 
46954     X86::CondCode CC;
46955     switch (User->getOpcode()) {
46956     default:
46957       // Be conservative.
46958       return true;
46959     case X86ISD::SETCC:
46960     case X86ISD::SETCC_CARRY:
46961       CC = (X86::CondCode)User->getConstantOperandVal(0);
46962       break;
46963     case X86ISD::BRCOND:
46964       CC = (X86::CondCode)User->getConstantOperandVal(2);
46965       break;
46966     case X86ISD::CMOV:
46967       CC = (X86::CondCode)User->getConstantOperandVal(2);
46968       break;
46969     }
46970 
46971     switch (CC) {
46972     default: break;
46973     case X86::COND_A: case X86::COND_AE:
46974     case X86::COND_B: case X86::COND_BE:
46975     case X86::COND_O: case X86::COND_NO:
46976     case X86::COND_G: case X86::COND_GE:
46977     case X86::COND_L: case X86::COND_LE:
46978       return true;
46979     }
46980   }
46981 
46982   return false;
46983 }
46984 
onlyZeroFlagUsed(SDValue Flags)46985 static bool onlyZeroFlagUsed(SDValue Flags) {
46986   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
46987 
46988   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
46989          UI != UE; ++UI) {
46990     SDNode *User = *UI;
46991 
46992     unsigned CCOpNo;
46993     switch (User->getOpcode()) {
46994     default:
46995       // Be conservative.
46996       return false;
46997     case X86ISD::SETCC:       CCOpNo = 0; break;
46998     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
46999     case X86ISD::BRCOND:      CCOpNo = 2; break;
47000     case X86ISD::CMOV:        CCOpNo = 2; break;
47001     }
47002 
47003     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
47004     if (CC != X86::COND_E && CC != X86::COND_NE)
47005       return false;
47006   }
47007 
47008   return true;
47009 }
47010 
combineCMP(SDNode * N,SelectionDAG & DAG)47011 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
47012   // Only handle test patterns.
47013   if (!isNullConstant(N->getOperand(1)))
47014     return SDValue();
47015 
47016   // If we have a CMP of a truncated binop, see if we can make a smaller binop
47017   // and use its flags directly.
47018   // TODO: Maybe we should try promoting compares that only use the zero flag
47019   // first if we can prove the upper bits with computeKnownBits?
47020   SDLoc dl(N);
47021   SDValue Op = N->getOperand(0);
47022   EVT VT = Op.getValueType();
47023 
47024   // If we have a constant logical shift that's only used in a comparison
47025   // against zero turn it into an equivalent AND. This allows turning it into
47026   // a TEST instruction later.
47027   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
47028       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
47029       onlyZeroFlagUsed(SDValue(N, 0))) {
47030     unsigned BitWidth = VT.getSizeInBits();
47031     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
47032     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
47033       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
47034       APInt Mask = Op.getOpcode() == ISD::SRL
47035                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
47036                        : APInt::getLowBitsSet(BitWidth, MaskBits);
47037       if (Mask.isSignedIntN(32)) {
47038         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
47039                          DAG.getConstant(Mask, dl, VT));
47040         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
47041                            DAG.getConstant(0, dl, VT));
47042       }
47043     }
47044   }
47045 
47046   // Look for a truncate with a single use.
47047   if (Op.getOpcode() != ISD::TRUNCATE || !Op.hasOneUse())
47048     return SDValue();
47049 
47050   Op = Op.getOperand(0);
47051 
47052   // Arithmetic op can only have one use.
47053   if (!Op.hasOneUse())
47054     return SDValue();
47055 
47056   unsigned NewOpc;
47057   switch (Op.getOpcode()) {
47058   default: return SDValue();
47059   case ISD::AND:
47060     // Skip and with constant. We have special handling for and with immediate
47061     // during isel to generate test instructions.
47062     if (isa<ConstantSDNode>(Op.getOperand(1)))
47063       return SDValue();
47064     NewOpc = X86ISD::AND;
47065     break;
47066   case ISD::OR:  NewOpc = X86ISD::OR;  break;
47067   case ISD::XOR: NewOpc = X86ISD::XOR; break;
47068   case ISD::ADD:
47069     // If the carry or overflow flag is used, we can't truncate.
47070     if (needCarryOrOverflowFlag(SDValue(N, 0)))
47071       return SDValue();
47072     NewOpc = X86ISD::ADD;
47073     break;
47074   case ISD::SUB:
47075     // If the carry or overflow flag is used, we can't truncate.
47076     if (needCarryOrOverflowFlag(SDValue(N, 0)))
47077       return SDValue();
47078     NewOpc = X86ISD::SUB;
47079     break;
47080   }
47081 
47082   // We found an op we can narrow. Truncate its inputs.
47083   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
47084   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
47085 
47086   // Use a X86 specific opcode to avoid DAG combine messing with it.
47087   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
47088   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
47089 
47090   // For AND, keep a CMP so that we can match the test pattern.
47091   if (NewOpc == X86ISD::AND)
47092     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
47093                        DAG.getConstant(0, dl, VT));
47094 
47095   // Return the flags.
47096   return Op.getValue(1);
47097 }
47098 
combineX86AddSub(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)47099 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
47100                                 TargetLowering::DAGCombinerInfo &DCI) {
47101   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
47102          "Expected X86ISD::ADD or X86ISD::SUB");
47103 
47104   SDLoc DL(N);
47105   SDValue LHS = N->getOperand(0);
47106   SDValue RHS = N->getOperand(1);
47107   MVT VT = LHS.getSimpleValueType();
47108   unsigned GenericOpc = X86ISD::ADD == N->getOpcode() ? ISD::ADD : ISD::SUB;
47109 
47110   // If we don't use the flag result, simplify back to a generic ADD/SUB.
47111   if (!N->hasAnyUseOfValue(1)) {
47112     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
47113     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
47114   }
47115 
47116   // Fold any similar generic ADD/SUB opcodes to reuse this node.
47117   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
47118     SDValue Ops[] = {N0, N1};
47119     SDVTList VTs = DAG.getVTList(N->getValueType(0));
47120     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
47121       SDValue Op(N, 0);
47122       if (Negate)
47123         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
47124       DCI.CombineTo(GenericAddSub, Op);
47125     }
47126   };
47127   MatchGeneric(LHS, RHS, false);
47128   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
47129 
47130   return SDValue();
47131 }
47132 
combineSBB(SDNode * N,SelectionDAG & DAG)47133 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
47134   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
47135     MVT VT = N->getSimpleValueType(0);
47136     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
47137     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
47138                        N->getOperand(0), N->getOperand(1),
47139                        Flags);
47140   }
47141 
47142   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
47143   // iff the flag result is dead.
47144   SDValue Op0 = N->getOperand(0);
47145   SDValue Op1 = N->getOperand(1);
47146   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op1) &&
47147       !N->hasAnyUseOfValue(1))
47148     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), Op0.getOperand(0),
47149                        Op0.getOperand(1), N->getOperand(2));
47150 
47151   return SDValue();
47152 }
47153 
47154 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
combineADC(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)47155 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
47156                           TargetLowering::DAGCombinerInfo &DCI) {
47157   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
47158   // the result is either zero or one (depending on the input carry bit).
47159   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
47160   if (X86::isZeroNode(N->getOperand(0)) &&
47161       X86::isZeroNode(N->getOperand(1)) &&
47162       // We don't have a good way to replace an EFLAGS use, so only do this when
47163       // dead right now.
47164       SDValue(N, 1).use_empty()) {
47165     SDLoc DL(N);
47166     EVT VT = N->getValueType(0);
47167     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
47168     SDValue Res1 =
47169         DAG.getNode(ISD::AND, DL, VT,
47170                     DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
47171                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
47172                                 N->getOperand(2)),
47173                     DAG.getConstant(1, DL, VT));
47174     return DCI.CombineTo(N, Res1, CarryOut);
47175   }
47176 
47177   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
47178     MVT VT = N->getSimpleValueType(0);
47179     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
47180     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
47181                        N->getOperand(0), N->getOperand(1),
47182                        Flags);
47183   }
47184 
47185   return SDValue();
47186 }
47187 
47188 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
47189 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
47190 /// with CMP+{ADC, SBB}.
combineAddOrSubToADCOrSBB(SDNode * N,SelectionDAG & DAG)47191 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
47192   bool IsSub = N->getOpcode() == ISD::SUB;
47193   SDValue X = N->getOperand(0);
47194   SDValue Y = N->getOperand(1);
47195 
47196   // If this is an add, canonicalize a zext operand to the RHS.
47197   // TODO: Incomplete? What if both sides are zexts?
47198   if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
47199       Y.getOpcode() != ISD::ZERO_EXTEND)
47200     std::swap(X, Y);
47201 
47202   // Look through a one-use zext.
47203   bool PeekedThroughZext = false;
47204   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
47205     Y = Y.getOperand(0);
47206     PeekedThroughZext = true;
47207   }
47208 
47209   // If this is an add, canonicalize a setcc operand to the RHS.
47210   // TODO: Incomplete? What if both sides are setcc?
47211   // TODO: Should we allow peeking through a zext of the other operand?
47212   if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
47213       Y.getOpcode() != X86ISD::SETCC)
47214     std::swap(X, Y);
47215 
47216   if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
47217     return SDValue();
47218 
47219   SDLoc DL(N);
47220   EVT VT = N->getValueType(0);
47221   X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
47222 
47223   // If X is -1 or 0, then we have an opportunity to avoid constants required in
47224   // the general case below.
47225   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
47226   if (ConstantX) {
47227     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnesValue()) ||
47228         (IsSub && CC == X86::COND_B && ConstantX->isNullValue())) {
47229       // This is a complicated way to get -1 or 0 from the carry flag:
47230       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
47231       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
47232       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
47233                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
47234                          Y.getOperand(1));
47235     }
47236 
47237     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnesValue()) ||
47238         (IsSub && CC == X86::COND_A && ConstantX->isNullValue())) {
47239       SDValue EFLAGS = Y->getOperand(1);
47240       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
47241           EFLAGS.getValueType().isInteger() &&
47242           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
47243         // Swap the operands of a SUB, and we have the same pattern as above.
47244         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
47245         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
47246         SDValue NewSub = DAG.getNode(
47247             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
47248             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
47249         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
47250         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
47251                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
47252                            NewEFLAGS);
47253       }
47254     }
47255   }
47256 
47257   if (CC == X86::COND_B) {
47258     // X + SETB Z --> adc X, 0
47259     // X - SETB Z --> sbb X, 0
47260     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
47261                        DAG.getVTList(VT, MVT::i32), X,
47262                        DAG.getConstant(0, DL, VT), Y.getOperand(1));
47263   }
47264 
47265   if (CC == X86::COND_A) {
47266     SDValue EFLAGS = Y.getOperand(1);
47267     // Try to convert COND_A into COND_B in an attempt to facilitate
47268     // materializing "setb reg".
47269     //
47270     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
47271     // cannot take an immediate as its first operand.
47272     //
47273     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
47274         EFLAGS.getValueType().isInteger() &&
47275         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
47276       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
47277                                    EFLAGS.getNode()->getVTList(),
47278                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
47279       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
47280       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
47281                          DAG.getVTList(VT, MVT::i32), X,
47282                          DAG.getConstant(0, DL, VT), NewEFLAGS);
47283     }
47284   }
47285 
47286   if (CC == X86::COND_AE) {
47287     // X + SETAE --> sbb X, -1
47288     // X - SETAE --> adc X, -1
47289     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
47290                        DAG.getVTList(VT, MVT::i32), X,
47291                        DAG.getConstant(-1, DL, VT), Y.getOperand(1));
47292   }
47293 
47294   if (CC == X86::COND_BE) {
47295     // X + SETBE --> sbb X, -1
47296     // X - SETBE --> adc X, -1
47297     SDValue EFLAGS = Y.getOperand(1);
47298     // Try to convert COND_BE into COND_AE in an attempt to facilitate
47299     // materializing "setae reg".
47300     //
47301     // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
47302     // cannot take an immediate as its first operand.
47303     //
47304     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
47305         EFLAGS.getValueType().isInteger() &&
47306         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
47307       SDValue NewSub = DAG.getNode(
47308           X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
47309           EFLAGS.getOperand(1), EFLAGS.getOperand(0));
47310       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
47311       return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
47312                          DAG.getVTList(VT, MVT::i32), X,
47313                          DAG.getConstant(-1, DL, VT), NewEFLAGS);
47314     }
47315   }
47316 
47317   if (CC != X86::COND_E && CC != X86::COND_NE)
47318     return SDValue();
47319 
47320   SDValue Cmp = Y.getOperand(1);
47321   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
47322       !X86::isZeroNode(Cmp.getOperand(1)) ||
47323       !Cmp.getOperand(0).getValueType().isInteger())
47324     return SDValue();
47325 
47326   SDValue Z = Cmp.getOperand(0);
47327   EVT ZVT = Z.getValueType();
47328 
47329   // If X is -1 or 0, then we have an opportunity to avoid constants required in
47330   // the general case below.
47331   if (ConstantX) {
47332     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
47333     // fake operands:
47334     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
47335     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
47336     if ((IsSub && CC == X86::COND_NE && ConstantX->isNullValue()) ||
47337         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnesValue())) {
47338       SDValue Zero = DAG.getConstant(0, DL, ZVT);
47339       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
47340       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
47341       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
47342                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
47343                          SDValue(Neg.getNode(), 1));
47344     }
47345 
47346     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
47347     // with fake operands:
47348     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
47349     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
47350     if ((IsSub && CC == X86::COND_E && ConstantX->isNullValue()) ||
47351         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnesValue())) {
47352       SDValue One = DAG.getConstant(1, DL, ZVT);
47353       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
47354       SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
47355       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
47356                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
47357                          Cmp1.getValue(1));
47358     }
47359   }
47360 
47361   // (cmp Z, 1) sets the carry flag if Z is 0.
47362   SDValue One = DAG.getConstant(1, DL, ZVT);
47363   SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
47364   SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
47365 
47366   // Add the flags type for ADC/SBB nodes.
47367   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
47368 
47369   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
47370   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
47371   if (CC == X86::COND_NE)
47372     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
47373                        DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
47374 
47375   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
47376   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
47377   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
47378                      DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
47379 }
47380 
matchPMADDWD(SelectionDAG & DAG,SDValue Op0,SDValue Op1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)47381 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
47382                             const SDLoc &DL, EVT VT,
47383                             const X86Subtarget &Subtarget) {
47384   // Example of pattern we try to detect:
47385   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
47386   //(add (build_vector (extract_elt t, 0),
47387   //                   (extract_elt t, 2),
47388   //                   (extract_elt t, 4),
47389   //                   (extract_elt t, 6)),
47390   //     (build_vector (extract_elt t, 1),
47391   //                   (extract_elt t, 3),
47392   //                   (extract_elt t, 5),
47393   //                   (extract_elt t, 7)))
47394 
47395   if (!Subtarget.hasSSE2())
47396     return SDValue();
47397 
47398   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
47399       Op1.getOpcode() != ISD::BUILD_VECTOR)
47400     return SDValue();
47401 
47402   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
47403       VT.getVectorNumElements() < 4 ||
47404       !isPowerOf2_32(VT.getVectorNumElements()))
47405     return SDValue();
47406 
47407   // Check if one of Op0,Op1 is of the form:
47408   // (build_vector (extract_elt Mul, 0),
47409   //               (extract_elt Mul, 2),
47410   //               (extract_elt Mul, 4),
47411   //                   ...
47412   // the other is of the form:
47413   // (build_vector (extract_elt Mul, 1),
47414   //               (extract_elt Mul, 3),
47415   //               (extract_elt Mul, 5),
47416   //                   ...
47417   // and identify Mul.
47418   SDValue Mul;
47419   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
47420     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
47421             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
47422     // TODO: Be more tolerant to undefs.
47423     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47424         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47425         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47426         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
47427       return SDValue();
47428     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
47429     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
47430     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
47431     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
47432     if (!Const0L || !Const1L || !Const0H || !Const1H)
47433       return SDValue();
47434     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
47435              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
47436     // Commutativity of mul allows factors of a product to reorder.
47437     if (Idx0L > Idx1L)
47438       std::swap(Idx0L, Idx1L);
47439     if (Idx0H > Idx1H)
47440       std::swap(Idx0H, Idx1H);
47441     // Commutativity of add allows pairs of factors to reorder.
47442     if (Idx0L > Idx0H) {
47443       std::swap(Idx0L, Idx0H);
47444       std::swap(Idx1L, Idx1H);
47445     }
47446     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
47447         Idx1H != 2 * i + 3)
47448       return SDValue();
47449     if (!Mul) {
47450       // First time an extract_elt's source vector is visited. Must be a MUL
47451       // with 2X number of vector elements than the BUILD_VECTOR.
47452       // Both extracts must be from same MUL.
47453       Mul = Op0L->getOperand(0);
47454       if (Mul->getOpcode() != ISD::MUL ||
47455           Mul.getValueType().getVectorNumElements() != 2 * e)
47456         return SDValue();
47457     }
47458     // Check that the extract is from the same MUL previously seen.
47459     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
47460         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
47461       return SDValue();
47462   }
47463 
47464   // Check if the Mul source can be safely shrunk.
47465   ShrinkMode Mode;
47466   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
47467       Mode == ShrinkMode::MULU16)
47468     return SDValue();
47469 
47470   EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
47471                                  VT.getVectorNumElements() * 2);
47472   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
47473   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
47474 
47475   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
47476                          ArrayRef<SDValue> Ops) {
47477     EVT InVT = Ops[0].getValueType();
47478     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
47479     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
47480                                  InVT.getVectorNumElements() / 2);
47481     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
47482   };
47483   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
47484 }
47485 
47486 // Attempt to turn this pattern into PMADDWD.
47487 // (add (mul (sext (build_vector)), (sext (build_vector))),
47488 //      (mul (sext (build_vector)), (sext (build_vector)))
matchPMADDWD_2(SelectionDAG & DAG,SDValue N0,SDValue N1,const SDLoc & DL,EVT VT,const X86Subtarget & Subtarget)47489 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
47490                               const SDLoc &DL, EVT VT,
47491                               const X86Subtarget &Subtarget) {
47492   if (!Subtarget.hasSSE2())
47493     return SDValue();
47494 
47495   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
47496     return SDValue();
47497 
47498   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
47499       VT.getVectorNumElements() < 4 ||
47500       !isPowerOf2_32(VT.getVectorNumElements()))
47501     return SDValue();
47502 
47503   SDValue N00 = N0.getOperand(0);
47504   SDValue N01 = N0.getOperand(1);
47505   SDValue N10 = N1.getOperand(0);
47506   SDValue N11 = N1.getOperand(1);
47507 
47508   // All inputs need to be sign extends.
47509   // TODO: Support ZERO_EXTEND from known positive?
47510   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
47511       N01.getOpcode() != ISD::SIGN_EXTEND ||
47512       N10.getOpcode() != ISD::SIGN_EXTEND ||
47513       N11.getOpcode() != ISD::SIGN_EXTEND)
47514     return SDValue();
47515 
47516   // Peek through the extends.
47517   N00 = N00.getOperand(0);
47518   N01 = N01.getOperand(0);
47519   N10 = N10.getOperand(0);
47520   N11 = N11.getOperand(0);
47521 
47522   // Must be extending from vXi16.
47523   EVT InVT = N00.getValueType();
47524   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
47525       N10.getValueType() != InVT || N11.getValueType() != InVT)
47526     return SDValue();
47527 
47528   // All inputs should be build_vectors.
47529   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
47530       N01.getOpcode() != ISD::BUILD_VECTOR ||
47531       N10.getOpcode() != ISD::BUILD_VECTOR ||
47532       N11.getOpcode() != ISD::BUILD_VECTOR)
47533     return SDValue();
47534 
47535   // For each element, we need to ensure we have an odd element from one vector
47536   // multiplied by the odd element of another vector and the even element from
47537   // one of the same vectors being multiplied by the even element from the
47538   // other vector. So we need to make sure for each element i, this operator
47539   // is being performed:
47540   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
47541   SDValue In0, In1;
47542   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
47543     SDValue N00Elt = N00.getOperand(i);
47544     SDValue N01Elt = N01.getOperand(i);
47545     SDValue N10Elt = N10.getOperand(i);
47546     SDValue N11Elt = N11.getOperand(i);
47547     // TODO: Be more tolerant to undefs.
47548     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47549         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47550         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
47551         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
47552       return SDValue();
47553     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
47554     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
47555     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
47556     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
47557     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
47558       return SDValue();
47559     unsigned IdxN00 = ConstN00Elt->getZExtValue();
47560     unsigned IdxN01 = ConstN01Elt->getZExtValue();
47561     unsigned IdxN10 = ConstN10Elt->getZExtValue();
47562     unsigned IdxN11 = ConstN11Elt->getZExtValue();
47563     // Add is commutative so indices can be reordered.
47564     if (IdxN00 > IdxN10) {
47565       std::swap(IdxN00, IdxN10);
47566       std::swap(IdxN01, IdxN11);
47567     }
47568     // N0 indices be the even element. N1 indices must be the next odd element.
47569     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
47570         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
47571       return SDValue();
47572     SDValue N00In = N00Elt.getOperand(0);
47573     SDValue N01In = N01Elt.getOperand(0);
47574     SDValue N10In = N10Elt.getOperand(0);
47575     SDValue N11In = N11Elt.getOperand(0);
47576     // First time we find an input capture it.
47577     if (!In0) {
47578       In0 = N00In;
47579       In1 = N01In;
47580     }
47581     // Mul is commutative so the input vectors can be in any order.
47582     // Canonicalize to make the compares easier.
47583     if (In0 != N00In)
47584       std::swap(N00In, N01In);
47585     if (In0 != N10In)
47586       std::swap(N10In, N11In);
47587     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
47588       return SDValue();
47589   }
47590 
47591   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
47592                          ArrayRef<SDValue> Ops) {
47593     // Shrink by adding truncate nodes and let DAGCombine fold with the
47594     // sources.
47595     EVT OpVT = Ops[0].getValueType();
47596     assert(OpVT.getScalarType() == MVT::i16 &&
47597            "Unexpected scalar element type");
47598     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
47599     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
47600                                  OpVT.getVectorNumElements() / 2);
47601     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
47602   };
47603   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
47604                           PMADDBuilder);
47605 }
47606 
combineAdd(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47607 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
47608                           TargetLowering::DAGCombinerInfo &DCI,
47609                           const X86Subtarget &Subtarget) {
47610   EVT VT = N->getValueType(0);
47611   SDValue Op0 = N->getOperand(0);
47612   SDValue Op1 = N->getOperand(1);
47613 
47614   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
47615     return MAdd;
47616   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
47617     return MAdd;
47618 
47619   // Try to synthesize horizontal adds from adds of shuffles.
47620   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
47621        VT == MVT::v8i32) &&
47622       Subtarget.hasSSSE3() &&
47623       isHorizontalBinOp(Op0, Op1, DAG, Subtarget, true)) {
47624     auto HADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
47625                           ArrayRef<SDValue> Ops) {
47626       return DAG.getNode(X86ISD::HADD, DL, Ops[0].getValueType(), Ops);
47627     };
47628     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
47629                             HADDBuilder);
47630   }
47631 
47632   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
47633   // (sub Y, (sext (vXi1 X))).
47634   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
47635   // generic DAG combine without a legal type check, but adding this there
47636   // caused regressions.
47637   if (VT.isVector()) {
47638     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47639     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
47640         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
47641         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
47642       SDLoc DL(N);
47643       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
47644       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
47645     }
47646 
47647     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
47648         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
47649         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
47650       SDLoc DL(N);
47651       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
47652       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
47653     }
47654   }
47655 
47656   return combineAddOrSubToADCOrSBB(N, DAG);
47657 }
47658 
combineSubToSubus(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)47659 static SDValue combineSubToSubus(SDNode *N, SelectionDAG &DAG,
47660                                  const X86Subtarget &Subtarget) {
47661   SDValue Op0 = N->getOperand(0);
47662   SDValue Op1 = N->getOperand(1);
47663   EVT VT = N->getValueType(0);
47664 
47665   if (!VT.isVector())
47666     return SDValue();
47667 
47668   // PSUBUS is supported, starting from SSE2, but truncation for v8i32
47669   // is only worth it with SSSE3 (PSHUFB).
47670   EVT EltVT = VT.getVectorElementType();
47671   if (!(Subtarget.hasSSE2() && (EltVT == MVT::i8 || EltVT == MVT::i16)) &&
47672       !(Subtarget.hasSSSE3() && (VT == MVT::v8i32 || VT == MVT::v8i64)) &&
47673       !(Subtarget.useBWIRegs() && (VT == MVT::v16i32)))
47674     return SDValue();
47675 
47676   SDValue SubusLHS, SubusRHS;
47677   // Try to find umax(a,b) - b or a - umin(a,b) patterns
47678   // they may be converted to subus(a,b).
47679   // TODO: Need to add IR canonicalization for this code.
47680   if (Op0.getOpcode() == ISD::UMAX) {
47681     SubusRHS = Op1;
47682     SDValue MaxLHS = Op0.getOperand(0);
47683     SDValue MaxRHS = Op0.getOperand(1);
47684     if (MaxLHS == Op1)
47685       SubusLHS = MaxRHS;
47686     else if (MaxRHS == Op1)
47687       SubusLHS = MaxLHS;
47688     else
47689       return SDValue();
47690   } else if (Op1.getOpcode() == ISD::UMIN) {
47691     SubusLHS = Op0;
47692     SDValue MinLHS = Op1.getOperand(0);
47693     SDValue MinRHS = Op1.getOperand(1);
47694     if (MinLHS == Op0)
47695       SubusRHS = MinRHS;
47696     else if (MinRHS == Op0)
47697       SubusRHS = MinLHS;
47698     else
47699       return SDValue();
47700   } else if (Op1.getOpcode() == ISD::TRUNCATE &&
47701              Op1.getOperand(0).getOpcode() == ISD::UMIN &&
47702              (EltVT == MVT::i8 || EltVT == MVT::i16)) {
47703     // Special case where the UMIN has been truncated. Try to push the truncate
47704     // further up. This is similar to the i32/i64 special processing.
47705     SubusLHS = Op0;
47706     SDValue MinLHS = Op1.getOperand(0).getOperand(0);
47707     SDValue MinRHS = Op1.getOperand(0).getOperand(1);
47708     EVT TruncVT = Op1.getOperand(0).getValueType();
47709     if (!(Subtarget.hasSSSE3() && (TruncVT == MVT::v8i32 ||
47710                                    TruncVT == MVT::v8i64)) &&
47711         !(Subtarget.useBWIRegs() && (TruncVT == MVT::v16i32)))
47712       return SDValue();
47713     SDValue OpToSaturate;
47714     if (MinLHS.getOpcode() == ISD::ZERO_EXTEND &&
47715         MinLHS.getOperand(0) == Op0)
47716       OpToSaturate = MinRHS;
47717     else if (MinRHS.getOpcode() == ISD::ZERO_EXTEND &&
47718              MinRHS.getOperand(0) == Op0)
47719       OpToSaturate = MinLHS;
47720     else
47721       return SDValue();
47722 
47723     // Saturate the non-extended input and then truncate it.
47724     SDLoc DL(N);
47725     SDValue SaturationConst =
47726         DAG.getConstant(APInt::getLowBitsSet(TruncVT.getScalarSizeInBits(),
47727                                              VT.getScalarSizeInBits()),
47728                         DL, TruncVT);
47729     SDValue UMin = DAG.getNode(ISD::UMIN, DL, TruncVT, OpToSaturate,
47730                                SaturationConst);
47731     SubusRHS = DAG.getNode(ISD::TRUNCATE, DL, VT, UMin);
47732   } else
47733     return SDValue();
47734 
47735   // PSUBUS doesn't support v8i32/v8i64/v16i32, but it can be enabled with
47736   // special preprocessing in some cases.
47737   if (EltVT == MVT::i8 || EltVT == MVT::i16)
47738     return DAG.getNode(ISD::USUBSAT, SDLoc(N), VT, SubusLHS, SubusRHS);
47739 
47740   assert((VT == MVT::v8i32 || VT == MVT::v16i32 || VT == MVT::v8i64) &&
47741          "Unexpected VT!");
47742 
47743   // Special preprocessing case can be only applied
47744   // if the value was zero extended from 16 bit,
47745   // so we require first 16 bits to be zeros for 32 bit
47746   // values, or first 48 bits for 64 bit values.
47747   KnownBits Known = DAG.computeKnownBits(SubusLHS);
47748   unsigned NumZeros = Known.countMinLeadingZeros();
47749   if ((VT == MVT::v8i64 && NumZeros < 48) || NumZeros < 16)
47750     return SDValue();
47751 
47752   EVT ExtType = SubusLHS.getValueType();
47753   EVT ShrinkedType;
47754   if (VT == MVT::v8i32 || VT == MVT::v8i64)
47755     ShrinkedType = MVT::v8i16;
47756   else
47757     ShrinkedType = NumZeros >= 24 ? MVT::v16i8 : MVT::v16i16;
47758 
47759   // If SubusLHS is zeroextended - truncate SubusRHS to it's
47760   // size SubusRHS = umin(0xFFF.., SubusRHS).
47761   SDValue SaturationConst =
47762       DAG.getConstant(APInt::getLowBitsSet(ExtType.getScalarSizeInBits(),
47763                                            ShrinkedType.getScalarSizeInBits()),
47764                       SDLoc(SubusLHS), ExtType);
47765   SDValue UMin = DAG.getNode(ISD::UMIN, SDLoc(SubusLHS), ExtType, SubusRHS,
47766                              SaturationConst);
47767   SDValue NewSubusLHS =
47768       DAG.getZExtOrTrunc(SubusLHS, SDLoc(SubusLHS), ShrinkedType);
47769   SDValue NewSubusRHS = DAG.getZExtOrTrunc(UMin, SDLoc(SubusRHS), ShrinkedType);
47770   SDValue Psubus = DAG.getNode(ISD::USUBSAT, SDLoc(N), ShrinkedType,
47771                                NewSubusLHS, NewSubusRHS);
47772 
47773   // Zero extend the result, it may be used somewhere as 32 bit,
47774   // if not zext and following trunc will shrink.
47775   return DAG.getZExtOrTrunc(Psubus, SDLoc(N), ExtType);
47776 }
47777 
combineSub(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)47778 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
47779                           TargetLowering::DAGCombinerInfo &DCI,
47780                           const X86Subtarget &Subtarget) {
47781   SDValue Op0 = N->getOperand(0);
47782   SDValue Op1 = N->getOperand(1);
47783 
47784   // X86 can't encode an immediate LHS of a sub. See if we can push the
47785   // negation into a preceding instruction.
47786   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
47787     // If the RHS of the sub is a XOR with one use and a constant, invert the
47788     // immediate. Then add one to the LHS of the sub so we can turn
47789     // X-Y -> X+~Y+1, saving one register.
47790     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
47791         isa<ConstantSDNode>(Op1.getOperand(1))) {
47792       const APInt &XorC = Op1.getConstantOperandAPInt(1);
47793       EVT VT = Op0.getValueType();
47794       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
47795                                    Op1.getOperand(0),
47796                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
47797       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
47798                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
47799     }
47800   }
47801 
47802   // Try to synthesize horizontal subs from subs of shuffles.
47803   EVT VT = N->getValueType(0);
47804   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
47805        VT == MVT::v8i32) &&
47806       Subtarget.hasSSSE3() &&
47807       isHorizontalBinOp(Op0, Op1, DAG, Subtarget, false)) {
47808     auto HSUBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
47809                           ArrayRef<SDValue> Ops) {
47810       return DAG.getNode(X86ISD::HSUB, DL, Ops[0].getValueType(), Ops);
47811     };
47812     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
47813                             HSUBBuilder);
47814   }
47815 
47816   // Try to create PSUBUS if SUB's argument is max/min
47817   if (SDValue V = combineSubToSubus(N, DAG, Subtarget))
47818     return V;
47819 
47820   return combineAddOrSubToADCOrSBB(N, DAG);
47821 }
47822 
combineVectorCompare(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)47823 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
47824                                     const X86Subtarget &Subtarget) {
47825   MVT VT = N->getSimpleValueType(0);
47826   SDLoc DL(N);
47827 
47828   if (N->getOperand(0) == N->getOperand(1)) {
47829     if (N->getOpcode() == X86ISD::PCMPEQ)
47830       return DAG.getConstant(-1, DL, VT);
47831     if (N->getOpcode() == X86ISD::PCMPGT)
47832       return DAG.getConstant(0, DL, VT);
47833   }
47834 
47835   return SDValue();
47836 }
47837 
47838 /// Helper that combines an array of subvector ops as if they were the operands
47839 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
47840 /// 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)47841 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
47842                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
47843                                       TargetLowering::DAGCombinerInfo &DCI,
47844                                       const X86Subtarget &Subtarget) {
47845   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
47846   unsigned EltSizeInBits = VT.getScalarSizeInBits();
47847 
47848   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
47849     return DAG.getUNDEF(VT);
47850 
47851   if (llvm::all_of(Ops, [](SDValue Op) {
47852         return ISD::isBuildVectorAllZeros(Op.getNode());
47853       }))
47854     return getZeroVector(VT, Subtarget, DAG, DL);
47855 
47856   SDValue Op0 = Ops[0];
47857   bool IsSplat = llvm::all_of(Ops, [&Op0](SDValue Op) { return Op == Op0; });
47858 
47859   // Fold subvector loads into one.
47860   // If needed, look through bitcasts to get to the load.
47861   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
47862     bool Fast;
47863     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
47864     if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
47865                                 *FirstLd->getMemOperand(), &Fast) &&
47866         Fast) {
47867       if (SDValue Ld =
47868               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
47869         return Ld;
47870     }
47871   }
47872 
47873   // Repeated subvectors.
47874   if (IsSplat) {
47875     // If this broadcast/subv_broadcast is inserted into both halves, use a
47876     // larger broadcast/subv_broadcast.
47877     if (Op0.getOpcode() == X86ISD::VBROADCAST ||
47878         Op0.getOpcode() == X86ISD::SUBV_BROADCAST)
47879       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
47880 
47881     // If this broadcast_load is inserted into both halves, use a larger
47882     // broadcast_load. Update other uses to use an extracted subvector.
47883     if (Op0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
47884       auto *MemIntr = cast<MemIntrinsicSDNode>(Op0);
47885       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
47886       SDValue Ops[] = {MemIntr->getChain(), MemIntr->getBasePtr()};
47887       SDValue BcastLd = DAG.getMemIntrinsicNode(
47888           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
47889           MemIntr->getMemOperand());
47890       DAG.ReplaceAllUsesOfValueWith(
47891           Op0, extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits()));
47892       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
47893       return BcastLd;
47894     }
47895 
47896     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
47897     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
47898         (Subtarget.hasAVX2() || MayFoldLoad(Op0.getOperand(0))))
47899       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
47900                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
47901                                      Op0.getOperand(0),
47902                                      DAG.getIntPtrConstant(0, DL)));
47903 
47904     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
47905     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
47906         (Subtarget.hasAVX2() ||
47907          (EltSizeInBits >= 32 && MayFoldLoad(Op0.getOperand(0)))) &&
47908         Op0.getOperand(0).getValueType() == VT.getScalarType())
47909       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
47910 
47911     // concat_vectors(extract_subvector(broadcast(x)),
47912     //                extract_subvector(broadcast(x))) -> broadcast(x)
47913     if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
47914         Op0.getOperand(0).getValueType() == VT) {
47915       if (Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST ||
47916           Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST_LOAD)
47917         return Op0.getOperand(0);
47918     }
47919   }
47920 
47921   // Repeated opcode.
47922   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
47923   // but it currently struggles with different vector widths.
47924   if (llvm::all_of(Ops, [Op0](SDValue Op) {
47925         return Op.getOpcode() == Op0.getOpcode();
47926       })) {
47927     unsigned NumOps = Ops.size();
47928     switch (Op0.getOpcode()) {
47929     case X86ISD::SHUFP: {
47930       // Add SHUFPD support if/when necessary.
47931       if (!IsSplat && VT.getScalarType() == MVT::f32 &&
47932           llvm::all_of(Ops, [Op0](SDValue Op) {
47933             return Op.getOperand(2) == Op0.getOperand(2);
47934           })) {
47935         SmallVector<SDValue, 2> LHS, RHS;
47936         for (unsigned i = 0; i != NumOps; ++i) {
47937           LHS.push_back(Ops[i].getOperand(0));
47938           RHS.push_back(Ops[i].getOperand(1));
47939         }
47940         return DAG.getNode(Op0.getOpcode(), DL, VT,
47941                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS),
47942                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, RHS),
47943                            Op0.getOperand(2));
47944       }
47945       break;
47946     }
47947     case X86ISD::PSHUFHW:
47948     case X86ISD::PSHUFLW:
47949     case X86ISD::PSHUFD:
47950       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
47951           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
47952         SmallVector<SDValue, 2> Src;
47953         for (unsigned i = 0; i != NumOps; ++i)
47954           Src.push_back(Ops[i].getOperand(0));
47955         return DAG.getNode(Op0.getOpcode(), DL, VT,
47956                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
47957                            Op0.getOperand(1));
47958       }
47959       LLVM_FALLTHROUGH;
47960     case X86ISD::VPERMILPI:
47961       // TODO - add support for vXf64/vXi64 shuffles.
47962       if (!IsSplat && NumOps == 2 && (VT == MVT::v8f32 || VT == MVT::v8i32) &&
47963           Subtarget.hasAVX() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
47964         SmallVector<SDValue, 2> Src;
47965         for (unsigned i = 0; i != NumOps; ++i)
47966           Src.push_back(DAG.getBitcast(MVT::v4f32, Ops[i].getOperand(0)));
47967         SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f32, Src);
47968         Res = DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, Res,
47969                           Op0.getOperand(1));
47970         return DAG.getBitcast(VT, Res);
47971       }
47972       break;
47973     case X86ISD::VSHLI:
47974     case X86ISD::VSRAI:
47975     case X86ISD::VSRLI:
47976       if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
47977            (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
47978             (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
47979           llvm::all_of(Ops, [Op0](SDValue Op) {
47980             return Op0.getOperand(1) == Op.getOperand(1);
47981           })) {
47982         SmallVector<SDValue, 2> Src;
47983         for (unsigned i = 0; i != NumOps; ++i)
47984           Src.push_back(Ops[i].getOperand(0));
47985         return DAG.getNode(Op0.getOpcode(), DL, VT,
47986                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
47987                            Op0.getOperand(1));
47988       }
47989       break;
47990     case X86ISD::VPERMI:
47991     case X86ISD::VROTLI:
47992     case X86ISD::VROTRI:
47993       if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
47994           llvm::all_of(Ops, [Op0](SDValue Op) {
47995             return Op0.getOperand(1) == Op.getOperand(1);
47996           })) {
47997         SmallVector<SDValue, 2> Src;
47998         for (unsigned i = 0; i != NumOps; ++i)
47999           Src.push_back(Ops[i].getOperand(0));
48000         return DAG.getNode(Op0.getOpcode(), DL, VT,
48001                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
48002                            Op0.getOperand(1));
48003       }
48004       break;
48005     case X86ISD::PACKSS:
48006     case X86ISD::PACKUS:
48007       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
48008           Subtarget.hasInt256()) {
48009         SmallVector<SDValue, 2> LHS, RHS;
48010         for (unsigned i = 0; i != NumOps; ++i) {
48011           LHS.push_back(Ops[i].getOperand(0));
48012           RHS.push_back(Ops[i].getOperand(1));
48013         }
48014         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
48015         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
48016                                  NumOps * SrcVT.getVectorNumElements());
48017         return DAG.getNode(Op0.getOpcode(), DL, VT,
48018                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, LHS),
48019                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, RHS));
48020       }
48021       break;
48022     case X86ISD::PALIGNR:
48023       if (!IsSplat &&
48024           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
48025            (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
48026           llvm::all_of(Ops, [Op0](SDValue Op) {
48027             return Op0.getOperand(2) == Op.getOperand(2);
48028           })) {
48029         SmallVector<SDValue, 2> LHS, RHS;
48030         for (unsigned i = 0; i != NumOps; ++i) {
48031           LHS.push_back(Ops[i].getOperand(0));
48032           RHS.push_back(Ops[i].getOperand(1));
48033         }
48034         return DAG.getNode(Op0.getOpcode(), DL, VT,
48035                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS),
48036                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, RHS),
48037                            Op0.getOperand(2));
48038       }
48039       break;
48040     }
48041   }
48042 
48043   return SDValue();
48044 }
48045 
combineConcatVectors(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48046 static SDValue combineConcatVectors(SDNode *N, SelectionDAG &DAG,
48047                                     TargetLowering::DAGCombinerInfo &DCI,
48048                                     const X86Subtarget &Subtarget) {
48049   EVT VT = N->getValueType(0);
48050   EVT SrcVT = N->getOperand(0).getValueType();
48051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48052 
48053   // Don't do anything for i1 vectors.
48054   if (VT.getVectorElementType() == MVT::i1)
48055     return SDValue();
48056 
48057   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
48058     SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
48059     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
48060                                            DCI, Subtarget))
48061       return R;
48062   }
48063 
48064   return SDValue();
48065 }
48066 
combineInsertSubvector(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48067 static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
48068                                       TargetLowering::DAGCombinerInfo &DCI,
48069                                       const X86Subtarget &Subtarget) {
48070   if (DCI.isBeforeLegalizeOps())
48071     return SDValue();
48072 
48073   MVT OpVT = N->getSimpleValueType(0);
48074 
48075   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
48076 
48077   SDLoc dl(N);
48078   SDValue Vec = N->getOperand(0);
48079   SDValue SubVec = N->getOperand(1);
48080 
48081   uint64_t IdxVal = N->getConstantOperandVal(2);
48082   MVT SubVecVT = SubVec.getSimpleValueType();
48083 
48084   if (Vec.isUndef() && SubVec.isUndef())
48085     return DAG.getUNDEF(OpVT);
48086 
48087   // Inserting undefs/zeros into zeros/undefs is a zero vector.
48088   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
48089       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
48090     return getZeroVector(OpVT, Subtarget, DAG, dl);
48091 
48092   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
48093     // If we're inserting into a zero vector and then into a larger zero vector,
48094     // just insert into the larger zero vector directly.
48095     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
48096         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
48097       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
48098       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
48099                          getZeroVector(OpVT, Subtarget, DAG, dl),
48100                          SubVec.getOperand(1),
48101                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
48102     }
48103 
48104     // If we're inserting into a zero vector and our input was extracted from an
48105     // insert into a zero vector of the same type and the extraction was at
48106     // least as large as the original insertion. Just insert the original
48107     // subvector into a zero vector.
48108     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
48109         isNullConstant(SubVec.getOperand(1)) &&
48110         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
48111       SDValue Ins = SubVec.getOperand(0);
48112       if (isNullConstant(Ins.getOperand(2)) &&
48113           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
48114           Ins.getOperand(1).getValueSizeInBits() <= SubVecVT.getSizeInBits())
48115         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
48116                            getZeroVector(OpVT, Subtarget, DAG, dl),
48117                            Ins.getOperand(1), N->getOperand(2));
48118     }
48119   }
48120 
48121   // Stop here if this is an i1 vector.
48122   if (IsI1Vector)
48123     return SDValue();
48124 
48125   // If this is an insert of an extract, combine to a shuffle. Don't do this
48126   // if the insert or extract can be represented with a subregister operation.
48127   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
48128       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
48129       (IdxVal != 0 ||
48130        !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
48131     int ExtIdxVal = SubVec.getConstantOperandVal(1);
48132     if (ExtIdxVal != 0) {
48133       int VecNumElts = OpVT.getVectorNumElements();
48134       int SubVecNumElts = SubVecVT.getVectorNumElements();
48135       SmallVector<int, 64> Mask(VecNumElts);
48136       // First create an identity shuffle mask.
48137       for (int i = 0; i != VecNumElts; ++i)
48138         Mask[i] = i;
48139       // Now insert the extracted portion.
48140       for (int i = 0; i != SubVecNumElts; ++i)
48141         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
48142 
48143       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
48144     }
48145   }
48146 
48147   // Match concat_vector style patterns.
48148   SmallVector<SDValue, 2> SubVectorOps;
48149   if (collectConcatOps(N, SubVectorOps)) {
48150     if (SDValue Fold =
48151             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
48152       return Fold;
48153 
48154     // If we're inserting all zeros into the upper half, change this to
48155     // a concat with zero. We will match this to a move
48156     // with implicit upper bit zeroing during isel.
48157     // We do this here because we don't want combineConcatVectorOps to
48158     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
48159     if (SubVectorOps.size() == 2 &&
48160         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
48161       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
48162                          getZeroVector(OpVT, Subtarget, DAG, dl),
48163                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
48164   }
48165 
48166   // If this is a broadcast insert into an upper undef, use a larger broadcast.
48167   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
48168     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
48169 
48170   // If this is a broadcast load inserted into an upper undef, use a larger
48171   // broadcast load.
48172   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
48173       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
48174     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
48175     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
48176     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
48177     SDValue BcastLd =
48178         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
48179                                 MemIntr->getMemoryVT(),
48180                                 MemIntr->getMemOperand());
48181     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
48182     return BcastLd;
48183   }
48184 
48185   return SDValue();
48186 }
48187 
48188 /// If we are extracting a subvector of a vector select and the select condition
48189 /// is composed of concatenated vectors, try to narrow the select width. This
48190 /// is a common pattern for AVX1 integer code because 256-bit selects may be
48191 /// legal, but there is almost no integer math/logic available for 256-bit.
48192 /// This function should only be called with legal types (otherwise, the calls
48193 /// to get simple value types will assert).
narrowExtractedVectorSelect(SDNode * Ext,SelectionDAG & DAG)48194 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
48195   SDValue Sel = peekThroughBitcasts(Ext->getOperand(0));
48196   SmallVector<SDValue, 4> CatOps;
48197   if (Sel.getOpcode() != ISD::VSELECT ||
48198       !collectConcatOps(Sel.getOperand(0).getNode(), CatOps))
48199     return SDValue();
48200 
48201   // Note: We assume simple value types because this should only be called with
48202   //       legal operations/types.
48203   // TODO: This can be extended to handle extraction to 256-bits.
48204   MVT VT = Ext->getSimpleValueType(0);
48205   if (!VT.is128BitVector())
48206     return SDValue();
48207 
48208   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
48209   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
48210     return SDValue();
48211 
48212   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
48213   MVT SelVT = Sel.getSimpleValueType();
48214   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
48215          "Unexpected vector type with legal operations");
48216 
48217   unsigned SelElts = SelVT.getVectorNumElements();
48218   unsigned CastedElts = WideVT.getVectorNumElements();
48219   unsigned ExtIdx = Ext->getConstantOperandVal(1);
48220   if (SelElts % CastedElts == 0) {
48221     // The select has the same or more (narrower) elements than the extract
48222     // operand. The extraction index gets scaled by that factor.
48223     ExtIdx *= (SelElts / CastedElts);
48224   } else if (CastedElts % SelElts == 0) {
48225     // The select has less (wider) elements than the extract operand. Make sure
48226     // that the extraction index can be divided evenly.
48227     unsigned IndexDivisor = CastedElts / SelElts;
48228     if (ExtIdx % IndexDivisor != 0)
48229       return SDValue();
48230     ExtIdx /= IndexDivisor;
48231   } else {
48232     llvm_unreachable("Element count of simple vector types are not divisible?");
48233   }
48234 
48235   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
48236   unsigned NarrowElts = SelElts / NarrowingFactor;
48237   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
48238   SDLoc DL(Ext);
48239   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
48240   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
48241   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
48242   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
48243   return DAG.getBitcast(VT, NarrowSel);
48244 }
48245 
combineExtractSubvector(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48246 static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
48247                                        TargetLowering::DAGCombinerInfo &DCI,
48248                                        const X86Subtarget &Subtarget) {
48249   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
48250   // eventually get combined/lowered into ANDNP) with a concatenated operand,
48251   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
48252   // We let generic combining take over from there to simplify the
48253   // insert/extract and 'not'.
48254   // This pattern emerges during AVX1 legalization. We handle it before lowering
48255   // to avoid complications like splitting constant vector loads.
48256 
48257   // Capture the original wide type in the likely case that we need to bitcast
48258   // back to this type.
48259   if (!N->getValueType(0).isSimple())
48260     return SDValue();
48261 
48262   MVT VT = N->getSimpleValueType(0);
48263   SDValue InVec = N->getOperand(0);
48264   unsigned IdxVal = N->getConstantOperandVal(1);
48265   SDValue InVecBC = peekThroughBitcasts(InVec);
48266   EVT InVecVT = InVec.getValueType();
48267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48268 
48269   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
48270       TLI.isTypeLegal(InVecVT) &&
48271       InVecVT.getSizeInBits() == 256 && InVecBC.getOpcode() == ISD::AND) {
48272     auto isConcatenatedNot = [] (SDValue V) {
48273       V = peekThroughBitcasts(V);
48274       if (!isBitwiseNot(V))
48275         return false;
48276       SDValue NotOp = V->getOperand(0);
48277       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
48278     };
48279     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
48280         isConcatenatedNot(InVecBC.getOperand(1))) {
48281       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
48282       SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
48283       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
48284                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
48285     }
48286   }
48287 
48288   if (DCI.isBeforeLegalizeOps())
48289     return SDValue();
48290 
48291   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
48292     return V;
48293 
48294   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
48295     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
48296 
48297   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
48298     if (VT.getScalarType() == MVT::i1)
48299       return DAG.getConstant(1, SDLoc(N), VT);
48300     return getOnesVector(VT, DAG, SDLoc(N));
48301   }
48302 
48303   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
48304     return DAG.getBuildVector(
48305         VT, SDLoc(N),
48306         InVec.getNode()->ops().slice(IdxVal, VT.getVectorNumElements()));
48307 
48308   // If we are extracting from an insert into a zero vector, replace with a
48309   // smaller insert into zero if we don't access less than the original
48310   // subvector. Don't do this for i1 vectors.
48311   if (VT.getVectorElementType() != MVT::i1 &&
48312       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && IdxVal == 0 &&
48313       InVec.hasOneUse() && isNullConstant(InVec.getOperand(2)) &&
48314       ISD::isBuildVectorAllZeros(InVec.getOperand(0).getNode()) &&
48315       InVec.getOperand(1).getValueSizeInBits() <= VT.getSizeInBits()) {
48316     SDLoc DL(N);
48317     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
48318                        getZeroVector(VT, Subtarget, DAG, DL),
48319                        InVec.getOperand(1), InVec.getOperand(2));
48320   }
48321 
48322   // If we're extracting from a broadcast then we're better off just
48323   // broadcasting to the smaller type directly, assuming this is the only use.
48324   // As its a broadcast we don't care about the extraction index.
48325   if (InVec.getOpcode() == X86ISD::VBROADCAST && InVec.hasOneUse() &&
48326       InVec.getOperand(0).getValueSizeInBits() <= VT.getSizeInBits())
48327     return DAG.getNode(X86ISD::VBROADCAST, SDLoc(N), VT, InVec.getOperand(0));
48328 
48329   if (InVec.getOpcode() == X86ISD::VBROADCAST_LOAD && InVec.hasOneUse()) {
48330     auto *MemIntr = cast<MemIntrinsicSDNode>(InVec);
48331     if (MemIntr->getMemoryVT().getSizeInBits() <= VT.getSizeInBits()) {
48332       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
48333       SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
48334       SDValue BcastLd =
48335           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
48336                                   MemIntr->getMemoryVT(),
48337                                   MemIntr->getMemOperand());
48338       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
48339       return BcastLd;
48340     }
48341   }
48342 
48343   // If we're extracting an upper subvector from a broadcast we should just
48344   // extract the lowest subvector instead which should allow
48345   // SimplifyDemandedVectorElts do more simplifications.
48346   if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
48347                       InVec.getOpcode() == X86ISD::VBROADCAST_LOAD))
48348     return extractSubVector(InVec, 0, DAG, SDLoc(N), VT.getSizeInBits());
48349 
48350   // If we're extracting a broadcasted subvector, just use the source.
48351   if (InVec.getOpcode() == X86ISD::SUBV_BROADCAST &&
48352       InVec.getOperand(0).getValueType() == VT)
48353     return InVec.getOperand(0);
48354 
48355   // Attempt to extract from the source of a shuffle vector.
48356   if ((InVecVT.getSizeInBits() % VT.getSizeInBits()) == 0 &&
48357       (IdxVal % VT.getVectorNumElements()) == 0) {
48358     SmallVector<int, 32> ShuffleMask;
48359     SmallVector<int, 32> ScaledMask;
48360     SmallVector<SDValue, 2> ShuffleInputs;
48361     unsigned NumSubVecs = InVecVT.getSizeInBits() / VT.getSizeInBits();
48362     // Decode the shuffle mask and scale it so its shuffling subvectors.
48363     if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
48364         scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
48365       unsigned SubVecIdx = IdxVal / VT.getVectorNumElements();
48366       if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
48367         return DAG.getUNDEF(VT);
48368       if (ScaledMask[SubVecIdx] == SM_SentinelZero)
48369         return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
48370       SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
48371       if (Src.getValueSizeInBits() == InVecVT.getSizeInBits()) {
48372         unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
48373         unsigned SrcEltIdx = SrcSubVecIdx * VT.getVectorNumElements();
48374         return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
48375                                 SDLoc(N), VT.getSizeInBits());
48376       }
48377     }
48378   }
48379 
48380   // If we're extracting the lowest subvector and we're the only user,
48381   // we may be able to perform this with a smaller vector width.
48382   if (IdxVal == 0 && InVec.hasOneUse()) {
48383     unsigned InOpcode = InVec.getOpcode();
48384     if (VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
48385       // v2f64 CVTDQ2PD(v4i32).
48386       if (InOpcode == ISD::SINT_TO_FP &&
48387           InVec.getOperand(0).getValueType() == MVT::v4i32) {
48388         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
48389       }
48390       // v2f64 CVTUDQ2PD(v4i32).
48391       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
48392           InVec.getOperand(0).getValueType() == MVT::v4i32) {
48393         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
48394       }
48395       // v2f64 CVTPS2PD(v4f32).
48396       if (InOpcode == ISD::FP_EXTEND &&
48397           InVec.getOperand(0).getValueType() == MVT::v4f32) {
48398         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
48399       }
48400     }
48401     if ((InOpcode == ISD::ANY_EXTEND ||
48402          InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
48403          InOpcode == ISD::ZERO_EXTEND ||
48404          InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
48405          InOpcode == ISD::SIGN_EXTEND ||
48406          InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
48407         VT.is128BitVector() &&
48408         InVec.getOperand(0).getSimpleValueType().is128BitVector()) {
48409       unsigned ExtOp = getOpcode_EXTEND_VECTOR_INREG(InOpcode);
48410       return DAG.getNode(ExtOp, SDLoc(N), VT, InVec.getOperand(0));
48411     }
48412     if (InOpcode == ISD::VSELECT &&
48413         InVec.getOperand(0).getValueType().is256BitVector() &&
48414         InVec.getOperand(1).getValueType().is256BitVector() &&
48415         InVec.getOperand(2).getValueType().is256BitVector()) {
48416       SDLoc DL(N);
48417       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
48418       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
48419       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
48420       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
48421     }
48422   }
48423 
48424   return SDValue();
48425 }
48426 
combineScalarToVector(SDNode * N,SelectionDAG & DAG)48427 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
48428   EVT VT = N->getValueType(0);
48429   SDValue Src = N->getOperand(0);
48430   SDLoc DL(N);
48431 
48432   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
48433   // This occurs frequently in our masked scalar intrinsic code and our
48434   // floating point select lowering with AVX512.
48435   // TODO: SimplifyDemandedBits instead?
48436   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
48437     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
48438       if (C->getAPIntValue().isOneValue())
48439         return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
48440                            Src.getOperand(0));
48441 
48442   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
48443   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
48444       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
48445       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
48446     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
48447       if (C->isNullValue())
48448         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
48449                            Src.getOperand(1));
48450 
48451   // Reduce v2i64 to v4i32 if we don't need the upper bits.
48452   // TODO: Move to DAGCombine/SimplifyDemandedBits?
48453   if (VT == MVT::v2i64 || VT == MVT::v2f64) {
48454     auto IsAnyExt64 = [](SDValue Op) {
48455       if (Op.getValueType() != MVT::i64 || !Op.hasOneUse())
48456         return SDValue();
48457       if (Op.getOpcode() == ISD::ANY_EXTEND &&
48458           Op.getOperand(0).getScalarValueSizeInBits() <= 32)
48459         return Op.getOperand(0);
48460       if (auto *Ld = dyn_cast<LoadSDNode>(Op))
48461         if (Ld->getExtensionType() == ISD::EXTLOAD &&
48462             Ld->getMemoryVT().getScalarSizeInBits() <= 32)
48463           return Op;
48464       return SDValue();
48465     };
48466     if (SDValue ExtSrc = IsAnyExt64(peekThroughOneUseBitcasts(Src)))
48467       return DAG.getBitcast(
48468           VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
48469                           DAG.getAnyExtOrTrunc(ExtSrc, DL, MVT::i32)));
48470   }
48471 
48472   // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
48473   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
48474       Src.getOperand(0).getValueType() == MVT::x86mmx)
48475     return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
48476 
48477   return SDValue();
48478 }
48479 
48480 // Simplify PMULDQ and PMULUDQ operations.
combinePMULDQ(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48481 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
48482                              TargetLowering::DAGCombinerInfo &DCI,
48483                              const X86Subtarget &Subtarget) {
48484   SDValue LHS = N->getOperand(0);
48485   SDValue RHS = N->getOperand(1);
48486 
48487   // Canonicalize constant to RHS.
48488   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
48489       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
48490     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
48491 
48492   // Multiply by zero.
48493   // Don't return RHS as it may contain UNDEFs.
48494   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
48495     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
48496 
48497   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
48498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48499   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnesValue(64), DCI))
48500     return SDValue(N, 0);
48501 
48502   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
48503   // convert it to any_extend_invec, due to the LegalOperations check, do the
48504   // conversion directly to a vector shuffle manually. This exposes combine
48505   // opportunities missed by combineExtInVec not calling
48506   // combineX86ShufflesRecursively on SSE4.1 targets.
48507   // FIXME: This is basically a hack around several other issues related to
48508   // ANY_EXTEND_VECTOR_INREG.
48509   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
48510       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
48511        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
48512       LHS.getOperand(0).getValueType() == MVT::v4i32) {
48513     SDLoc dl(N);
48514     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
48515                                LHS.getOperand(0), { 0, -1, 1, -1 });
48516     LHS = DAG.getBitcast(MVT::v2i64, LHS);
48517     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
48518   }
48519   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
48520       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
48521        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
48522       RHS.getOperand(0).getValueType() == MVT::v4i32) {
48523     SDLoc dl(N);
48524     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
48525                                RHS.getOperand(0), { 0, -1, 1, -1 });
48526     RHS = DAG.getBitcast(MVT::v2i64, RHS);
48527     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
48528   }
48529 
48530   return SDValue();
48531 }
48532 
combineExtInVec(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI,const X86Subtarget & Subtarget)48533 static SDValue combineExtInVec(SDNode *N, SelectionDAG &DAG,
48534                                TargetLowering::DAGCombinerInfo &DCI,
48535                                const X86Subtarget &Subtarget) {
48536   EVT VT = N->getValueType(0);
48537   SDValue In = N->getOperand(0);
48538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48539 
48540   // Try to merge vector loads and extend_inreg to an extload.
48541   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
48542       In.hasOneUse()) {
48543     auto *Ld = cast<LoadSDNode>(In);
48544     if (Ld->isSimple()) {
48545       MVT SVT = In.getSimpleValueType().getVectorElementType();
48546       ISD::LoadExtType Ext = N->getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG
48547                                  ? ISD::SEXTLOAD
48548                                  : ISD::ZEXTLOAD;
48549       EVT MemVT =
48550           EVT::getVectorVT(*DAG.getContext(), SVT, VT.getVectorNumElements());
48551       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
48552         SDValue Load =
48553             DAG.getExtLoad(Ext, SDLoc(N), VT, Ld->getChain(), Ld->getBasePtr(),
48554                            Ld->getPointerInfo(), MemVT,
48555                            Ld->getOriginalAlign(),
48556                            Ld->getMemOperand()->getFlags());
48557         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
48558         return Load;
48559       }
48560     }
48561   }
48562 
48563   // Attempt to combine as a shuffle.
48564   // TODO: SSE41 support
48565   if (Subtarget.hasAVX() && N->getOpcode() != ISD::SIGN_EXTEND_VECTOR_INREG) {
48566     SDValue Op(N, 0);
48567     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
48568       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
48569         return Res;
48570   }
48571 
48572   return SDValue();
48573 }
48574 
combineKSHIFT(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)48575 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
48576                              TargetLowering::DAGCombinerInfo &DCI) {
48577   EVT VT = N->getValueType(0);
48578 
48579   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
48580     return DAG.getConstant(0, SDLoc(N), VT);
48581 
48582   APInt KnownUndef, KnownZero;
48583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48584   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
48585   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
48586                                      KnownZero, DCI))
48587     return SDValue(N, 0);
48588 
48589   return SDValue();
48590 }
48591 
48592 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
48593 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
48594 // extra instructions between the conversion due to going to scalar and back.
combineFP16_TO_FP(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48595 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
48596                                  const X86Subtarget &Subtarget) {
48597   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
48598     return SDValue();
48599 
48600   if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
48601     return SDValue();
48602 
48603   if (N->getValueType(0) != MVT::f32 ||
48604       N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
48605     return SDValue();
48606 
48607   SDLoc dl(N);
48608   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
48609                             N->getOperand(0).getOperand(0));
48610   Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
48611                     DAG.getTargetConstant(4, dl, MVT::i32));
48612   Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
48613   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
48614                      DAG.getIntPtrConstant(0, dl));
48615 }
48616 
combineFP_EXTEND(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48617 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
48618                                 const X86Subtarget &Subtarget) {
48619   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
48620     return SDValue();
48621 
48622   bool IsStrict = N->isStrictFPOpcode();
48623   EVT VT = N->getValueType(0);
48624   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
48625   EVT SrcVT = Src.getValueType();
48626 
48627   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
48628     return SDValue();
48629 
48630   if (VT.getVectorElementType() != MVT::f32 &&
48631       VT.getVectorElementType() != MVT::f64)
48632     return SDValue();
48633 
48634   unsigned NumElts = VT.getVectorNumElements();
48635   if (NumElts == 1 || !isPowerOf2_32(NumElts))
48636     return SDValue();
48637 
48638   SDLoc dl(N);
48639 
48640   // Convert the input to vXi16.
48641   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
48642   Src = DAG.getBitcast(IntVT, Src);
48643 
48644   // Widen to at least 8 input elements.
48645   if (NumElts < 8) {
48646     unsigned NumConcats = 8 / NumElts;
48647     SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
48648                                 : DAG.getConstant(0, dl, IntVT);
48649     SmallVector<SDValue, 4> Ops(NumConcats, Fill);
48650     Ops[0] = Src;
48651     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
48652   }
48653 
48654   // Destination is vXf32 with at least 4 elements.
48655   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
48656                                std::max(4U, NumElts));
48657   SDValue Cvt, Chain;
48658   if (IsStrict) {
48659     Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
48660                       {N->getOperand(0), Src});
48661     Chain = Cvt.getValue(1);
48662   } else {
48663     Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
48664   }
48665 
48666   if (NumElts < 4) {
48667     assert(NumElts == 2 && "Unexpected size");
48668     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
48669                       DAG.getIntPtrConstant(0, dl));
48670   }
48671 
48672   if (IsStrict) {
48673     // Extend to the original VT if necessary.
48674     if (Cvt.getValueType() != VT) {
48675       Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
48676                         {Chain, Cvt});
48677       Chain = Cvt.getValue(1);
48678     }
48679     return DAG.getMergeValues({Cvt, Chain}, dl);
48680   }
48681 
48682   // Extend to the original VT if necessary.
48683   return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
48684 }
48685 
48686 // Try to find a larger VBROADCAST_LOAD that we can extract from. Limit this to
48687 // cases where the loads have the same input chain and the output chains are
48688 // unused. This avoids any memory ordering issues.
combineVBROADCAST_LOAD(SDNode * N,SelectionDAG & DAG,TargetLowering::DAGCombinerInfo & DCI)48689 static SDValue combineVBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
48690                                       TargetLowering::DAGCombinerInfo &DCI) {
48691   // Only do this if the chain result is unused.
48692   if (N->hasAnyUseOfValue(1))
48693     return SDValue();
48694 
48695   auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
48696 
48697   SDValue Ptr = MemIntrin->getBasePtr();
48698   SDValue Chain = MemIntrin->getChain();
48699   EVT VT = N->getSimpleValueType(0);
48700   EVT MemVT = MemIntrin->getMemoryVT();
48701 
48702   // Look at other users of our base pointer and try to find a wider broadcast.
48703   // The input chain and the size of the memory VT must match.
48704   for (SDNode *User : Ptr->uses())
48705     if (User != N && User->getOpcode() == X86ISD::VBROADCAST_LOAD &&
48706         cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
48707         cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
48708         cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
48709             MemVT.getSizeInBits() &&
48710         !User->hasAnyUseOfValue(1) &&
48711         User->getValueSizeInBits(0) > VT.getSizeInBits()) {
48712       SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
48713                                          VT.getSizeInBits());
48714       Extract = DAG.getBitcast(VT, Extract);
48715       return DCI.CombineTo(N, Extract, SDValue(User, 1));
48716     }
48717 
48718   return SDValue();
48719 }
48720 
combineFP_ROUND(SDNode * N,SelectionDAG & DAG,const X86Subtarget & Subtarget)48721 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
48722                                const X86Subtarget &Subtarget) {
48723   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
48724     return SDValue();
48725 
48726   EVT VT = N->getValueType(0);
48727   SDValue Src = N->getOperand(0);
48728   EVT SrcVT = Src.getValueType();
48729 
48730   if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
48731       SrcVT.getVectorElementType() != MVT::f32)
48732     return SDValue();
48733 
48734   unsigned NumElts = VT.getVectorNumElements();
48735   if (NumElts == 1 || !isPowerOf2_32(NumElts))
48736     return SDValue();
48737 
48738   SDLoc dl(N);
48739 
48740   // Widen to at least 4 input elements.
48741   if (NumElts < 4)
48742     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
48743                       DAG.getConstantFP(0.0, dl, SrcVT));
48744 
48745   // Destination is v8i16 with at least 8 elements.
48746   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
48747                                std::max(8U, NumElts));
48748   SDValue Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src,
48749                             DAG.getTargetConstant(4, dl, MVT::i32));
48750 
48751   // Extract down to real number of elements.
48752   if (NumElts < 8) {
48753     EVT IntVT = VT.changeVectorElementTypeToInteger();
48754     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
48755                       DAG.getIntPtrConstant(0, dl));
48756   }
48757 
48758   return DAG.getBitcast(VT, Cvt);
48759 }
48760 
combineMOVDQ2Q(SDNode * N,SelectionDAG & DAG)48761 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
48762   SDValue Src = N->getOperand(0);
48763 
48764   // Turn MOVDQ2Q+simple_load into an mmx load.
48765   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
48766     LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
48767 
48768     if (LN->isSimple()) {
48769       SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
48770                                   LN->getBasePtr(),
48771                                   LN->getPointerInfo(),
48772                                   LN->getOriginalAlign(),
48773                                   LN->getMemOperand()->getFlags());
48774       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
48775       return NewLd;
48776     }
48777   }
48778 
48779   return SDValue();
48780 }
48781 
PerformDAGCombine(SDNode * N,DAGCombinerInfo & DCI) const48782 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
48783                                              DAGCombinerInfo &DCI) const {
48784   SelectionDAG &DAG = DCI.DAG;
48785   switch (N->getOpcode()) {
48786   default: break;
48787   case ISD::SCALAR_TO_VECTOR:
48788     return combineScalarToVector(N, DAG);
48789   case ISD::EXTRACT_VECTOR_ELT:
48790   case X86ISD::PEXTRW:
48791   case X86ISD::PEXTRB:
48792     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
48793   case ISD::CONCAT_VECTORS:
48794     return combineConcatVectors(N, DAG, DCI, Subtarget);
48795   case ISD::INSERT_SUBVECTOR:
48796     return combineInsertSubvector(N, DAG, DCI, Subtarget);
48797   case ISD::EXTRACT_SUBVECTOR:
48798     return combineExtractSubvector(N, DAG, DCI, Subtarget);
48799   case ISD::VSELECT:
48800   case ISD::SELECT:
48801   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
48802   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
48803   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
48804   case X86ISD::CMP:         return combineCMP(N, DAG);
48805   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
48806   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
48807   case X86ISD::ADD:
48808   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
48809   case X86ISD::SBB:         return combineSBB(N, DAG);
48810   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
48811   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
48812   case ISD::SHL:            return combineShiftLeft(N, DAG);
48813   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG, Subtarget);
48814   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI, Subtarget);
48815   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
48816   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
48817   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
48818   case X86ISD::BEXTR:       return combineBEXTR(N, DAG, DCI, Subtarget);
48819   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
48820   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
48821   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
48822   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
48823   case X86ISD::VEXTRACT_STORE:
48824     return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
48825   case ISD::SINT_TO_FP:
48826   case ISD::STRICT_SINT_TO_FP:
48827     return combineSIntToFP(N, DAG, DCI, Subtarget);
48828   case ISD::UINT_TO_FP:
48829   case ISD::STRICT_UINT_TO_FP:
48830     return combineUIntToFP(N, DAG, Subtarget);
48831   case ISD::FADD:
48832   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
48833   case ISD::FNEG:           return combineFneg(N, DAG, DCI, Subtarget);
48834   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
48835   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG, DCI);
48836   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
48837   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
48838   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
48839   case X86ISD::FXOR:
48840   case X86ISD::FOR:         return combineFOr(N, DAG, DCI, Subtarget);
48841   case X86ISD::FMIN:
48842   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
48843   case ISD::FMINNUM:
48844   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
48845   case X86ISD::CVTSI2P:
48846   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
48847   case X86ISD::CVTP2SI:
48848   case X86ISD::CVTP2UI:
48849   case X86ISD::STRICT_CVTTP2SI:
48850   case X86ISD::CVTTP2SI:
48851   case X86ISD::STRICT_CVTTP2UI:
48852   case X86ISD::CVTTP2UI:
48853                             return combineCVTP2I_CVTTP2I(N, DAG, DCI);
48854   case X86ISD::STRICT_CVTPH2PS:
48855   case X86ISD::CVTPH2PS:    return combineCVTPH2PS(N, DAG, DCI);
48856   case X86ISD::BT:          return combineBT(N, DAG, DCI);
48857   case ISD::ANY_EXTEND:
48858   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
48859   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
48860   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
48861   case ISD::ANY_EXTEND_VECTOR_INREG:
48862   case ISD::SIGN_EXTEND_VECTOR_INREG:
48863   case ISD::ZERO_EXTEND_VECTOR_INREG: return combineExtInVec(N, DAG, DCI,
48864                                                              Subtarget);
48865   case ISD::SETCC:          return combineSetCC(N, DAG, Subtarget);
48866   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
48867   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
48868   case X86ISD::PACKSS:
48869   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
48870   case X86ISD::VSHL:
48871   case X86ISD::VSRA:
48872   case X86ISD::VSRL:
48873     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
48874   case X86ISD::VSHLI:
48875   case X86ISD::VSRAI:
48876   case X86ISD::VSRLI:
48877     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
48878   case ISD::INSERT_VECTOR_ELT:
48879   case X86ISD::PINSRB:
48880   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
48881   case X86ISD::SHUFP:       // Handle all target specific shuffles
48882   case X86ISD::INSERTPS:
48883   case X86ISD::EXTRQI:
48884   case X86ISD::INSERTQI:
48885   case X86ISD::VALIGN:
48886   case X86ISD::PALIGNR:
48887   case X86ISD::VSHLDQ:
48888   case X86ISD::VSRLDQ:
48889   case X86ISD::BLENDI:
48890   case X86ISD::UNPCKH:
48891   case X86ISD::UNPCKL:
48892   case X86ISD::MOVHLPS:
48893   case X86ISD::MOVLHPS:
48894   case X86ISD::PSHUFB:
48895   case X86ISD::PSHUFD:
48896   case X86ISD::PSHUFHW:
48897   case X86ISD::PSHUFLW:
48898   case X86ISD::MOVSHDUP:
48899   case X86ISD::MOVSLDUP:
48900   case X86ISD::MOVDDUP:
48901   case X86ISD::MOVSS:
48902   case X86ISD::MOVSD:
48903   case X86ISD::VBROADCAST:
48904   case X86ISD::VPPERM:
48905   case X86ISD::VPERMI:
48906   case X86ISD::VPERMV:
48907   case X86ISD::VPERMV3:
48908   case X86ISD::VPERMIL2:
48909   case X86ISD::VPERMILPI:
48910   case X86ISD::VPERMILPV:
48911   case X86ISD::VPERM2X128:
48912   case X86ISD::SHUF128:
48913   case X86ISD::VZEXT_MOVL:
48914   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
48915   case X86ISD::FMADD_RND:
48916   case X86ISD::FMSUB:
48917   case X86ISD::STRICT_FMSUB:
48918   case X86ISD::FMSUB_RND:
48919   case X86ISD::FNMADD:
48920   case X86ISD::STRICT_FNMADD:
48921   case X86ISD::FNMADD_RND:
48922   case X86ISD::FNMSUB:
48923   case X86ISD::STRICT_FNMSUB:
48924   case X86ISD::FNMSUB_RND:
48925   case ISD::FMA:
48926   case ISD::STRICT_FMA:     return combineFMA(N, DAG, DCI, Subtarget);
48927   case X86ISD::FMADDSUB_RND:
48928   case X86ISD::FMSUBADD_RND:
48929   case X86ISD::FMADDSUB:
48930   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
48931   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
48932   case X86ISD::MGATHER:
48933   case X86ISD::MSCATTER:    return combineX86GatherScatter(N, DAG, DCI);
48934   case ISD::MGATHER:
48935   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
48936   case X86ISD::PCMPEQ:
48937   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
48938   case X86ISD::PMULDQ:
48939   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
48940   case X86ISD::KSHIFTL:
48941   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
48942   case ISD::FP16_TO_FP:     return combineFP16_TO_FP(N, DAG, Subtarget);
48943   case ISD::STRICT_FP_EXTEND:
48944   case ISD::FP_EXTEND:      return combineFP_EXTEND(N, DAG, Subtarget);
48945   case ISD::FP_ROUND:       return combineFP_ROUND(N, DAG, Subtarget);
48946   case X86ISD::VBROADCAST_LOAD: return combineVBROADCAST_LOAD(N, DAG, DCI);
48947   case X86ISD::MOVDQ2Q:     return combineMOVDQ2Q(N, DAG);
48948   }
48949 
48950   return SDValue();
48951 }
48952 
isTypeDesirableForOp(unsigned Opc,EVT VT) const48953 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
48954   if (!isTypeLegal(VT))
48955     return false;
48956 
48957   // There are no vXi8 shifts.
48958   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
48959     return false;
48960 
48961   // TODO: Almost no 8-bit ops are desirable because they have no actual
48962   //       size/speed advantages vs. 32-bit ops, but they do have a major
48963   //       potential disadvantage by causing partial register stalls.
48964   //
48965   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
48966   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
48967   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
48968   // check for a constant operand to the multiply.
48969   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
48970     return false;
48971 
48972   // i16 instruction encodings are longer and some i16 instructions are slow,
48973   // so those are not desirable.
48974   if (VT == MVT::i16) {
48975     switch (Opc) {
48976     default:
48977       break;
48978     case ISD::LOAD:
48979     case ISD::SIGN_EXTEND:
48980     case ISD::ZERO_EXTEND:
48981     case ISD::ANY_EXTEND:
48982     case ISD::SHL:
48983     case ISD::SRA:
48984     case ISD::SRL:
48985     case ISD::SUB:
48986     case ISD::ADD:
48987     case ISD::MUL:
48988     case ISD::AND:
48989     case ISD::OR:
48990     case ISD::XOR:
48991       return false;
48992     }
48993   }
48994 
48995   // Any legal type not explicitly accounted for above here is desirable.
48996   return true;
48997 }
48998 
expandIndirectJTBranch(const SDLoc & dl,SDValue Value,SDValue Addr,SelectionDAG & DAG) const48999 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
49000                                                   SDValue Value, SDValue Addr,
49001                                                   SelectionDAG &DAG) const {
49002   const Module *M = DAG.getMachineFunction().getMMI().getModule();
49003   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
49004   if (IsCFProtectionSupported) {
49005     // In case control-flow branch protection is enabled, we need to add
49006     // notrack prefix to the indirect branch.
49007     // In order to do that we create NT_BRIND SDNode.
49008     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
49009     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
49010   }
49011 
49012   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
49013 }
49014 
IsDesirableToPromoteOp(SDValue Op,EVT & PVT) const49015 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
49016   EVT VT = Op.getValueType();
49017   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
49018                              isa<ConstantSDNode>(Op.getOperand(1));
49019 
49020   // i16 is legal, but undesirable since i16 instruction encodings are longer
49021   // and some i16 instructions are slow.
49022   // 8-bit multiply-by-constant can usually be expanded to something cheaper
49023   // using LEA and/or other ALU ops.
49024   if (VT != MVT::i16 && !Is8BitMulByConstant)
49025     return false;
49026 
49027   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
49028     if (!Op.hasOneUse())
49029       return false;
49030     SDNode *User = *Op->use_begin();
49031     if (!ISD::isNormalStore(User))
49032       return false;
49033     auto *Ld = cast<LoadSDNode>(Load);
49034     auto *St = cast<StoreSDNode>(User);
49035     return Ld->getBasePtr() == St->getBasePtr();
49036   };
49037 
49038   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
49039     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
49040       return false;
49041     if (!Op.hasOneUse())
49042       return false;
49043     SDNode *User = *Op->use_begin();
49044     if (User->getOpcode() != ISD::ATOMIC_STORE)
49045       return false;
49046     auto *Ld = cast<AtomicSDNode>(Load);
49047     auto *St = cast<AtomicSDNode>(User);
49048     return Ld->getBasePtr() == St->getBasePtr();
49049   };
49050 
49051   bool Commute = false;
49052   switch (Op.getOpcode()) {
49053   default: return false;
49054   case ISD::SIGN_EXTEND:
49055   case ISD::ZERO_EXTEND:
49056   case ISD::ANY_EXTEND:
49057     break;
49058   case ISD::SHL:
49059   case ISD::SRA:
49060   case ISD::SRL: {
49061     SDValue N0 = Op.getOperand(0);
49062     // Look out for (store (shl (load), x)).
49063     if (MayFoldLoad(N0) && IsFoldableRMW(N0, Op))
49064       return false;
49065     break;
49066   }
49067   case ISD::ADD:
49068   case ISD::MUL:
49069   case ISD::AND:
49070   case ISD::OR:
49071   case ISD::XOR:
49072     Commute = true;
49073     LLVM_FALLTHROUGH;
49074   case ISD::SUB: {
49075     SDValue N0 = Op.getOperand(0);
49076     SDValue N1 = Op.getOperand(1);
49077     // Avoid disabling potential load folding opportunities.
49078     if (MayFoldLoad(N1) &&
49079         (!Commute || !isa<ConstantSDNode>(N0) ||
49080          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
49081       return false;
49082     if (MayFoldLoad(N0) &&
49083         ((Commute && !isa<ConstantSDNode>(N1)) ||
49084          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
49085       return false;
49086     if (IsFoldableAtomicRMW(N0, Op) ||
49087         (Commute && IsFoldableAtomicRMW(N1, Op)))
49088       return false;
49089   }
49090   }
49091 
49092   PVT = MVT::i32;
49093   return true;
49094 }
49095 
49096 //===----------------------------------------------------------------------===//
49097 //                           X86 Inline Assembly Support
49098 //===----------------------------------------------------------------------===//
49099 
49100 // Helper to match a string separated by whitespace.
matchAsm(StringRef S,ArrayRef<const char * > Pieces)49101 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
49102   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
49103 
49104   for (StringRef Piece : Pieces) {
49105     if (!S.startswith(Piece)) // Check if the piece matches.
49106       return false;
49107 
49108     S = S.substr(Piece.size());
49109     StringRef::size_type Pos = S.find_first_not_of(" \t");
49110     if (Pos == 0) // We matched a prefix.
49111       return false;
49112 
49113     S = S.substr(Pos);
49114   }
49115 
49116   return S.empty();
49117 }
49118 
clobbersFlagRegisters(const SmallVector<StringRef,4> & AsmPieces)49119 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
49120 
49121   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
49122     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
49123         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
49124         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
49125 
49126       if (AsmPieces.size() == 3)
49127         return true;
49128       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
49129         return true;
49130     }
49131   }
49132   return false;
49133 }
49134 
ExpandInlineAsm(CallInst * CI) const49135 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
49136   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
49137 
49138   const std::string &AsmStr = IA->getAsmString();
49139 
49140   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
49141   if (!Ty || Ty->getBitWidth() % 16 != 0)
49142     return false;
49143 
49144   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
49145   SmallVector<StringRef, 4> AsmPieces;
49146   SplitString(AsmStr, AsmPieces, ";\n");
49147 
49148   switch (AsmPieces.size()) {
49149   default: return false;
49150   case 1:
49151     // FIXME: this should verify that we are targeting a 486 or better.  If not,
49152     // we will turn this bswap into something that will be lowered to logical
49153     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
49154     // lower so don't worry about this.
49155     // bswap $0
49156     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
49157         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
49158         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
49159         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
49160         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
49161         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
49162       // No need to check constraints, nothing other than the equivalent of
49163       // "=r,0" would be valid here.
49164       return IntrinsicLowering::LowerToByteSwap(CI);
49165     }
49166 
49167     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
49168     if (CI->getType()->isIntegerTy(16) &&
49169         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
49170         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
49171          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
49172       AsmPieces.clear();
49173       StringRef ConstraintsStr = IA->getConstraintString();
49174       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
49175       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
49176       if (clobbersFlagRegisters(AsmPieces))
49177         return IntrinsicLowering::LowerToByteSwap(CI);
49178     }
49179     break;
49180   case 3:
49181     if (CI->getType()->isIntegerTy(32) &&
49182         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
49183         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
49184         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
49185         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
49186       AsmPieces.clear();
49187       StringRef ConstraintsStr = IA->getConstraintString();
49188       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
49189       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
49190       if (clobbersFlagRegisters(AsmPieces))
49191         return IntrinsicLowering::LowerToByteSwap(CI);
49192     }
49193 
49194     if (CI->getType()->isIntegerTy(64)) {
49195       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
49196       if (Constraints.size() >= 2 &&
49197           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
49198           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
49199         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
49200         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
49201             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
49202             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
49203           return IntrinsicLowering::LowerToByteSwap(CI);
49204       }
49205     }
49206     break;
49207   }
49208   return false;
49209 }
49210 
parseConstraintCode(llvm::StringRef Constraint)49211 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
49212   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
49213                            .Case("{@cca}", X86::COND_A)
49214                            .Case("{@ccae}", X86::COND_AE)
49215                            .Case("{@ccb}", X86::COND_B)
49216                            .Case("{@ccbe}", X86::COND_BE)
49217                            .Case("{@ccc}", X86::COND_B)
49218                            .Case("{@cce}", X86::COND_E)
49219                            .Case("{@ccz}", X86::COND_E)
49220                            .Case("{@ccg}", X86::COND_G)
49221                            .Case("{@ccge}", X86::COND_GE)
49222                            .Case("{@ccl}", X86::COND_L)
49223                            .Case("{@ccle}", X86::COND_LE)
49224                            .Case("{@ccna}", X86::COND_BE)
49225                            .Case("{@ccnae}", X86::COND_B)
49226                            .Case("{@ccnb}", X86::COND_AE)
49227                            .Case("{@ccnbe}", X86::COND_A)
49228                            .Case("{@ccnc}", X86::COND_AE)
49229                            .Case("{@ccne}", X86::COND_NE)
49230                            .Case("{@ccnz}", X86::COND_NE)
49231                            .Case("{@ccng}", X86::COND_LE)
49232                            .Case("{@ccnge}", X86::COND_L)
49233                            .Case("{@ccnl}", X86::COND_GE)
49234                            .Case("{@ccnle}", X86::COND_G)
49235                            .Case("{@ccno}", X86::COND_NO)
49236                            .Case("{@ccnp}", X86::COND_P)
49237                            .Case("{@ccns}", X86::COND_NS)
49238                            .Case("{@cco}", X86::COND_O)
49239                            .Case("{@ccp}", X86::COND_P)
49240                            .Case("{@ccs}", X86::COND_S)
49241                            .Default(X86::COND_INVALID);
49242   return Cond;
49243 }
49244 
49245 /// Given a constraint letter, return the type of constraint for this target.
49246 X86TargetLowering::ConstraintType
getConstraintType(StringRef Constraint) const49247 X86TargetLowering::getConstraintType(StringRef Constraint) const {
49248   if (Constraint.size() == 1) {
49249     switch (Constraint[0]) {
49250     case 'R':
49251     case 'q':
49252     case 'Q':
49253     case 'f':
49254     case 't':
49255     case 'u':
49256     case 'y':
49257     case 'x':
49258     case 'v':
49259     case 'l':
49260     case 'k': // AVX512 masking registers.
49261       return C_RegisterClass;
49262     case 'a':
49263     case 'b':
49264     case 'c':
49265     case 'd':
49266     case 'S':
49267     case 'D':
49268     case 'A':
49269       return C_Register;
49270     case 'I':
49271     case 'J':
49272     case 'K':
49273     case 'N':
49274     case 'G':
49275     case 'L':
49276     case 'M':
49277       return C_Immediate;
49278     case 'C':
49279     case 'e':
49280     case 'Z':
49281       return C_Other;
49282     default:
49283       break;
49284     }
49285   }
49286   else if (Constraint.size() == 2) {
49287     switch (Constraint[0]) {
49288     default:
49289       break;
49290     case 'Y':
49291       switch (Constraint[1]) {
49292       default:
49293         break;
49294       case 'z':
49295         return C_Register;
49296       case 'i':
49297       case 'm':
49298       case 'k':
49299       case 't':
49300       case '2':
49301         return C_RegisterClass;
49302       }
49303     }
49304   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
49305     return C_Other;
49306   return TargetLowering::getConstraintType(Constraint);
49307 }
49308 
49309 /// Examine constraint type and operand type and determine a weight value.
49310 /// This object must already have been set up with the operand type
49311 /// and the current alternative constraint selected.
49312 TargetLowering::ConstraintWeight
getSingleConstraintMatchWeight(AsmOperandInfo & info,const char * constraint) const49313   X86TargetLowering::getSingleConstraintMatchWeight(
49314     AsmOperandInfo &info, const char *constraint) const {
49315   ConstraintWeight weight = CW_Invalid;
49316   Value *CallOperandVal = info.CallOperandVal;
49317     // If we don't have a value, we can't do a match,
49318     // but allow it at the lowest weight.
49319   if (!CallOperandVal)
49320     return CW_Default;
49321   Type *type = CallOperandVal->getType();
49322   // Look at the constraint type.
49323   switch (*constraint) {
49324   default:
49325     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
49326     LLVM_FALLTHROUGH;
49327   case 'R':
49328   case 'q':
49329   case 'Q':
49330   case 'a':
49331   case 'b':
49332   case 'c':
49333   case 'd':
49334   case 'S':
49335   case 'D':
49336   case 'A':
49337     if (CallOperandVal->getType()->isIntegerTy())
49338       weight = CW_SpecificReg;
49339     break;
49340   case 'f':
49341   case 't':
49342   case 'u':
49343     if (type->isFloatingPointTy())
49344       weight = CW_SpecificReg;
49345     break;
49346   case 'y':
49347     if (type->isX86_MMXTy() && Subtarget.hasMMX())
49348       weight = CW_SpecificReg;
49349     break;
49350   case 'Y':
49351     if (StringRef(constraint).size() != 2)
49352       break;
49353     switch (constraint[1]) {
49354       default:
49355         return CW_Invalid;
49356       // XMM0
49357       case 'z':
49358         if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
49359             ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
49360             ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
49361           return CW_SpecificReg;
49362         return CW_Invalid;
49363       // Conditional OpMask regs (AVX512)
49364       case 'k':
49365         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
49366           return CW_Register;
49367         return CW_Invalid;
49368       // Any MMX reg
49369       case 'm':
49370         if (type->isX86_MMXTy() && Subtarget.hasMMX())
49371           return weight;
49372         return CW_Invalid;
49373       // Any SSE reg when ISA >= SSE2, same as 'x'
49374       case 'i':
49375       case 't':
49376       case '2':
49377         if (!Subtarget.hasSSE2())
49378           return CW_Invalid;
49379         break;
49380     }
49381     break;
49382   case 'v':
49383     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
49384       weight = CW_Register;
49385     LLVM_FALLTHROUGH;
49386   case 'x':
49387     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
49388         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
49389       weight = CW_Register;
49390     break;
49391   case 'k':
49392     // Enable conditional vector operations using %k<#> registers.
49393     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
49394       weight = CW_Register;
49395     break;
49396   case 'I':
49397     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
49398       if (C->getZExtValue() <= 31)
49399         weight = CW_Constant;
49400     }
49401     break;
49402   case 'J':
49403     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49404       if (C->getZExtValue() <= 63)
49405         weight = CW_Constant;
49406     }
49407     break;
49408   case 'K':
49409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49410       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
49411         weight = CW_Constant;
49412     }
49413     break;
49414   case 'L':
49415     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49416       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
49417         weight = CW_Constant;
49418     }
49419     break;
49420   case 'M':
49421     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49422       if (C->getZExtValue() <= 3)
49423         weight = CW_Constant;
49424     }
49425     break;
49426   case 'N':
49427     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49428       if (C->getZExtValue() <= 0xff)
49429         weight = CW_Constant;
49430     }
49431     break;
49432   case 'G':
49433   case 'C':
49434     if (isa<ConstantFP>(CallOperandVal)) {
49435       weight = CW_Constant;
49436     }
49437     break;
49438   case 'e':
49439     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49440       if ((C->getSExtValue() >= -0x80000000LL) &&
49441           (C->getSExtValue() <= 0x7fffffffLL))
49442         weight = CW_Constant;
49443     }
49444     break;
49445   case 'Z':
49446     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
49447       if (C->getZExtValue() <= 0xffffffff)
49448         weight = CW_Constant;
49449     }
49450     break;
49451   }
49452   return weight;
49453 }
49454 
49455 /// Try to replace an X constraint, which matches anything, with another that
49456 /// has more specific requirements based on the type of the corresponding
49457 /// operand.
49458 const char *X86TargetLowering::
LowerXConstraint(EVT ConstraintVT) const49459 LowerXConstraint(EVT ConstraintVT) const {
49460   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
49461   // 'f' like normal targets.
49462   if (ConstraintVT.isFloatingPoint()) {
49463     if (Subtarget.hasSSE1())
49464       return "x";
49465   }
49466 
49467   return TargetLowering::LowerXConstraint(ConstraintVT);
49468 }
49469 
49470 // Lower @cc targets via setcc.
LowerAsmOutputForConstraint(SDValue & Chain,SDValue & Flag,SDLoc DL,const AsmOperandInfo & OpInfo,SelectionDAG & DAG) const49471 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
49472     SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
49473     SelectionDAG &DAG) const {
49474   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
49475   if (Cond == X86::COND_INVALID)
49476     return SDValue();
49477   // Check that return type is valid.
49478   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
49479       OpInfo.ConstraintVT.getSizeInBits() < 8)
49480     report_fatal_error("Flag output operand is of invalid type");
49481 
49482   // Get EFLAGS register. Only update chain when copyfrom is glued.
49483   if (Flag.getNode()) {
49484     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
49485     Chain = Flag.getValue(1);
49486   } else
49487     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
49488   // Extract CC code.
49489   SDValue CC = getSETCC(Cond, Flag, DL, DAG);
49490   // Extend to 32-bits
49491   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
49492 
49493   return Result;
49494 }
49495 
49496 /// Lower the specified operand into the Ops vector.
49497 /// If it is invalid, don't add anything to Ops.
LowerAsmOperandForConstraint(SDValue Op,std::string & Constraint,std::vector<SDValue> & Ops,SelectionDAG & DAG) const49498 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
49499                                                      std::string &Constraint,
49500                                                      std::vector<SDValue>&Ops,
49501                                                      SelectionDAG &DAG) const {
49502   SDValue Result;
49503 
49504   // Only support length 1 constraints for now.
49505   if (Constraint.length() > 1) return;
49506 
49507   char ConstraintLetter = Constraint[0];
49508   switch (ConstraintLetter) {
49509   default: break;
49510   case 'I':
49511     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49512       if (C->getZExtValue() <= 31) {
49513         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49514                                        Op.getValueType());
49515         break;
49516       }
49517     }
49518     return;
49519   case 'J':
49520     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49521       if (C->getZExtValue() <= 63) {
49522         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49523                                        Op.getValueType());
49524         break;
49525       }
49526     }
49527     return;
49528   case 'K':
49529     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49530       if (isInt<8>(C->getSExtValue())) {
49531         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49532                                        Op.getValueType());
49533         break;
49534       }
49535     }
49536     return;
49537   case 'L':
49538     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49539       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
49540           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
49541         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
49542                                        Op.getValueType());
49543         break;
49544       }
49545     }
49546     return;
49547   case 'M':
49548     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49549       if (C->getZExtValue() <= 3) {
49550         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49551                                        Op.getValueType());
49552         break;
49553       }
49554     }
49555     return;
49556   case 'N':
49557     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49558       if (C->getZExtValue() <= 255) {
49559         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49560                                        Op.getValueType());
49561         break;
49562       }
49563     }
49564     return;
49565   case 'O':
49566     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49567       if (C->getZExtValue() <= 127) {
49568         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49569                                        Op.getValueType());
49570         break;
49571       }
49572     }
49573     return;
49574   case 'e': {
49575     // 32-bit signed value
49576     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49577       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
49578                                            C->getSExtValue())) {
49579         // Widen to 64 bits here to get it sign extended.
49580         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
49581         break;
49582       }
49583     // FIXME gcc accepts some relocatable values here too, but only in certain
49584     // memory models; it's complicated.
49585     }
49586     return;
49587   }
49588   case 'Z': {
49589     // 32-bit unsigned value
49590     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
49591       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
49592                                            C->getZExtValue())) {
49593         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
49594                                        Op.getValueType());
49595         break;
49596       }
49597     }
49598     // FIXME gcc accepts some relocatable values here too, but only in certain
49599     // memory models; it's complicated.
49600     return;
49601   }
49602   case 'i': {
49603     // Literal immediates are always ok.
49604     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
49605       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
49606       BooleanContent BCont = getBooleanContents(MVT::i64);
49607       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
49608                                     : ISD::SIGN_EXTEND;
49609       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
49610                                                   : CST->getSExtValue();
49611       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
49612       break;
49613     }
49614 
49615     // In any sort of PIC mode addresses need to be computed at runtime by
49616     // adding in a register or some sort of table lookup.  These can't
49617     // be used as immediates.
49618     if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
49619       return;
49620 
49621     // If we are in non-pic codegen mode, we allow the address of a global (with
49622     // an optional displacement) to be used with 'i'.
49623     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
49624       // If we require an extra load to get this address, as in PIC mode, we
49625       // can't accept it.
49626       if (isGlobalStubReference(
49627               Subtarget.classifyGlobalReference(GA->getGlobal())))
49628         return;
49629     break;
49630   }
49631   }
49632 
49633   if (Result.getNode()) {
49634     Ops.push_back(Result);
49635     return;
49636   }
49637   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
49638 }
49639 
49640 /// Check if \p RC is a general purpose register class.
49641 /// I.e., GR* or one of their variant.
isGRClass(const TargetRegisterClass & RC)49642 static bool isGRClass(const TargetRegisterClass &RC) {
49643   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
49644          RC.hasSuperClassEq(&X86::GR16RegClass) ||
49645          RC.hasSuperClassEq(&X86::GR32RegClass) ||
49646          RC.hasSuperClassEq(&X86::GR64RegClass) ||
49647          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
49648 }
49649 
49650 /// Check if \p RC is a vector register class.
49651 /// I.e., FR* / VR* or one of their variant.
isFRClass(const TargetRegisterClass & RC)49652 static bool isFRClass(const TargetRegisterClass &RC) {
49653   return RC.hasSuperClassEq(&X86::FR32XRegClass) ||
49654          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
49655          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
49656          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
49657          RC.hasSuperClassEq(&X86::VR512RegClass);
49658 }
49659 
49660 /// Check if \p RC is a mask register class.
49661 /// I.e., VK* or one of their variant.
isVKClass(const TargetRegisterClass & RC)49662 static bool isVKClass(const TargetRegisterClass &RC) {
49663   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
49664          RC.hasSuperClassEq(&X86::VK2RegClass) ||
49665          RC.hasSuperClassEq(&X86::VK4RegClass) ||
49666          RC.hasSuperClassEq(&X86::VK8RegClass) ||
49667          RC.hasSuperClassEq(&X86::VK16RegClass) ||
49668          RC.hasSuperClassEq(&X86::VK32RegClass) ||
49669          RC.hasSuperClassEq(&X86::VK64RegClass);
49670 }
49671 
49672 std::pair<unsigned, const TargetRegisterClass *>
getRegForInlineAsmConstraint(const TargetRegisterInfo * TRI,StringRef Constraint,MVT VT) const49673 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
49674                                                 StringRef Constraint,
49675                                                 MVT VT) const {
49676   // First, see if this is a constraint that directly corresponds to an LLVM
49677   // register class.
49678   if (Constraint.size() == 1) {
49679     // GCC Constraint Letters
49680     switch (Constraint[0]) {
49681     default: break;
49682     // 'A' means [ER]AX + [ER]DX.
49683     case 'A':
49684       if (Subtarget.is64Bit())
49685         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
49686       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
49687              "Expecting 64, 32 or 16 bit subtarget");
49688       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
49689 
49690       // TODO: Slight differences here in allocation order and leaving
49691       // RIP in the class. Do they matter any more here than they do
49692       // in the normal allocation?
49693     case 'k':
49694       if (Subtarget.hasAVX512()) {
49695         if (VT == MVT::i1)
49696           return std::make_pair(0U, &X86::VK1RegClass);
49697         if (VT == MVT::i8)
49698           return std::make_pair(0U, &X86::VK8RegClass);
49699         if (VT == MVT::i16)
49700           return std::make_pair(0U, &X86::VK16RegClass);
49701       }
49702       if (Subtarget.hasBWI()) {
49703         if (VT == MVT::i32)
49704           return std::make_pair(0U, &X86::VK32RegClass);
49705         if (VT == MVT::i64)
49706           return std::make_pair(0U, &X86::VK64RegClass);
49707       }
49708       break;
49709     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
49710       if (Subtarget.is64Bit()) {
49711         if (VT == MVT::i8 || VT == MVT::i1)
49712           return std::make_pair(0U, &X86::GR8RegClass);
49713         if (VT == MVT::i16)
49714           return std::make_pair(0U, &X86::GR16RegClass);
49715         if (VT == MVT::i32 || VT == MVT::f32)
49716           return std::make_pair(0U, &X86::GR32RegClass);
49717         if (VT != MVT::f80)
49718           return std::make_pair(0U, &X86::GR64RegClass);
49719         break;
49720       }
49721       LLVM_FALLTHROUGH;
49722       // 32-bit fallthrough
49723     case 'Q':   // Q_REGS
49724       if (VT == MVT::i8 || VT == MVT::i1)
49725         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
49726       if (VT == MVT::i16)
49727         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
49728       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
49729         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
49730       if (VT != MVT::f80)
49731         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
49732       break;
49733     case 'r':   // GENERAL_REGS
49734     case 'l':   // INDEX_REGS
49735       if (VT == MVT::i8 || VT == MVT::i1)
49736         return std::make_pair(0U, &X86::GR8RegClass);
49737       if (VT == MVT::i16)
49738         return std::make_pair(0U, &X86::GR16RegClass);
49739       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
49740         return std::make_pair(0U, &X86::GR32RegClass);
49741       if (VT != MVT::f80)
49742         return std::make_pair(0U, &X86::GR64RegClass);
49743       break;
49744     case 'R':   // LEGACY_REGS
49745       if (VT == MVT::i8 || VT == MVT::i1)
49746         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
49747       if (VT == MVT::i16)
49748         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
49749       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
49750         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
49751       if (VT != MVT::f80)
49752         return std::make_pair(0U, &X86::GR64_NOREXRegClass);
49753       break;
49754     case 'f':  // FP Stack registers.
49755       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
49756       // value to the correct fpstack register class.
49757       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
49758         return std::make_pair(0U, &X86::RFP32RegClass);
49759       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
49760         return std::make_pair(0U, &X86::RFP64RegClass);
49761       if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
49762         return std::make_pair(0U, &X86::RFP80RegClass);
49763       break;
49764     case 'y':   // MMX_REGS if MMX allowed.
49765       if (!Subtarget.hasMMX()) break;
49766       return std::make_pair(0U, &X86::VR64RegClass);
49767     case 'v':
49768     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
49769       if (!Subtarget.hasSSE1()) break;
49770       bool VConstraint = (Constraint[0] == 'v');
49771 
49772       switch (VT.SimpleTy) {
49773       default: break;
49774       // Scalar SSE types.
49775       case MVT::f32:
49776       case MVT::i32:
49777         if (VConstraint && Subtarget.hasVLX())
49778           return std::make_pair(0U, &X86::FR32XRegClass);
49779         return std::make_pair(0U, &X86::FR32RegClass);
49780       case MVT::f64:
49781       case MVT::i64:
49782         if (VConstraint && Subtarget.hasVLX())
49783           return std::make_pair(0U, &X86::FR64XRegClass);
49784         return std::make_pair(0U, &X86::FR64RegClass);
49785       case MVT::i128:
49786         if (Subtarget.is64Bit()) {
49787           if (VConstraint && Subtarget.hasVLX())
49788             return std::make_pair(0U, &X86::VR128XRegClass);
49789           return std::make_pair(0U, &X86::VR128RegClass);
49790         }
49791         break;
49792       // Vector types and fp128.
49793       case MVT::f128:
49794       case MVT::v16i8:
49795       case MVT::v8i16:
49796       case MVT::v4i32:
49797       case MVT::v2i64:
49798       case MVT::v4f32:
49799       case MVT::v2f64:
49800         if (VConstraint && Subtarget.hasVLX())
49801           return std::make_pair(0U, &X86::VR128XRegClass);
49802         return std::make_pair(0U, &X86::VR128RegClass);
49803       // AVX types.
49804       case MVT::v32i8:
49805       case MVT::v16i16:
49806       case MVT::v8i32:
49807       case MVT::v4i64:
49808       case MVT::v8f32:
49809       case MVT::v4f64:
49810         if (VConstraint && Subtarget.hasVLX())
49811           return std::make_pair(0U, &X86::VR256XRegClass);
49812         if (Subtarget.hasAVX())
49813           return std::make_pair(0U, &X86::VR256RegClass);
49814         break;
49815       case MVT::v64i8:
49816       case MVT::v32i16:
49817       case MVT::v8f64:
49818       case MVT::v16f32:
49819       case MVT::v16i32:
49820       case MVT::v8i64:
49821         if (!Subtarget.hasAVX512()) break;
49822         if (VConstraint)
49823           return std::make_pair(0U, &X86::VR512RegClass);
49824         return std::make_pair(0U, &X86::VR512_0_15RegClass);
49825       }
49826       break;
49827     }
49828   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
49829     switch (Constraint[1]) {
49830     default:
49831       break;
49832     case 'i':
49833     case 't':
49834     case '2':
49835       return getRegForInlineAsmConstraint(TRI, "x", VT);
49836     case 'm':
49837       if (!Subtarget.hasMMX()) break;
49838       return std::make_pair(0U, &X86::VR64RegClass);
49839     case 'z':
49840       if (!Subtarget.hasSSE1()) break;
49841       switch (VT.SimpleTy) {
49842       default: break;
49843       // Scalar SSE types.
49844       case MVT::f32:
49845       case MVT::i32:
49846         return std::make_pair(X86::XMM0, &X86::FR32RegClass);
49847       case MVT::f64:
49848       case MVT::i64:
49849         return std::make_pair(X86::XMM0, &X86::FR64RegClass);
49850       case MVT::f128:
49851       case MVT::v16i8:
49852       case MVT::v8i16:
49853       case MVT::v4i32:
49854       case MVT::v2i64:
49855       case MVT::v4f32:
49856       case MVT::v2f64:
49857         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
49858       // AVX types.
49859       case MVT::v32i8:
49860       case MVT::v16i16:
49861       case MVT::v8i32:
49862       case MVT::v4i64:
49863       case MVT::v8f32:
49864       case MVT::v4f64:
49865         if (Subtarget.hasAVX())
49866           return std::make_pair(X86::YMM0, &X86::VR256RegClass);
49867         break;
49868       case MVT::v64i8:
49869       case MVT::v32i16:
49870       case MVT::v8f64:
49871       case MVT::v16f32:
49872       case MVT::v16i32:
49873       case MVT::v8i64:
49874         if (Subtarget.hasAVX512())
49875           return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
49876         break;
49877       }
49878       break;
49879     case 'k':
49880       // This register class doesn't allocate k0 for masked vector operation.
49881       if (Subtarget.hasAVX512()) {
49882         if (VT == MVT::i1)
49883           return std::make_pair(0U, &X86::VK1WMRegClass);
49884         if (VT == MVT::i8)
49885           return std::make_pair(0U, &X86::VK8WMRegClass);
49886         if (VT == MVT::i16)
49887           return std::make_pair(0U, &X86::VK16WMRegClass);
49888       }
49889       if (Subtarget.hasBWI()) {
49890         if (VT == MVT::i32)
49891           return std::make_pair(0U, &X86::VK32WMRegClass);
49892         if (VT == MVT::i64)
49893           return std::make_pair(0U, &X86::VK64WMRegClass);
49894       }
49895       break;
49896     }
49897   }
49898 
49899   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
49900     return std::make_pair(0U, &X86::GR32RegClass);
49901 
49902   // Use the default implementation in TargetLowering to convert the register
49903   // constraint into a member of a register class.
49904   std::pair<Register, const TargetRegisterClass*> Res;
49905   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
49906 
49907   // Not found as a standard register?
49908   if (!Res.second) {
49909     // Map st(0) -> st(7) -> ST0
49910     if (Constraint.size() == 7 && Constraint[0] == '{' &&
49911         tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
49912         Constraint[3] == '(' &&
49913         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
49914         Constraint[5] == ')' && Constraint[6] == '}') {
49915       // st(7) is not allocatable and thus not a member of RFP80. Return
49916       // singleton class in cases where we have a reference to it.
49917       if (Constraint[4] == '7')
49918         return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
49919       return std::make_pair(X86::FP0 + Constraint[4] - '0',
49920                             &X86::RFP80RegClass);
49921     }
49922 
49923     // GCC allows "st(0)" to be called just plain "st".
49924     if (StringRef("{st}").equals_lower(Constraint))
49925       return std::make_pair(X86::FP0, &X86::RFP80RegClass);
49926 
49927     // flags -> EFLAGS
49928     if (StringRef("{flags}").equals_lower(Constraint))
49929       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
49930 
49931     // dirflag -> DF
49932     if (StringRef("{dirflag}").equals_lower(Constraint))
49933       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
49934 
49935     // fpsr -> FPSW
49936     if (StringRef("{fpsr}").equals_lower(Constraint))
49937       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
49938 
49939     return Res;
49940   }
49941 
49942   // Make sure it isn't a register that requires 64-bit mode.
49943   if (!Subtarget.is64Bit() &&
49944       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
49945       TRI->getEncodingValue(Res.first) >= 8) {
49946     // Register requires REX prefix, but we're in 32-bit mode.
49947     return std::make_pair(0, nullptr);
49948   }
49949 
49950   // Make sure it isn't a register that requires AVX512.
49951   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
49952       TRI->getEncodingValue(Res.first) & 0x10) {
49953     // Register requires EVEX prefix.
49954     return std::make_pair(0, nullptr);
49955   }
49956 
49957   // Otherwise, check to see if this is a register class of the wrong value
49958   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
49959   // turn into {ax},{dx}.
49960   // MVT::Other is used to specify clobber names.
49961   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
49962     return Res;   // Correct type already, nothing to do.
49963 
49964   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
49965   // return "eax". This should even work for things like getting 64bit integer
49966   // registers when given an f64 type.
49967   const TargetRegisterClass *Class = Res.second;
49968   // The generic code will match the first register class that contains the
49969   // given register. Thus, based on the ordering of the tablegened file,
49970   // the "plain" GR classes might not come first.
49971   // Therefore, use a helper method.
49972   if (isGRClass(*Class)) {
49973     unsigned Size = VT.getSizeInBits();
49974     if (Size == 1) Size = 8;
49975     Register DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
49976     if (DestReg > 0) {
49977       bool is64Bit = Subtarget.is64Bit();
49978       const TargetRegisterClass *RC =
49979           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
49980         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
49981         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
49982         : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
49983         : nullptr;
49984       if (Size == 64 && !is64Bit) {
49985         // Model GCC's behavior here and select a fixed pair of 32-bit
49986         // registers.
49987         switch (DestReg) {
49988         case X86::RAX:
49989           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
49990         case X86::RDX:
49991           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
49992         case X86::RCX:
49993           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
49994         case X86::RBX:
49995           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
49996         case X86::RSI:
49997           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
49998         case X86::RDI:
49999           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
50000         case X86::RBP:
50001           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
50002         default:
50003           return std::make_pair(0, nullptr);
50004         }
50005       }
50006       if (RC && RC->contains(DestReg))
50007         return std::make_pair(DestReg, RC);
50008       return Res;
50009     }
50010     // No register found/type mismatch.
50011     return std::make_pair(0, nullptr);
50012   } else if (isFRClass(*Class)) {
50013     // Handle references to XMM physical registers that got mapped into the
50014     // wrong class.  This can happen with constraints like {xmm0} where the
50015     // target independent register mapper will just pick the first match it can
50016     // find, ignoring the required type.
50017 
50018     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
50019     if (VT == MVT::f32 || VT == MVT::i32)
50020       Res.second = &X86::FR32XRegClass;
50021     else if (VT == MVT::f64 || VT == MVT::i64)
50022       Res.second = &X86::FR64XRegClass;
50023     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
50024       Res.second = &X86::VR128XRegClass;
50025     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
50026       Res.second = &X86::VR256XRegClass;
50027     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
50028       Res.second = &X86::VR512RegClass;
50029     else {
50030       // Type mismatch and not a clobber: Return an error;
50031       Res.first = 0;
50032       Res.second = nullptr;
50033     }
50034   } else if (isVKClass(*Class)) {
50035     if (VT == MVT::i1)
50036       Res.second = &X86::VK1RegClass;
50037     else if (VT == MVT::i8)
50038       Res.second = &X86::VK8RegClass;
50039     else if (VT == MVT::i16)
50040       Res.second = &X86::VK16RegClass;
50041     else if (VT == MVT::i32)
50042       Res.second = &X86::VK32RegClass;
50043     else if (VT == MVT::i64)
50044       Res.second = &X86::VK64RegClass;
50045     else {
50046       // Type mismatch and not a clobber: Return an error;
50047       Res.first = 0;
50048       Res.second = nullptr;
50049     }
50050   }
50051 
50052   return Res;
50053 }
50054 
getScalingFactorCost(const DataLayout & DL,const AddrMode & AM,Type * Ty,unsigned AS) const50055 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
50056                                             const AddrMode &AM, Type *Ty,
50057                                             unsigned AS) const {
50058   // Scaling factors are not free at all.
50059   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
50060   // will take 2 allocations in the out of order engine instead of 1
50061   // for plain addressing mode, i.e. inst (reg1).
50062   // E.g.,
50063   // vaddps (%rsi,%rdx), %ymm0, %ymm1
50064   // Requires two allocations (one for the load, one for the computation)
50065   // whereas:
50066   // vaddps (%rsi), %ymm0, %ymm1
50067   // Requires just 1 allocation, i.e., freeing allocations for other operations
50068   // and having less micro operations to execute.
50069   //
50070   // For some X86 architectures, this is even worse because for instance for
50071   // stores, the complex addressing mode forces the instruction to use the
50072   // "load" ports instead of the dedicated "store" port.
50073   // E.g., on Haswell:
50074   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
50075   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
50076   if (isLegalAddressingMode(DL, AM, Ty, AS))
50077     // Scale represents reg2 * scale, thus account for 1
50078     // as soon as we use a second register.
50079     return AM.Scale != 0;
50080   return -1;
50081 }
50082 
isIntDivCheap(EVT VT,AttributeList Attr) const50083 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
50084   // Integer division on x86 is expensive. However, when aggressively optimizing
50085   // for code size, we prefer to use a div instruction, as it is usually smaller
50086   // than the alternative sequence.
50087   // The exception to this is vector division. Since x86 doesn't have vector
50088   // integer division, leaving the division as-is is a loss even in terms of
50089   // size, because it will have to be scalarized, while the alternative code
50090   // sequence can be performed in vector form.
50091   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
50092   return OptSize && !VT.isVector();
50093 }
50094 
initializeSplitCSR(MachineBasicBlock * Entry) const50095 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
50096   if (!Subtarget.is64Bit())
50097     return;
50098 
50099   // Update IsSplitCSR in X86MachineFunctionInfo.
50100   X86MachineFunctionInfo *AFI =
50101       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
50102   AFI->setIsSplitCSR(true);
50103 }
50104 
insertCopiesSplitCSR(MachineBasicBlock * Entry,const SmallVectorImpl<MachineBasicBlock * > & Exits) const50105 void X86TargetLowering::insertCopiesSplitCSR(
50106     MachineBasicBlock *Entry,
50107     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
50108   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
50109   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
50110   if (!IStart)
50111     return;
50112 
50113   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
50114   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
50115   MachineBasicBlock::iterator MBBI = Entry->begin();
50116   for (const MCPhysReg *I = IStart; *I; ++I) {
50117     const TargetRegisterClass *RC = nullptr;
50118     if (X86::GR64RegClass.contains(*I))
50119       RC = &X86::GR64RegClass;
50120     else
50121       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
50122 
50123     Register NewVR = MRI->createVirtualRegister(RC);
50124     // Create copy from CSR to a virtual register.
50125     // FIXME: this currently does not emit CFI pseudo-instructions, it works
50126     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
50127     // nounwind. If we want to generalize this later, we may need to emit
50128     // CFI pseudo-instructions.
50129     assert(
50130         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
50131         "Function should be nounwind in insertCopiesSplitCSR!");
50132     Entry->addLiveIn(*I);
50133     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
50134         .addReg(*I);
50135 
50136     // Insert the copy-back instructions right before the terminator.
50137     for (auto *Exit : Exits)
50138       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
50139               TII->get(TargetOpcode::COPY), *I)
50140           .addReg(NewVR);
50141   }
50142 }
50143 
supportSwiftError() const50144 bool X86TargetLowering::supportSwiftError() const {
50145   return Subtarget.is64Bit();
50146 }
50147 
50148 /// Returns true if stack probing through a function call is requested.
hasStackProbeSymbol(MachineFunction & MF) const50149 bool X86TargetLowering::hasStackProbeSymbol(MachineFunction &MF) const {
50150   return !getStackProbeSymbolName(MF).empty();
50151 }
50152 
50153 /// Returns true if stack probing through inline assembly is requested.
hasInlineStackProbe(MachineFunction & MF) const50154 bool X86TargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
50155 
50156   // No inline stack probe for Windows, they have their own mechanism.
50157   if (Subtarget.isOSWindows() ||
50158       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
50159     return false;
50160 
50161   // If the function specifically requests inline stack probes, emit them.
50162   if (MF.getFunction().hasFnAttribute("probe-stack"))
50163     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
50164            "inline-asm";
50165 
50166   return false;
50167 }
50168 
50169 /// Returns the name of the symbol used to emit stack probes or the empty
50170 /// string if not applicable.
50171 StringRef
getStackProbeSymbolName(MachineFunction & MF) const50172 X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
50173   // Inline Stack probes disable stack probe call
50174   if (hasInlineStackProbe(MF))
50175     return "";
50176 
50177   // If the function specifically requests stack probes, emit them.
50178   if (MF.getFunction().hasFnAttribute("probe-stack"))
50179     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
50180 
50181   // Generally, if we aren't on Windows, the platform ABI does not include
50182   // support for stack probes, so don't emit them.
50183   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
50184       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
50185     return "";
50186 
50187   // We need a stack probe to conform to the Windows ABI. Choose the right
50188   // symbol.
50189   if (Subtarget.is64Bit())
50190     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
50191   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
50192 }
50193 
50194 unsigned
getStackProbeSize(MachineFunction & MF) const50195 X86TargetLowering::getStackProbeSize(MachineFunction &MF) const {
50196   // The default stack probe size is 4096 if the function has no stackprobesize
50197   // attribute.
50198   unsigned StackProbeSize = 4096;
50199   const Function &Fn = MF.getFunction();
50200   if (Fn.hasFnAttribute("stack-probe-size"))
50201     Fn.getFnAttribute("stack-probe-size")
50202         .getValueAsString()
50203         .getAsInteger(0, StackProbeSize);
50204   return StackProbeSize;
50205 }
50206