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/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineModuleInfo.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/TargetLowering.h"
42 #include "llvm/CodeGen/WinEHFuncInfo.h"
43 #include "llvm/IR/CallingConv.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DerivedTypes.h"
46 #include "llvm/IR/DiagnosticInfo.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/GlobalAlias.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/Instructions.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/MC/MCAsmInfo.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCExpr.h"
55 #include "llvm/MC/MCSymbol.h"
56 #include "llvm/Support/CommandLine.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/KnownBits.h"
60 #include "llvm/Support/MathExtras.h"
61 #include "llvm/Target/TargetOptions.h"
62 #include <algorithm>
63 #include <bitset>
64 #include <cctype>
65 #include <numeric>
66 using namespace llvm;
67 
68 #define DEBUG_TYPE "x86-isel"
69 
70 STATISTIC(NumTailCalls, "Number of tail calls");
71 
72 static cl::opt<int> ExperimentalPrefLoopAlignment(
73     "x86-experimental-pref-loop-alignment", cl::init(4),
74     cl::desc(
75         "Sets the preferable loop alignment for experiments (as log2 bytes)"
76         "(the last x86-experimental-pref-loop-alignment bits"
77         " of the loop header PC will be 0)."),
78     cl::Hidden);
79 
80 static cl::opt<int> ExperimentalPrefInnermostLoopAlignment(
81     "x86-experimental-pref-innermost-loop-alignment", cl::init(4),
82     cl::desc(
83         "Sets the preferable loop alignment for experiments (as log2 bytes) "
84         "for innermost loops only. If specified, this option overrides "
85         "alignment set by x86-experimental-pref-loop-alignment."),
86     cl::Hidden);
87 
88 static cl::opt<bool> MulConstantOptimization(
89     "mul-constant-optimization", cl::init(true),
90     cl::desc("Replace 'mul x, Const' with more effective instructions like "
91              "SHIFT, LEA, etc."),
92     cl::Hidden);
93 
94 static cl::opt<bool> ExperimentalUnorderedISEL(
95     "x86-experimental-unordered-atomic-isel", cl::init(false),
96     cl::desc("Use LoadSDNode and StoreSDNode instead of "
97              "AtomicSDNode for unordered atomic loads and "
98              "stores respectively."),
99     cl::Hidden);
100 
101 /// Call this when the user attempts to do something unsupported, like
102 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
103 /// report_fatal_error, so calling code should attempt to recover without
104 /// crashing.
105 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
106                              const char *Msg) {
107   MachineFunction &MF = DAG.getMachineFunction();
108   DAG.getContext()->diagnose(
109       DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
110 }
111 
112 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
113                                      const X86Subtarget &STI)
114     : TargetLowering(TM), Subtarget(STI) {
115   bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
116   X86ScalarSSEf64 = Subtarget.hasSSE2();
117   X86ScalarSSEf32 = Subtarget.hasSSE1();
118   MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
119 
120   // Set up the TargetLowering object.
121 
122   // X86 is weird. It always uses i8 for shift amounts and setcc results.
123   setBooleanContents(ZeroOrOneBooleanContent);
124   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
125   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
126 
127   // For 64-bit, since we have so many registers, use the ILP scheduler.
128   // For 32-bit, use the register pressure specific scheduling.
129   // For Atom, always use ILP scheduling.
130   if (Subtarget.isAtom())
131     setSchedulingPreference(Sched::ILP);
132   else if (Subtarget.is64Bit())
133     setSchedulingPreference(Sched::ILP);
134   else
135     setSchedulingPreference(Sched::RegPressure);
136   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
137   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
138 
139   // Bypass expensive divides and use cheaper ones.
140   if (TM.getOptLevel() >= CodeGenOpt::Default) {
141     if (Subtarget.hasSlowDivide32())
142       addBypassSlowDiv(32, 8);
143     if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
144       addBypassSlowDiv(64, 32);
145   }
146 
147   // Setup Windows compiler runtime calls.
148   if (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()) {
149     static const struct {
150       const RTLIB::Libcall Op;
151       const char * const Name;
152       const CallingConv::ID CC;
153     } LibraryCalls[] = {
154       { RTLIB::SDIV_I64, "_alldiv", CallingConv::X86_StdCall },
155       { RTLIB::UDIV_I64, "_aulldiv", CallingConv::X86_StdCall },
156       { RTLIB::SREM_I64, "_allrem", CallingConv::X86_StdCall },
157       { RTLIB::UREM_I64, "_aullrem", CallingConv::X86_StdCall },
158       { RTLIB::MUL_I64, "_allmul", CallingConv::X86_StdCall },
159     };
160 
161     for (const auto &LC : LibraryCalls) {
162       setLibcallName(LC.Op, LC.Name);
163       setLibcallCallingConv(LC.Op, LC.CC);
164     }
165   }
166 
167   if (Subtarget.getTargetTriple().isOSMSVCRT()) {
168     // MSVCRT doesn't have powi; fall back to pow
169     setLibcallName(RTLIB::POWI_F32, nullptr);
170     setLibcallName(RTLIB::POWI_F64, nullptr);
171   }
172 
173   // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
174   // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
175   // FIXME: Should we be limiting the atomic size on other configs? Default is
176   // 1024.
177   if (!Subtarget.hasCmpxchg8b())
178     setMaxAtomicSizeInBitsSupported(32);
179 
180   // Set up the register classes.
181   addRegisterClass(MVT::i8, &X86::GR8RegClass);
182   addRegisterClass(MVT::i16, &X86::GR16RegClass);
183   addRegisterClass(MVT::i32, &X86::GR32RegClass);
184   if (Subtarget.is64Bit())
185     addRegisterClass(MVT::i64, &X86::GR64RegClass);
186 
187   for (MVT VT : MVT::integer_valuetypes())
188     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
189 
190   // We don't accept any truncstore of integer registers.
191   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
192   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
193   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
194   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
195   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
196   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
197 
198   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
199 
200   // SETOEQ and SETUNE require checking two conditions.
201   for (auto VT : {MVT::f32, MVT::f64, MVT::f80}) {
202     setCondCodeAction(ISD::SETOEQ, VT, Expand);
203     setCondCodeAction(ISD::SETUNE, VT, Expand);
204   }
205 
206   // Integer absolute.
207   if (Subtarget.hasCMov()) {
208     setOperationAction(ISD::ABS            , MVT::i16  , Custom);
209     setOperationAction(ISD::ABS            , MVT::i32  , Custom);
210     if (Subtarget.is64Bit())
211       setOperationAction(ISD::ABS          , MVT::i64  , Custom);
212   }
213 
214   // Funnel shifts.
215   for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
216     // For slow shld targets we only lower for code size.
217     LegalizeAction ShiftDoubleAction = Subtarget.isSHLDSlow() ? Custom : Legal;
218 
219     setOperationAction(ShiftOp             , MVT::i8   , Custom);
220     setOperationAction(ShiftOp             , MVT::i16  , Custom);
221     setOperationAction(ShiftOp             , MVT::i32  , ShiftDoubleAction);
222     if (Subtarget.is64Bit())
223       setOperationAction(ShiftOp           , MVT::i64  , ShiftDoubleAction);
224   }
225 
226   if (!Subtarget.useSoftFloat()) {
227     // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
228     // operation.
229     setOperationAction(ISD::UINT_TO_FP,        MVT::i8, Promote);
230     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i8, Promote);
231     setOperationAction(ISD::UINT_TO_FP,        MVT::i16, Promote);
232     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i16, Promote);
233     // We have an algorithm for SSE2, and we turn this into a 64-bit
234     // FILD or VCVTUSI2SS/SD for other targets.
235     setOperationAction(ISD::UINT_TO_FP,        MVT::i32, Custom);
236     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
237     // We have an algorithm for SSE2->double, and we turn this into a
238     // 64-bit FILD followed by conditional FADD for other targets.
239     setOperationAction(ISD::UINT_TO_FP,        MVT::i64, Custom);
240     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
241 
242     // Promote i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
243     // this operation.
244     setOperationAction(ISD::SINT_TO_FP,        MVT::i8, Promote);
245     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i8, Promote);
246     // SSE has no i16 to fp conversion, only i32. We promote in the handler
247     // to allow f80 to use i16 and f64 to use i16 with sse1 only
248     setOperationAction(ISD::SINT_TO_FP,        MVT::i16, Custom);
249     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i16, Custom);
250     // f32 and f64 cases are Legal with SSE1/SSE2, f80 case is not
251     setOperationAction(ISD::SINT_TO_FP,        MVT::i32, Custom);
252     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
253     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
254     // are Legal, f80 is custom lowered.
255     setOperationAction(ISD::SINT_TO_FP,        MVT::i64, Custom);
256     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
257 
258     // Promote i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
259     // this operation.
260     setOperationAction(ISD::FP_TO_SINT,        MVT::i8,  Promote);
261     // FIXME: This doesn't generate invalid exception when it should. PR44019.
262     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i8,  Promote);
263     setOperationAction(ISD::FP_TO_SINT,        MVT::i16, Custom);
264     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i16, Custom);
265     setOperationAction(ISD::FP_TO_SINT,        MVT::i32, Custom);
266     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
267     // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
268     // are Legal, f80 is custom lowered.
269     setOperationAction(ISD::FP_TO_SINT,        MVT::i64, Custom);
270     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
271 
272     // Handle FP_TO_UINT by promoting the destination to a larger signed
273     // conversion.
274     setOperationAction(ISD::FP_TO_UINT,        MVT::i8,  Promote);
275     // FIXME: This doesn't generate invalid exception when it should. PR44019.
276     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i8,  Promote);
277     setOperationAction(ISD::FP_TO_UINT,        MVT::i16, Promote);
278     // FIXME: This doesn't generate invalid exception when it should. PR44019.
279     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i16, Promote);
280     setOperationAction(ISD::FP_TO_UINT,        MVT::i32, Custom);
281     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
282     setOperationAction(ISD::FP_TO_UINT,        MVT::i64, Custom);
283     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
284 
285     setOperationAction(ISD::LRINT,             MVT::f32, Custom);
286     setOperationAction(ISD::LRINT,             MVT::f64, Custom);
287     setOperationAction(ISD::LLRINT,            MVT::f32, Custom);
288     setOperationAction(ISD::LLRINT,            MVT::f64, Custom);
289 
290     if (!Subtarget.is64Bit()) {
291       setOperationAction(ISD::LRINT,  MVT::i64, Custom);
292       setOperationAction(ISD::LLRINT, MVT::i64, Custom);
293     }
294   }
295 
296   if (Subtarget.hasSSE2()) {
297     // Custom lowering for saturating float to int conversions.
298     // We handle promotion to larger result types manually.
299     for (MVT VT : { MVT::i8, MVT::i16, MVT::i32 }) {
300       setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
301       setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
302     }
303     if (Subtarget.is64Bit()) {
304       setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
305       setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
306     }
307   }
308 
309   // Handle address space casts between mixed sized pointers.
310   setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
311   setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
312 
313   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
314   if (!X86ScalarSSEf64) {
315     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
316     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
317     if (Subtarget.is64Bit()) {
318       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
319       // Without SSE, i64->f64 goes through memory.
320       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
321     }
322   } else if (!Subtarget.is64Bit())
323     setOperationAction(ISD::BITCAST      , MVT::i64  , Custom);
324 
325   // Scalar integer divide and remainder are lowered to use operations that
326   // produce two results, to match the available instructions. This exposes
327   // the two-result form to trivial CSE, which is able to combine x/y and x%y
328   // into a single instruction.
329   //
330   // Scalar integer multiply-high is also lowered to use two-result
331   // operations, to match the available instructions. However, plain multiply
332   // (low) operations are left as Legal, as there are single-result
333   // instructions for this in x86. Using the two-result multiply instructions
334   // when both high and low results are needed must be arranged by dagcombine.
335   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
336     setOperationAction(ISD::MULHS, VT, Expand);
337     setOperationAction(ISD::MULHU, VT, Expand);
338     setOperationAction(ISD::SDIV, VT, Expand);
339     setOperationAction(ISD::UDIV, VT, Expand);
340     setOperationAction(ISD::SREM, VT, Expand);
341     setOperationAction(ISD::UREM, VT, Expand);
342   }
343 
344   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
345   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
346   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
347                    MVT::i8,  MVT::i16, MVT::i32, MVT::i64 }) {
348     setOperationAction(ISD::BR_CC,     VT, Expand);
349     setOperationAction(ISD::SELECT_CC, VT, Expand);
350   }
351   if (Subtarget.is64Bit())
352     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
353   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
354   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
355   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
356 
357   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
358   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
359   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
360   setOperationAction(ISD::FREM             , MVT::f128 , Expand);
361   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
362 
363   // Promote the i8 variants and force them on up to i32 which has a shorter
364   // encoding.
365   setOperationPromotedToType(ISD::CTTZ           , MVT::i8   , MVT::i32);
366   setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
367   if (!Subtarget.hasBMI()) {
368     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
369     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
370     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Legal);
371     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Legal);
372     if (Subtarget.is64Bit()) {
373       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
374       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
375     }
376   }
377 
378   if (Subtarget.hasLZCNT()) {
379     // When promoting the i8 variants, force them to i32 for a shorter
380     // encoding.
381     setOperationPromotedToType(ISD::CTLZ           , MVT::i8   , MVT::i32);
382     setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
383   } else {
384     for (auto VT : {MVT::i8, MVT::i16, MVT::i32, MVT::i64}) {
385       if (VT == MVT::i64 && !Subtarget.is64Bit())
386         continue;
387       setOperationAction(ISD::CTLZ           , VT, Custom);
388       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
389     }
390   }
391 
392   for (auto Op : {ISD::FP16_TO_FP, ISD::STRICT_FP16_TO_FP, ISD::FP_TO_FP16,
393                   ISD::STRICT_FP_TO_FP16}) {
394     // Special handling for half-precision floating point conversions.
395     // If we don't have F16C support, then lower half float conversions
396     // into library calls.
397     setOperationAction(
398         Op, MVT::f32,
399         (!Subtarget.useSoftFloat() && Subtarget.hasF16C()) ? Custom : Expand);
400     // There's never any support for operations beyond MVT::f32.
401     setOperationAction(Op, MVT::f64, Expand);
402     setOperationAction(Op, MVT::f80, Expand);
403     setOperationAction(Op, MVT::f128, Expand);
404   }
405 
406   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
407   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
408   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
409   setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
410   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
411   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
412   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
413   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
414 
415   setOperationAction(ISD::PARITY, MVT::i8, Custom);
416   if (Subtarget.hasPOPCNT()) {
417     setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
418   } else {
419     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
420     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
421     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
422     if (Subtarget.is64Bit())
423       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
424     else
425       setOperationAction(ISD::CTPOP        , MVT::i64  , Custom);
426 
427     setOperationAction(ISD::PARITY, MVT::i16, Custom);
428     setOperationAction(ISD::PARITY, MVT::i32, Custom);
429     if (Subtarget.is64Bit())
430       setOperationAction(ISD::PARITY, MVT::i64, Custom);
431   }
432 
433   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
434 
435   if (!Subtarget.hasMOVBE())
436     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
437 
438   // X86 wants to expand cmov itself.
439   for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
440     setOperationAction(ISD::SELECT, VT, Custom);
441     setOperationAction(ISD::SETCC, VT, Custom);
442     setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
443     setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
444   }
445   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
446     if (VT == MVT::i64 && !Subtarget.is64Bit())
447       continue;
448     setOperationAction(ISD::SELECT, VT, Custom);
449     setOperationAction(ISD::SETCC,  VT, Custom);
450   }
451 
452   // Custom action for SELECT MMX and expand action for SELECT_CC MMX
453   setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
454   setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
455 
456   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
457   // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
458   // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
459   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
460   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
461   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
462   if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
463     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
464 
465   // Darwin ABI issue.
466   for (auto VT : { MVT::i32, MVT::i64 }) {
467     if (VT == MVT::i64 && !Subtarget.is64Bit())
468       continue;
469     setOperationAction(ISD::ConstantPool    , VT, Custom);
470     setOperationAction(ISD::JumpTable       , VT, Custom);
471     setOperationAction(ISD::GlobalAddress   , VT, Custom);
472     setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
473     setOperationAction(ISD::ExternalSymbol  , VT, Custom);
474     setOperationAction(ISD::BlockAddress    , VT, Custom);
475   }
476 
477   // 64-bit shl, sra, srl (iff 32-bit x86)
478   for (auto VT : { MVT::i32, MVT::i64 }) {
479     if (VT == MVT::i64 && !Subtarget.is64Bit())
480       continue;
481     setOperationAction(ISD::SHL_PARTS, VT, Custom);
482     setOperationAction(ISD::SRA_PARTS, VT, Custom);
483     setOperationAction(ISD::SRL_PARTS, VT, Custom);
484   }
485 
486   if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
487     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
488 
489   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
490 
491   // Expand certain atomics
492   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
493     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
494     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
495     setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
496     setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
497     setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
498     setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
499     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
500   }
501 
502   if (!Subtarget.is64Bit())
503     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
504 
505   if (Subtarget.hasCmpxchg16b()) {
506     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
507   }
508 
509   // FIXME - use subtarget debug flags
510   if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
511       !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
512       TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
513     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
514   }
515 
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518 
519   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521 
522   setOperationAction(ISD::TRAP, MVT::Other, Legal);
523   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
524   setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
525 
526   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
527   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
528   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
529   bool Is64Bit = Subtarget.is64Bit();
530   setOperationAction(ISD::VAARG,  MVT::Other, Is64Bit ? Custom : Expand);
531   setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
532 
533   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
534   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
535 
536   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
537 
538   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
539   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
540   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
541 
542   if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
543     // f32 and f64 use SSE.
544     // Set up the FP register classes.
545     addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
546                                                      : &X86::FR32RegClass);
547     addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
548                                                      : &X86::FR64RegClass);
549 
550     // Disable f32->f64 extload as we can only generate this in one instruction
551     // under optsize. So its easier to pattern match (fpext (load)) for that
552     // case instead of needing to emit 2 instructions for extload in the
553     // non-optsize case.
554     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
555 
556     for (auto VT : { MVT::f32, MVT::f64 }) {
557       // Use ANDPD to simulate FABS.
558       setOperationAction(ISD::FABS, VT, Custom);
559 
560       // Use XORP to simulate FNEG.
561       setOperationAction(ISD::FNEG, VT, Custom);
562 
563       // Use ANDPD and ORPD to simulate FCOPYSIGN.
564       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
565 
566       // These might be better off as horizontal vector ops.
567       setOperationAction(ISD::FADD, VT, Custom);
568       setOperationAction(ISD::FSUB, VT, Custom);
569 
570       // We don't support sin/cos/fmod
571       setOperationAction(ISD::FSIN   , VT, Expand);
572       setOperationAction(ISD::FCOS   , VT, Expand);
573       setOperationAction(ISD::FSINCOS, VT, Expand);
574     }
575 
576     // Lower this to MOVMSK plus an AND.
577     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
578     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
579 
580   } else if (!Subtarget.useSoftFloat() && X86ScalarSSEf32 &&
581              (UseX87 || Is64Bit)) {
582     // Use SSE for f32, x87 for f64.
583     // Set up the FP register classes.
584     addRegisterClass(MVT::f32, &X86::FR32RegClass);
585     if (UseX87)
586       addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587 
588     // Use ANDPS to simulate FABS.
589     setOperationAction(ISD::FABS , MVT::f32, Custom);
590 
591     // Use XORP to simulate FNEG.
592     setOperationAction(ISD::FNEG , MVT::f32, Custom);
593 
594     if (UseX87)
595       setOperationAction(ISD::UNDEF, MVT::f64, Expand);
596 
597     // Use ANDPS and ORPS to simulate FCOPYSIGN.
598     if (UseX87)
599       setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
600     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
601 
602     // We don't support sin/cos/fmod
603     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
604     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
605     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
606 
607     if (UseX87) {
608       // Always expand sin/cos functions even though x87 has an instruction.
609       setOperationAction(ISD::FSIN, MVT::f64, Expand);
610       setOperationAction(ISD::FCOS, MVT::f64, Expand);
611       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
612     }
613   } else if (UseX87) {
614     // f32 and f64 in x87.
615     // Set up the FP register classes.
616     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
617     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
618 
619     for (auto VT : { MVT::f32, MVT::f64 }) {
620       setOperationAction(ISD::UNDEF,     VT, Expand);
621       setOperationAction(ISD::FCOPYSIGN, VT, Expand);
622 
623       // Always expand sin/cos functions even though x87 has an instruction.
624       setOperationAction(ISD::FSIN   , VT, Expand);
625       setOperationAction(ISD::FCOS   , VT, Expand);
626       setOperationAction(ISD::FSINCOS, VT, Expand);
627     }
628   }
629 
630   // Expand FP32 immediates into loads from the stack, save special cases.
631   if (isTypeLegal(MVT::f32)) {
632     if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
633       addLegalFPImmediate(APFloat(+0.0f)); // FLD0
634       addLegalFPImmediate(APFloat(+1.0f)); // FLD1
635       addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
636       addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
637     } else // SSE immediates.
638       addLegalFPImmediate(APFloat(+0.0f)); // xorps
639   }
640   // Expand FP64 immediates into loads from the stack, save special cases.
641   if (isTypeLegal(MVT::f64)) {
642     if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
643       addLegalFPImmediate(APFloat(+0.0)); // FLD0
644       addLegalFPImmediate(APFloat(+1.0)); // FLD1
645       addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
646       addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647     } else // SSE immediates.
648       addLegalFPImmediate(APFloat(+0.0)); // xorpd
649   }
650   // Handle constrained floating-point operations of scalar.
651   setOperationAction(ISD::STRICT_FADD,      MVT::f32, Legal);
652   setOperationAction(ISD::STRICT_FADD,      MVT::f64, Legal);
653   setOperationAction(ISD::STRICT_FSUB,      MVT::f32, Legal);
654   setOperationAction(ISD::STRICT_FSUB,      MVT::f64, Legal);
655   setOperationAction(ISD::STRICT_FMUL,      MVT::f32, Legal);
656   setOperationAction(ISD::STRICT_FMUL,      MVT::f64, Legal);
657   setOperationAction(ISD::STRICT_FDIV,      MVT::f32, Legal);
658   setOperationAction(ISD::STRICT_FDIV,      MVT::f64, Legal);
659   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
660   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f32, Legal);
661   setOperationAction(ISD::STRICT_FP_ROUND,  MVT::f64, Legal);
662   setOperationAction(ISD::STRICT_FSQRT,     MVT::f32, Legal);
663   setOperationAction(ISD::STRICT_FSQRT,     MVT::f64, Legal);
664 
665   // We don't support FMA.
666   setOperationAction(ISD::FMA, MVT::f64, Expand);
667   setOperationAction(ISD::FMA, MVT::f32, Expand);
668 
669   // f80 always uses X87.
670   if (UseX87) {
671     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
672     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
673     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
674     {
675       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
676       addLegalFPImmediate(TmpFlt);  // FLD0
677       TmpFlt.changeSign();
678       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
679 
680       bool ignored;
681       APFloat TmpFlt2(+1.0);
682       TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
683                       &ignored);
684       addLegalFPImmediate(TmpFlt2);  // FLD1
685       TmpFlt2.changeSign();
686       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
687     }
688 
689     // Always expand sin/cos functions even though x87 has an instruction.
690     setOperationAction(ISD::FSIN   , MVT::f80, Expand);
691     setOperationAction(ISD::FCOS   , MVT::f80, Expand);
692     setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
693 
694     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
695     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
696     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
697     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
698     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
699     setOperationAction(ISD::FMA, MVT::f80, Expand);
700     setOperationAction(ISD::LROUND, MVT::f80, Expand);
701     setOperationAction(ISD::LLROUND, MVT::f80, Expand);
702     setOperationAction(ISD::LRINT, MVT::f80, Custom);
703     setOperationAction(ISD::LLRINT, MVT::f80, Custom);
704 
705     // Handle constrained floating-point operations of scalar.
706     setOperationAction(ISD::STRICT_FADD     , MVT::f80, Legal);
707     setOperationAction(ISD::STRICT_FSUB     , MVT::f80, Legal);
708     setOperationAction(ISD::STRICT_FMUL     , MVT::f80, Legal);
709     setOperationAction(ISD::STRICT_FDIV     , MVT::f80, Legal);
710     setOperationAction(ISD::STRICT_FSQRT    , MVT::f80, Legal);
711     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f80, Legal);
712     // FIXME: When the target is 64-bit, STRICT_FP_ROUND will be overwritten
713     // as Custom.
714     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Legal);
715   }
716 
717   // f128 uses xmm registers, but most operations require libcalls.
718   if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
719     addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
720                                                    : &X86::VR128RegClass);
721 
722     addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
723 
724     setOperationAction(ISD::FADD,        MVT::f128, LibCall);
725     setOperationAction(ISD::STRICT_FADD, MVT::f128, LibCall);
726     setOperationAction(ISD::FSUB,        MVT::f128, LibCall);
727     setOperationAction(ISD::STRICT_FSUB, MVT::f128, LibCall);
728     setOperationAction(ISD::FDIV,        MVT::f128, LibCall);
729     setOperationAction(ISD::STRICT_FDIV, MVT::f128, LibCall);
730     setOperationAction(ISD::FMUL,        MVT::f128, LibCall);
731     setOperationAction(ISD::STRICT_FMUL, MVT::f128, LibCall);
732     setOperationAction(ISD::FMA,         MVT::f128, LibCall);
733     setOperationAction(ISD::STRICT_FMA,  MVT::f128, LibCall);
734 
735     setOperationAction(ISD::FABS, MVT::f128, Custom);
736     setOperationAction(ISD::FNEG, MVT::f128, Custom);
737     setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
738 
739     setOperationAction(ISD::FSIN,         MVT::f128, LibCall);
740     setOperationAction(ISD::STRICT_FSIN,  MVT::f128, LibCall);
741     setOperationAction(ISD::FCOS,         MVT::f128, LibCall);
742     setOperationAction(ISD::STRICT_FCOS,  MVT::f128, LibCall);
743     setOperationAction(ISD::FSINCOS,      MVT::f128, LibCall);
744     // No STRICT_FSINCOS
745     setOperationAction(ISD::FSQRT,        MVT::f128, LibCall);
746     setOperationAction(ISD::STRICT_FSQRT, MVT::f128, LibCall);
747 
748     setOperationAction(ISD::FP_EXTEND,        MVT::f128, Custom);
749     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Custom);
750     // We need to custom handle any FP_ROUND with an f128 input, but
751     // LegalizeDAG uses the result type to know when to run a custom handler.
752     // So we have to list all legal floating point result types here.
753     if (isTypeLegal(MVT::f32)) {
754       setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
755       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
756     }
757     if (isTypeLegal(MVT::f64)) {
758       setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
759       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
760     }
761     if (isTypeLegal(MVT::f80)) {
762       setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
763       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
764     }
765 
766     setOperationAction(ISD::SETCC, MVT::f128, Custom);
767 
768     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
769     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
770     setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
771     setTruncStoreAction(MVT::f128, MVT::f32, Expand);
772     setTruncStoreAction(MVT::f128, MVT::f64, Expand);
773     setTruncStoreAction(MVT::f128, MVT::f80, Expand);
774   }
775 
776   // Always use a library call for pow.
777   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
778   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f128 , Expand);
781 
782   setOperationAction(ISD::FLOG, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
788   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
789 
790   // Some FP actions are always expanded for vector types.
791   for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
792                    MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
793     setOperationAction(ISD::FSIN,      VT, Expand);
794     setOperationAction(ISD::FSINCOS,   VT, Expand);
795     setOperationAction(ISD::FCOS,      VT, Expand);
796     setOperationAction(ISD::FREM,      VT, Expand);
797     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
798     setOperationAction(ISD::FPOW,      VT, Expand);
799     setOperationAction(ISD::FLOG,      VT, Expand);
800     setOperationAction(ISD::FLOG2,     VT, Expand);
801     setOperationAction(ISD::FLOG10,    VT, Expand);
802     setOperationAction(ISD::FEXP,      VT, Expand);
803     setOperationAction(ISD::FEXP2,     VT, Expand);
804   }
805 
806   // First set operation action for all vector types to either promote
807   // (for widening) or expand (for scalarization). Then we will selectively
808   // turn on ones that can be effectively codegen'd.
809   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
810     setOperationAction(ISD::SDIV, VT, Expand);
811     setOperationAction(ISD::UDIV, VT, Expand);
812     setOperationAction(ISD::SREM, VT, Expand);
813     setOperationAction(ISD::UREM, VT, Expand);
814     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
815     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
816     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
817     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
818     setOperationAction(ISD::FMA,  VT, Expand);
819     setOperationAction(ISD::FFLOOR, VT, Expand);
820     setOperationAction(ISD::FCEIL, VT, Expand);
821     setOperationAction(ISD::FTRUNC, VT, Expand);
822     setOperationAction(ISD::FRINT, VT, Expand);
823     setOperationAction(ISD::FNEARBYINT, VT, Expand);
824     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
825     setOperationAction(ISD::MULHS, VT, Expand);
826     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
827     setOperationAction(ISD::MULHU, VT, Expand);
828     setOperationAction(ISD::SDIVREM, VT, Expand);
829     setOperationAction(ISD::UDIVREM, VT, Expand);
830     setOperationAction(ISD::CTPOP, VT, Expand);
831     setOperationAction(ISD::CTTZ, VT, Expand);
832     setOperationAction(ISD::CTLZ, VT, Expand);
833     setOperationAction(ISD::ROTL, VT, Expand);
834     setOperationAction(ISD::ROTR, VT, Expand);
835     setOperationAction(ISD::BSWAP, VT, Expand);
836     setOperationAction(ISD::SETCC, VT, Expand);
837     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
838     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
839     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
840     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
841     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
842     setOperationAction(ISD::TRUNCATE, VT, Expand);
843     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
844     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
845     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
846     setOperationAction(ISD::SELECT_CC, VT, Expand);
847     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
848       setTruncStoreAction(InnerVT, VT, Expand);
849 
850       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
851       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
852 
853       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
854       // types, we have to deal with them whether we ask for Expansion or not.
855       // Setting Expand causes its own optimisation problems though, so leave
856       // them legal.
857       if (VT.getVectorElementType() == MVT::i1)
858         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
859 
860       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
861       // split/scalarized right now.
862       if (VT.getVectorElementType() == MVT::f16)
863         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
864     }
865   }
866 
867   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
868   // with -msoft-float, disable use of MMX as well.
869   if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
870     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
871     // No operations on x86mmx supported, everything uses intrinsics.
872   }
873 
874   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
875     addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
876                                                     : &X86::VR128RegClass);
877 
878     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
879     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
880     setOperationAction(ISD::FCOPYSIGN,          MVT::v4f32, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
883     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
884     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
885     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
886 
887     setOperationAction(ISD::LOAD,               MVT::v2f32, Custom);
888     setOperationAction(ISD::STORE,              MVT::v2f32, Custom);
889 
890     setOperationAction(ISD::STRICT_FADD,        MVT::v4f32, Legal);
891     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f32, Legal);
892     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f32, Legal);
893     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f32, Legal);
894     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f32, Legal);
895   }
896 
897   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
898     addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
899                                                     : &X86::VR128RegClass);
900 
901     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
902     // registers cannot be used even for integer operations.
903     addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
904                                                     : &X86::VR128RegClass);
905     addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
906                                                     : &X86::VR128RegClass);
907     addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
908                                                     : &X86::VR128RegClass);
909     addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
910                                                     : &X86::VR128RegClass);
911 
912     for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
913                      MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
914       setOperationAction(ISD::SDIV, VT, Custom);
915       setOperationAction(ISD::SREM, VT, Custom);
916       setOperationAction(ISD::UDIV, VT, Custom);
917       setOperationAction(ISD::UREM, VT, Custom);
918     }
919 
920     setOperationAction(ISD::MUL,                MVT::v2i8,  Custom);
921     setOperationAction(ISD::MUL,                MVT::v4i8,  Custom);
922     setOperationAction(ISD::MUL,                MVT::v8i8,  Custom);
923 
924     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
925     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
926     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
927     setOperationAction(ISD::MULHU,              MVT::v4i32, Custom);
928     setOperationAction(ISD::MULHS,              MVT::v4i32, Custom);
929     setOperationAction(ISD::MULHU,              MVT::v16i8, Custom);
930     setOperationAction(ISD::MULHS,              MVT::v16i8, Custom);
931     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
932     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
933     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
934     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
935     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
936     setOperationAction(ISD::FCOPYSIGN,          MVT::v2f64, Custom);
937 
938     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
939       setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
940       setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
941       setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
942       setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
943     }
944 
945     setOperationAction(ISD::UADDSAT,            MVT::v16i8, Legal);
946     setOperationAction(ISD::SADDSAT,            MVT::v16i8, Legal);
947     setOperationAction(ISD::USUBSAT,            MVT::v16i8, Legal);
948     setOperationAction(ISD::SSUBSAT,            MVT::v16i8, Legal);
949     setOperationAction(ISD::UADDSAT,            MVT::v8i16, Legal);
950     setOperationAction(ISD::SADDSAT,            MVT::v8i16, Legal);
951     setOperationAction(ISD::USUBSAT,            MVT::v8i16, Legal);
952     setOperationAction(ISD::SSUBSAT,            MVT::v8i16, Legal);
953     setOperationAction(ISD::USUBSAT,            MVT::v4i32, Custom);
954     setOperationAction(ISD::USUBSAT,            MVT::v2i64, Custom);
955 
956     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
957     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
958     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
959 
960     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
961       setOperationAction(ISD::SETCC,              VT, Custom);
962       setOperationAction(ISD::STRICT_FSETCC,      VT, Custom);
963       setOperationAction(ISD::STRICT_FSETCCS,     VT, Custom);
964       setOperationAction(ISD::CTPOP,              VT, Custom);
965       setOperationAction(ISD::ABS,                VT, Custom);
966 
967       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
968       // setcc all the way to isel and prefer SETGT in some isel patterns.
969       setCondCodeAction(ISD::SETLT, VT, Custom);
970       setCondCodeAction(ISD::SETLE, VT, Custom);
971     }
972 
973     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
974       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
975       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
976       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
977       setOperationAction(ISD::VSELECT,            VT, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979     }
980 
981     for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
982       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
983       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
984       setOperationAction(ISD::VSELECT,            VT, Custom);
985 
986       if (VT == MVT::v2i64 && !Subtarget.is64Bit())
987         continue;
988 
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991     }
992 
993     // Custom lower v2i64 and v2f64 selects.
994     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
995     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
996     setOperationAction(ISD::SELECT,             MVT::v4i32, Custom);
997     setOperationAction(ISD::SELECT,             MVT::v8i16, Custom);
998     setOperationAction(ISD::SELECT,             MVT::v16i8, Custom);
999 
1000     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1001     setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
1002     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v4i32, Legal);
1003     setOperationAction(ISD::STRICT_FP_TO_SINT,  MVT::v2i32, Custom);
1004 
1005     // Custom legalize these to avoid over promotion or custom promotion.
1006     for (auto VT : {MVT::v2i8, MVT::v4i8, MVT::v8i8, MVT::v2i16, MVT::v4i16}) {
1007       setOperationAction(ISD::FP_TO_SINT,        VT, Custom);
1008       setOperationAction(ISD::FP_TO_UINT,        VT, Custom);
1009       setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Custom);
1010       setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Custom);
1011     }
1012 
1013     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1014     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v4i32, Legal);
1015     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
1016     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2i32, Custom);
1017 
1018     setOperationAction(ISD::UINT_TO_FP,         MVT::v2i32, Custom);
1019     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2i32, Custom);
1020 
1021     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
1022     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v4i32, Custom);
1023 
1024     // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
1025     setOperationAction(ISD::SINT_TO_FP,         MVT::v2f32, Custom);
1026     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v2f32, Custom);
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v2f32, Custom);
1028     setOperationAction(ISD::STRICT_UINT_TO_FP,  MVT::v2f32, Custom);
1029 
1030     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1031     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v2f32, Custom);
1032     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1033     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v2f32, Custom);
1034 
1035     // We want to legalize this to an f64 load rather than an i64 load on
1036     // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
1037     // store.
1038     setOperationAction(ISD::LOAD,               MVT::v2i32, Custom);
1039     setOperationAction(ISD::LOAD,               MVT::v4i16, Custom);
1040     setOperationAction(ISD::LOAD,               MVT::v8i8,  Custom);
1041     setOperationAction(ISD::STORE,              MVT::v2i32, Custom);
1042     setOperationAction(ISD::STORE,              MVT::v4i16, Custom);
1043     setOperationAction(ISD::STORE,              MVT::v8i8,  Custom);
1044 
1045     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1046     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1047     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1048     if (!Subtarget.hasAVX512())
1049       setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
1050 
1051     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1052     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1053     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1054 
1055     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1056 
1057     setOperationAction(ISD::TRUNCATE,    MVT::v2i8,  Custom);
1058     setOperationAction(ISD::TRUNCATE,    MVT::v2i16, Custom);
1059     setOperationAction(ISD::TRUNCATE,    MVT::v2i32, Custom);
1060     setOperationAction(ISD::TRUNCATE,    MVT::v4i8,  Custom);
1061     setOperationAction(ISD::TRUNCATE,    MVT::v4i16, Custom);
1062     setOperationAction(ISD::TRUNCATE,    MVT::v8i8,  Custom);
1063 
1064     // In the customized shift lowering, the legal v4i32/v2i64 cases
1065     // in AVX2 will be recognized.
1066     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1067       setOperationAction(ISD::SRL,              VT, Custom);
1068       setOperationAction(ISD::SHL,              VT, Custom);
1069       setOperationAction(ISD::SRA,              VT, Custom);
1070     }
1071 
1072     setOperationAction(ISD::ROTL,               MVT::v4i32, Custom);
1073     setOperationAction(ISD::ROTL,               MVT::v8i16, Custom);
1074 
1075     // With 512-bit registers or AVX512VL+BW, expanding (and promoting the
1076     // shifts) is better.
1077     if (!Subtarget.useAVX512Regs() &&
1078         !(Subtarget.hasBWI() && Subtarget.hasVLX()))
1079       setOperationAction(ISD::ROTL,             MVT::v16i8, Custom);
1080 
1081     setOperationAction(ISD::STRICT_FSQRT,       MVT::v2f64, Legal);
1082     setOperationAction(ISD::STRICT_FADD,        MVT::v2f64, Legal);
1083     setOperationAction(ISD::STRICT_FSUB,        MVT::v2f64, Legal);
1084     setOperationAction(ISD::STRICT_FMUL,        MVT::v2f64, Legal);
1085     setOperationAction(ISD::STRICT_FDIV,        MVT::v2f64, Legal);
1086   }
1087 
1088   if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1089     setOperationAction(ISD::ABS,                MVT::v16i8, Legal);
1090     setOperationAction(ISD::ABS,                MVT::v8i16, Legal);
1091     setOperationAction(ISD::ABS,                MVT::v4i32, Legal);
1092     setOperationAction(ISD::BITREVERSE,         MVT::v16i8, Custom);
1093     setOperationAction(ISD::CTLZ,               MVT::v16i8, Custom);
1094     setOperationAction(ISD::CTLZ,               MVT::v8i16, Custom);
1095     setOperationAction(ISD::CTLZ,               MVT::v4i32, Custom);
1096     setOperationAction(ISD::CTLZ,               MVT::v2i64, Custom);
1097 
1098     // These might be better off as horizontal vector ops.
1099     setOperationAction(ISD::ADD,                MVT::i16, Custom);
1100     setOperationAction(ISD::ADD,                MVT::i32, Custom);
1101     setOperationAction(ISD::SUB,                MVT::i16, Custom);
1102     setOperationAction(ISD::SUB,                MVT::i32, Custom);
1103   }
1104 
1105   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1106     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1107       setOperationAction(ISD::FFLOOR,            RoundedTy,  Legal);
1108       setOperationAction(ISD::STRICT_FFLOOR,     RoundedTy,  Legal);
1109       setOperationAction(ISD::FCEIL,             RoundedTy,  Legal);
1110       setOperationAction(ISD::STRICT_FCEIL,      RoundedTy,  Legal);
1111       setOperationAction(ISD::FTRUNC,            RoundedTy,  Legal);
1112       setOperationAction(ISD::STRICT_FTRUNC,     RoundedTy,  Legal);
1113       setOperationAction(ISD::FRINT,             RoundedTy,  Legal);
1114       setOperationAction(ISD::STRICT_FRINT,      RoundedTy,  Legal);
1115       setOperationAction(ISD::FNEARBYINT,        RoundedTy,  Legal);
1116       setOperationAction(ISD::STRICT_FNEARBYINT, RoundedTy,  Legal);
1117       setOperationAction(ISD::FROUNDEVEN,        RoundedTy,  Legal);
1118       setOperationAction(ISD::STRICT_FROUNDEVEN, RoundedTy,  Legal);
1119 
1120       setOperationAction(ISD::FROUND,            RoundedTy,  Custom);
1121     }
1122 
1123     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
1124     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
1125     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
1126     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
1127     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
1128     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
1129     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
1130     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
1131 
1132     setOperationAction(ISD::UADDSAT,            MVT::v4i32, Custom);
1133 
1134     // FIXME: Do we need to handle scalar-to-vector here?
1135     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1136 
1137     // We directly match byte blends in the backend as they match the VSELECT
1138     // condition form.
1139     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1140 
1141     // SSE41 brings specific instructions for doing vector sign extend even in
1142     // cases where we don't have SRA.
1143     for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1144       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1145       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1146     }
1147 
1148     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1149     for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1150       setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8,  Legal);
1151       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8,  Legal);
1152       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8,  Legal);
1153       setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1154       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1155       setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1156     }
1157 
1158     // i8 vectors are custom because the source register and source
1159     // source memory operand types are not the same width.
1160     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1161 
1162     if (Subtarget.is64Bit() && !Subtarget.hasAVX512()) {
1163       // We need to scalarize v4i64->v432 uint_to_fp using cvtsi2ss, but we can
1164       // do the pre and post work in the vector domain.
1165       setOperationAction(ISD::UINT_TO_FP,        MVT::v4i64, Custom);
1166       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i64, Custom);
1167       // We need to mark SINT_TO_FP as Custom even though we want to expand it
1168       // so that DAG combine doesn't try to turn it into uint_to_fp.
1169       setOperationAction(ISD::SINT_TO_FP,        MVT::v4i64, Custom);
1170       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i64, Custom);
1171     }
1172   }
1173 
1174   if (!Subtarget.useSoftFloat() && Subtarget.hasSSE42()) {
1175     setOperationAction(ISD::UADDSAT,            MVT::v2i64, Custom);
1176   }
1177 
1178   if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1179     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1180                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1181       setOperationAction(ISD::ROTL, VT, Custom);
1182 
1183     // XOP can efficiently perform BITREVERSE with VPPERM.
1184     for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1185       setOperationAction(ISD::BITREVERSE, VT, Custom);
1186 
1187     for (auto VT : { MVT::v16i8, MVT::v8i16,  MVT::v4i32, MVT::v2i64,
1188                      MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1189       setOperationAction(ISD::BITREVERSE, VT, Custom);
1190   }
1191 
1192   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1193     bool HasInt256 = Subtarget.hasInt256();
1194 
1195     addRegisterClass(MVT::v32i8,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1196                                                      : &X86::VR256RegClass);
1197     addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1198                                                      : &X86::VR256RegClass);
1199     addRegisterClass(MVT::v8i32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1200                                                      : &X86::VR256RegClass);
1201     addRegisterClass(MVT::v8f32,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1202                                                      : &X86::VR256RegClass);
1203     addRegisterClass(MVT::v4i64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1204                                                      : &X86::VR256RegClass);
1205     addRegisterClass(MVT::v4f64,  Subtarget.hasVLX() ? &X86::VR256XRegClass
1206                                                      : &X86::VR256RegClass);
1207 
1208     for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1209       setOperationAction(ISD::FFLOOR,            VT, Legal);
1210       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1211       setOperationAction(ISD::FCEIL,             VT, Legal);
1212       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1213       setOperationAction(ISD::FTRUNC,            VT, Legal);
1214       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1215       setOperationAction(ISD::FRINT,             VT, Legal);
1216       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1217       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1218       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1219       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1220       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1221 
1222       setOperationAction(ISD::FROUND,            VT, Custom);
1223 
1224       setOperationAction(ISD::FNEG,              VT, Custom);
1225       setOperationAction(ISD::FABS,              VT, Custom);
1226       setOperationAction(ISD::FCOPYSIGN,         VT, Custom);
1227     }
1228 
1229     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1230     // even though v8i16 is a legal type.
1231     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i16, MVT::v8i32);
1232     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i16, MVT::v8i32);
1233     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1234     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1235     setOperationAction(ISD::FP_TO_SINT,                MVT::v8i32, Legal);
1236     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v8i32, Legal);
1237 
1238     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1239     setOperationAction(ISD::STRICT_SINT_TO_FP,  MVT::v8i32, Legal);
1240 
1241     setOperationAction(ISD::STRICT_FP_ROUND,    MVT::v4f32, Legal);
1242     setOperationAction(ISD::STRICT_FADD,        MVT::v8f32, Legal);
1243     setOperationAction(ISD::STRICT_FADD,        MVT::v4f64, Legal);
1244     setOperationAction(ISD::STRICT_FSUB,        MVT::v8f32, Legal);
1245     setOperationAction(ISD::STRICT_FSUB,        MVT::v4f64, Legal);
1246     setOperationAction(ISD::STRICT_FMUL,        MVT::v8f32, Legal);
1247     setOperationAction(ISD::STRICT_FMUL,        MVT::v4f64, Legal);
1248     setOperationAction(ISD::STRICT_FDIV,        MVT::v8f32, Legal);
1249     setOperationAction(ISD::STRICT_FDIV,        MVT::v4f64, Legal);
1250     setOperationAction(ISD::STRICT_FP_EXTEND,   MVT::v4f64, Legal);
1251     setOperationAction(ISD::STRICT_FSQRT,       MVT::v8f32, Legal);
1252     setOperationAction(ISD::STRICT_FSQRT,       MVT::v4f64, Legal);
1253 
1254     if (!Subtarget.hasAVX512())
1255       setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1256 
1257     // In the customized shift lowering, the legal v8i32/v4i64 cases
1258     // in AVX2 will be recognized.
1259     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1260       setOperationAction(ISD::SRL, VT, Custom);
1261       setOperationAction(ISD::SHL, VT, Custom);
1262       setOperationAction(ISD::SRA, VT, Custom);
1263     }
1264 
1265     // These types need custom splitting if their input is a 128-bit vector.
1266     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i64,  Custom);
1267     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i32, Custom);
1268     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i64,  Custom);
1269     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i32, Custom);
1270 
1271     setOperationAction(ISD::ROTL,              MVT::v8i32,  Custom);
1272     setOperationAction(ISD::ROTL,              MVT::v16i16, Custom);
1273 
1274     // With BWI, expanding (and promoting the shifts) is the better.
1275     if (!Subtarget.useBWIRegs())
1276       setOperationAction(ISD::ROTL,            MVT::v32i8,  Custom);
1277 
1278     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1279     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1280     setOperationAction(ISD::SELECT,            MVT::v8i32, Custom);
1281     setOperationAction(ISD::SELECT,            MVT::v16i16, Custom);
1282     setOperationAction(ISD::SELECT,            MVT::v32i8, Custom);
1283     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1284 
1285     for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1286       setOperationAction(ISD::SIGN_EXTEND,     VT, Custom);
1287       setOperationAction(ISD::ZERO_EXTEND,     VT, Custom);
1288       setOperationAction(ISD::ANY_EXTEND,      VT, Custom);
1289     }
1290 
1291     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1292     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1293     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1294     setOperationAction(ISD::BITREVERSE,        MVT::v32i8, Custom);
1295 
1296     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1297       setOperationAction(ISD::SETCC,           VT, Custom);
1298       setOperationAction(ISD::STRICT_FSETCC,   VT, Custom);
1299       setOperationAction(ISD::STRICT_FSETCCS,  VT, Custom);
1300       setOperationAction(ISD::CTPOP,           VT, Custom);
1301       setOperationAction(ISD::CTLZ,            VT, Custom);
1302 
1303       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1304       // setcc all the way to isel and prefer SETGT in some isel patterns.
1305       setCondCodeAction(ISD::SETLT, VT, Custom);
1306       setCondCodeAction(ISD::SETLE, VT, Custom);
1307     }
1308 
1309     if (Subtarget.hasAnyFMA()) {
1310       for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1311                        MVT::v2f64, MVT::v4f64 }) {
1312         setOperationAction(ISD::FMA, VT, Legal);
1313         setOperationAction(ISD::STRICT_FMA, VT, Legal);
1314       }
1315     }
1316 
1317     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1318       setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1319       setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1320     }
1321 
1322     setOperationAction(ISD::MUL,       MVT::v4i64,  Custom);
1323     setOperationAction(ISD::MUL,       MVT::v8i32,  HasInt256 ? Legal : Custom);
1324     setOperationAction(ISD::MUL,       MVT::v16i16, HasInt256 ? Legal : Custom);
1325     setOperationAction(ISD::MUL,       MVT::v32i8,  Custom);
1326 
1327     setOperationAction(ISD::MULHU,     MVT::v8i32,  Custom);
1328     setOperationAction(ISD::MULHS,     MVT::v8i32,  Custom);
1329     setOperationAction(ISD::MULHU,     MVT::v16i16, HasInt256 ? Legal : Custom);
1330     setOperationAction(ISD::MULHS,     MVT::v16i16, HasInt256 ? Legal : Custom);
1331     setOperationAction(ISD::MULHU,     MVT::v32i8,  Custom);
1332     setOperationAction(ISD::MULHS,     MVT::v32i8,  Custom);
1333 
1334     setOperationAction(ISD::ABS,       MVT::v4i64,  Custom);
1335     setOperationAction(ISD::SMAX,      MVT::v4i64,  Custom);
1336     setOperationAction(ISD::UMAX,      MVT::v4i64,  Custom);
1337     setOperationAction(ISD::SMIN,      MVT::v4i64,  Custom);
1338     setOperationAction(ISD::UMIN,      MVT::v4i64,  Custom);
1339 
1340     setOperationAction(ISD::UADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1341     setOperationAction(ISD::SADDSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1342     setOperationAction(ISD::USUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1343     setOperationAction(ISD::SSUBSAT,   MVT::v32i8,  HasInt256 ? Legal : Custom);
1344     setOperationAction(ISD::UADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1345     setOperationAction(ISD::SADDSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1346     setOperationAction(ISD::USUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1347     setOperationAction(ISD::SSUBSAT,   MVT::v16i16, HasInt256 ? Legal : Custom);
1348     setOperationAction(ISD::UADDSAT,   MVT::v8i32, Custom);
1349     setOperationAction(ISD::USUBSAT,   MVT::v8i32, Custom);
1350     setOperationAction(ISD::UADDSAT,   MVT::v4i64, Custom);
1351     setOperationAction(ISD::USUBSAT,   MVT::v4i64, Custom);
1352 
1353     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1354       setOperationAction(ISD::ABS,  VT, HasInt256 ? Legal : Custom);
1355       setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1356       setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1357       setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1358       setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1359     }
1360 
1361     for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1362       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1363       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1364     }
1365 
1366     if (HasInt256) {
1367       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1368       // when we have a 256bit-wide blend with immediate.
1369       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1370       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32, Custom);
1371 
1372       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1373       for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1374         setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1375         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i8,  Legal);
1376         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i8,  Legal);
1377         setLoadExtAction(LoadExtOp, MVT::v8i32,  MVT::v8i16, Legal);
1378         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i16, Legal);
1379         setLoadExtAction(LoadExtOp, MVT::v4i64,  MVT::v4i32, Legal);
1380       }
1381     }
1382 
1383     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1384                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1385       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1386       setOperationAction(ISD::MSTORE, VT, Legal);
1387     }
1388 
1389     // Extract subvector is special because the value type
1390     // (result) is 128-bit but the source is 256-bit wide.
1391     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1392                      MVT::v4f32, MVT::v2f64 }) {
1393       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1394     }
1395 
1396     // Custom lower several nodes for 256-bit types.
1397     for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1398                     MVT::v8f32, MVT::v4f64 }) {
1399       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1400       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1401       setOperationAction(ISD::VSELECT,            VT, Custom);
1402       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1403       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1404       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1405       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1406       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1407       setOperationAction(ISD::STORE,              VT, Custom);
1408     }
1409 
1410     if (HasInt256) {
1411       setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1412 
1413       // Custom legalize 2x32 to get a little better code.
1414       setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1415       setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1416 
1417       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1418                        MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1419         setOperationAction(ISD::MGATHER,  VT, Custom);
1420     }
1421   }
1422 
1423   // This block controls legalization of the mask vector sizes that are
1424   // available with AVX512. 512-bit vectors are in a separate block controlled
1425   // by useAVX512Regs.
1426   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1427     addRegisterClass(MVT::v1i1,   &X86::VK1RegClass);
1428     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1429     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1430     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1431     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1432 
1433     setOperationAction(ISD::SELECT,             MVT::v1i1, Custom);
1434     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1435     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i1, Custom);
1436 
1437     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v8i1,  MVT::v8i32);
1438     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v8i1,  MVT::v8i32);
1439     setOperationPromotedToType(ISD::FP_TO_SINT,        MVT::v4i1,  MVT::v4i32);
1440     setOperationPromotedToType(ISD::FP_TO_UINT,        MVT::v4i1,  MVT::v4i32);
1441     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v8i1,  MVT::v8i32);
1442     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v8i1,  MVT::v8i32);
1443     setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::v4i1,  MVT::v4i32);
1444     setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::v4i1,  MVT::v4i32);
1445     setOperationAction(ISD::FP_TO_SINT,                MVT::v2i1,  Custom);
1446     setOperationAction(ISD::FP_TO_UINT,                MVT::v2i1,  Custom);
1447     setOperationAction(ISD::STRICT_FP_TO_SINT,         MVT::v2i1,  Custom);
1448     setOperationAction(ISD::STRICT_FP_TO_UINT,         MVT::v2i1,  Custom);
1449 
1450     // There is no byte sized k-register load or store without AVX512DQ.
1451     if (!Subtarget.hasDQI()) {
1452       setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1453       setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1454       setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1455       setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1456 
1457       setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1458       setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1459       setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1460       setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1461     }
1462 
1463     // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1464     for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1465       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1466       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1467       setOperationAction(ISD::ANY_EXTEND,  VT, Custom);
1468     }
1469 
1470     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1471       setOperationAction(ISD::ADD,              VT, Custom);
1472       setOperationAction(ISD::SUB,              VT, Custom);
1473       setOperationAction(ISD::MUL,              VT, Custom);
1474       setOperationAction(ISD::UADDSAT,          VT, Custom);
1475       setOperationAction(ISD::SADDSAT,          VT, Custom);
1476       setOperationAction(ISD::USUBSAT,          VT, Custom);
1477       setOperationAction(ISD::SSUBSAT,          VT, Custom);
1478       setOperationAction(ISD::VSELECT,          VT,  Expand);
1479     }
1480 
1481     for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1482       setOperationAction(ISD::SETCC,            VT, Custom);
1483       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1484       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1485       setOperationAction(ISD::SELECT,           VT, Custom);
1486       setOperationAction(ISD::TRUNCATE,         VT, Custom);
1487 
1488       setOperationAction(ISD::BUILD_VECTOR,     VT, Custom);
1489       setOperationAction(ISD::CONCAT_VECTORS,   VT, Custom);
1490       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1491       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1492       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1493       setOperationAction(ISD::VECTOR_SHUFFLE,   VT,  Custom);
1494     }
1495 
1496     for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1497       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1498   }
1499 
1500   // This block controls legalization for 512-bit operations with 32/64 bit
1501   // elements. 512-bits can be disabled based on prefer-vector-width and
1502   // required-vector-width function attributes.
1503   if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1504     bool HasBWI = Subtarget.hasBWI();
1505 
1506     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1507     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1508     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1509     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1510     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1511     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1512 
1513     for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1514       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8,  Legal);
1515       setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1516       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i8,   Legal);
1517       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i16,  Legal);
1518       setLoadExtAction(ExtType, MVT::v8i64,  MVT::v8i32,  Legal);
1519       if (HasBWI)
1520         setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1521     }
1522 
1523     for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1524       setOperationAction(ISD::FNEG,  VT, Custom);
1525       setOperationAction(ISD::FABS,  VT, Custom);
1526       setOperationAction(ISD::FMA,   VT, Legal);
1527       setOperationAction(ISD::STRICT_FMA, VT, Legal);
1528       setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1529     }
1530 
1531     for (MVT VT : { MVT::v16i1, MVT::v16i8, MVT::v16i16 }) {
1532       setOperationPromotedToType(ISD::FP_TO_SINT       , VT, MVT::v16i32);
1533       setOperationPromotedToType(ISD::FP_TO_UINT       , VT, MVT::v16i32);
1534       setOperationPromotedToType(ISD::STRICT_FP_TO_SINT, VT, MVT::v16i32);
1535       setOperationPromotedToType(ISD::STRICT_FP_TO_UINT, VT, MVT::v16i32);
1536     }
1537     setOperationAction(ISD::FP_TO_SINT,        MVT::v16i32, Legal);
1538     setOperationAction(ISD::FP_TO_UINT,        MVT::v16i32, Legal);
1539     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v16i32, Legal);
1540     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v16i32, Legal);
1541     setOperationAction(ISD::SINT_TO_FP,        MVT::v16i32, Legal);
1542     setOperationAction(ISD::UINT_TO_FP,        MVT::v16i32, Legal);
1543     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v16i32, Legal);
1544     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v16i32, Legal);
1545 
1546     setOperationAction(ISD::STRICT_FADD,      MVT::v16f32, Legal);
1547     setOperationAction(ISD::STRICT_FADD,      MVT::v8f64,  Legal);
1548     setOperationAction(ISD::STRICT_FSUB,      MVT::v16f32, Legal);
1549     setOperationAction(ISD::STRICT_FSUB,      MVT::v8f64,  Legal);
1550     setOperationAction(ISD::STRICT_FMUL,      MVT::v16f32, Legal);
1551     setOperationAction(ISD::STRICT_FMUL,      MVT::v8f64,  Legal);
1552     setOperationAction(ISD::STRICT_FDIV,      MVT::v16f32, Legal);
1553     setOperationAction(ISD::STRICT_FDIV,      MVT::v8f64,  Legal);
1554     setOperationAction(ISD::STRICT_FSQRT,     MVT::v16f32, Legal);
1555     setOperationAction(ISD::STRICT_FSQRT,     MVT::v8f64,  Legal);
1556     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::v8f64,  Legal);
1557     setOperationAction(ISD::STRICT_FP_ROUND,  MVT::v8f32,  Legal);
1558 
1559     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1560     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1561     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1562     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1563     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1564     if (HasBWI)
1565       setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1566 
1567     // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1568     // to 512-bit rather than use the AVX2 instructions so that we can use
1569     // k-masks.
1570     if (!Subtarget.hasVLX()) {
1571       for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1572            MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1573         setOperationAction(ISD::MLOAD,  VT, Custom);
1574         setOperationAction(ISD::MSTORE, VT, Custom);
1575       }
1576     }
1577 
1578     setOperationAction(ISD::TRUNCATE,    MVT::v8i32,  Legal);
1579     setOperationAction(ISD::TRUNCATE,    MVT::v16i16, Legal);
1580     setOperationAction(ISD::TRUNCATE,    MVT::v32i8,  HasBWI ? Legal : Custom);
1581     setOperationAction(ISD::TRUNCATE,    MVT::v16i64, Custom);
1582     setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1583     setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1584     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64,  Custom);
1585     setOperationAction(ISD::ANY_EXTEND,  MVT::v32i16, Custom);
1586     setOperationAction(ISD::ANY_EXTEND,  MVT::v16i32, Custom);
1587     setOperationAction(ISD::ANY_EXTEND,  MVT::v8i64,  Custom);
1588     setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1589     setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1590     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64,  Custom);
1591 
1592     if (HasBWI) {
1593       // Extends from v64i1 masks to 512-bit vectors.
1594       setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1595       setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1596       setOperationAction(ISD::ANY_EXTEND,         MVT::v64i8, Custom);
1597     }
1598 
1599     for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1600       setOperationAction(ISD::FFLOOR,            VT, Legal);
1601       setOperationAction(ISD::STRICT_FFLOOR,     VT, Legal);
1602       setOperationAction(ISD::FCEIL,             VT, Legal);
1603       setOperationAction(ISD::STRICT_FCEIL,      VT, Legal);
1604       setOperationAction(ISD::FTRUNC,            VT, Legal);
1605       setOperationAction(ISD::STRICT_FTRUNC,     VT, Legal);
1606       setOperationAction(ISD::FRINT,             VT, Legal);
1607       setOperationAction(ISD::STRICT_FRINT,      VT, Legal);
1608       setOperationAction(ISD::FNEARBYINT,        VT, Legal);
1609       setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
1610       setOperationAction(ISD::FROUNDEVEN,        VT, Legal);
1611       setOperationAction(ISD::STRICT_FROUNDEVEN, VT, Legal);
1612 
1613       setOperationAction(ISD::FROUND,            VT, Custom);
1614     }
1615 
1616     for (auto VT : {MVT::v32i16, MVT::v16i32, MVT::v8i64}) {
1617       setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1618       setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1619     }
1620 
1621     setOperationAction(ISD::ADD, MVT::v32i16, HasBWI ? Legal : Custom);
1622     setOperationAction(ISD::SUB, MVT::v32i16, HasBWI ? Legal : Custom);
1623     setOperationAction(ISD::ADD, MVT::v64i8,  HasBWI ? Legal : Custom);
1624     setOperationAction(ISD::SUB, MVT::v64i8,  HasBWI ? Legal : Custom);
1625 
1626     setOperationAction(ISD::MUL, MVT::v8i64,  Custom);
1627     setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1628     setOperationAction(ISD::MUL, MVT::v32i16, HasBWI ? Legal : Custom);
1629     setOperationAction(ISD::MUL, MVT::v64i8,  Custom);
1630 
1631     setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1632     setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1633     setOperationAction(ISD::MULHS, MVT::v32i16, HasBWI ? Legal : Custom);
1634     setOperationAction(ISD::MULHU, MVT::v32i16, HasBWI ? Legal : Custom);
1635     setOperationAction(ISD::MULHS, MVT::v64i8,  Custom);
1636     setOperationAction(ISD::MULHU, MVT::v64i8,  Custom);
1637 
1638     setOperationAction(ISD::BITREVERSE, MVT::v64i8,  Custom);
1639 
1640     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1641       setOperationAction(ISD::SRL,              VT, Custom);
1642       setOperationAction(ISD::SHL,              VT, Custom);
1643       setOperationAction(ISD::SRA,              VT, Custom);
1644       setOperationAction(ISD::SETCC,            VT, Custom);
1645 
1646       // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1647       // setcc all the way to isel and prefer SETGT in some isel patterns.
1648       setCondCodeAction(ISD::SETLT, VT, Custom);
1649       setCondCodeAction(ISD::SETLE, VT, Custom);
1650     }
1651     for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1652       setOperationAction(ISD::SMAX,             VT, Legal);
1653       setOperationAction(ISD::UMAX,             VT, Legal);
1654       setOperationAction(ISD::SMIN,             VT, Legal);
1655       setOperationAction(ISD::UMIN,             VT, Legal);
1656       setOperationAction(ISD::ABS,              VT, Legal);
1657       setOperationAction(ISD::CTPOP,            VT, Custom);
1658       setOperationAction(ISD::ROTL,             VT, Custom);
1659       setOperationAction(ISD::ROTR,             VT, Custom);
1660       setOperationAction(ISD::STRICT_FSETCC,    VT, Custom);
1661       setOperationAction(ISD::STRICT_FSETCCS,   VT, Custom);
1662     }
1663 
1664     for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1665       setOperationAction(ISD::ABS,     VT, HasBWI ? Legal : Custom);
1666       setOperationAction(ISD::CTPOP,   VT, Subtarget.hasBITALG() ? Legal : Custom);
1667       setOperationAction(ISD::CTLZ,    VT, Custom);
1668       setOperationAction(ISD::SMAX,    VT, HasBWI ? Legal : Custom);
1669       setOperationAction(ISD::UMAX,    VT, HasBWI ? Legal : Custom);
1670       setOperationAction(ISD::SMIN,    VT, HasBWI ? Legal : Custom);
1671       setOperationAction(ISD::UMIN,    VT, HasBWI ? Legal : Custom);
1672       setOperationAction(ISD::UADDSAT, VT, HasBWI ? Legal : Custom);
1673       setOperationAction(ISD::SADDSAT, VT, HasBWI ? Legal : Custom);
1674       setOperationAction(ISD::USUBSAT, VT, HasBWI ? Legal : Custom);
1675       setOperationAction(ISD::SSUBSAT, VT, HasBWI ? Legal : Custom);
1676     }
1677 
1678     if (Subtarget.hasDQI()) {
1679       setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1680       setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1681       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v8i64, Legal);
1682       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i64, Legal);
1683       setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1684       setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1685       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v8i64, Legal);
1686       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i64, Legal);
1687 
1688       setOperationAction(ISD::MUL,        MVT::v8i64, Legal);
1689     }
1690 
1691     if (Subtarget.hasCDI()) {
1692       // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1693       for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1694         setOperationAction(ISD::CTLZ,            VT, Legal);
1695       }
1696     } // Subtarget.hasCDI()
1697 
1698     if (Subtarget.hasVPOPCNTDQ()) {
1699       for (auto VT : { MVT::v16i32, MVT::v8i64 })
1700         setOperationAction(ISD::CTPOP, VT, Legal);
1701     }
1702 
1703     // Extract subvector is special because the value type
1704     // (result) is 256-bit but the source is 512-bit wide.
1705     // 128-bit was made Legal under AVX1.
1706     for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1707                      MVT::v8f32, MVT::v4f64 })
1708       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1709 
1710     for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32, MVT::v8i64,
1711                      MVT::v16f32, MVT::v8f64 }) {
1712       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1713       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Legal);
1714       setOperationAction(ISD::SELECT,             VT, Custom);
1715       setOperationAction(ISD::VSELECT,            VT, Custom);
1716       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1717       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1718       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1719       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1720       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1721     }
1722 
1723     for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1724       setOperationAction(ISD::MLOAD,               VT, Legal);
1725       setOperationAction(ISD::MSTORE,              VT, Legal);
1726       setOperationAction(ISD::MGATHER,             VT, Custom);
1727       setOperationAction(ISD::MSCATTER,            VT, Custom);
1728     }
1729     if (HasBWI) {
1730       for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1731         setOperationAction(ISD::MLOAD,        VT, Legal);
1732         setOperationAction(ISD::MSTORE,       VT, Legal);
1733       }
1734     } else {
1735       setOperationAction(ISD::STORE, MVT::v32i16, Custom);
1736       setOperationAction(ISD::STORE, MVT::v64i8,  Custom);
1737     }
1738 
1739     if (Subtarget.hasVBMI2()) {
1740       for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1741                        MVT::v16i16, MVT::v8i32, MVT::v4i64,
1742                        MVT::v32i16, MVT::v16i32, MVT::v8i64 }) {
1743         setOperationAction(ISD::FSHL, VT, Custom);
1744         setOperationAction(ISD::FSHR, VT, Custom);
1745       }
1746 
1747       setOperationAction(ISD::ROTL, MVT::v32i16, Custom);
1748       setOperationAction(ISD::ROTR, MVT::v8i16,  Custom);
1749       setOperationAction(ISD::ROTR, MVT::v16i16, Custom);
1750       setOperationAction(ISD::ROTR, MVT::v32i16, Custom);
1751     }
1752   }// useAVX512Regs
1753 
1754   // This block controls legalization for operations that don't have
1755   // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1756   // narrower widths.
1757   if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1758     // These operations are handled on non-VLX by artificially widening in
1759     // isel patterns.
1760 
1761     setOperationAction(ISD::FP_TO_UINT, MVT::v8i32,
1762                        Subtarget.hasVLX() ? Legal : Custom);
1763     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32,
1764                        Subtarget.hasVLX() ? Legal : Custom);
1765     setOperationAction(ISD::FP_TO_UINT,         MVT::v2i32, Custom);
1766     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v8i32,
1767                        Subtarget.hasVLX() ? Legal : Custom);
1768     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32,
1769                        Subtarget.hasVLX() ? Legal : Custom);
1770     setOperationAction(ISD::STRICT_FP_TO_UINT,  MVT::v2i32, Custom);
1771     setOperationAction(ISD::UINT_TO_FP, MVT::v8i32,
1772                        Subtarget.hasVLX() ? Legal : Custom);
1773     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32,
1774                        Subtarget.hasVLX() ? Legal : Custom);
1775     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v8i32,
1776                        Subtarget.hasVLX() ? Legal : Custom);
1777     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32,
1778                        Subtarget.hasVLX() ? Legal : Custom);
1779 
1780     if (Subtarget.hasDQI()) {
1781       // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1782       // v2f32 UINT_TO_FP is already custom under SSE2.
1783       assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&
1784              isOperationCustom(ISD::STRICT_UINT_TO_FP, MVT::v2f32) &&
1785              "Unexpected operation action!");
1786       // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1787       setOperationAction(ISD::FP_TO_SINT,        MVT::v2f32, Custom);
1788       setOperationAction(ISD::FP_TO_UINT,        MVT::v2f32, Custom);
1789       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f32, Custom);
1790       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f32, Custom);
1791     }
1792 
1793     for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1794       setOperationAction(ISD::SMAX, VT, Legal);
1795       setOperationAction(ISD::UMAX, VT, Legal);
1796       setOperationAction(ISD::SMIN, VT, Legal);
1797       setOperationAction(ISD::UMIN, VT, Legal);
1798       setOperationAction(ISD::ABS,  VT, Legal);
1799     }
1800 
1801     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1802       setOperationAction(ISD::ROTL,     VT, Custom);
1803       setOperationAction(ISD::ROTR,     VT, Custom);
1804     }
1805 
1806     // Custom legalize 2x32 to get a little better code.
1807     setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1808     setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1809 
1810     for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1811                      MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1812       setOperationAction(ISD::MSCATTER, VT, Custom);
1813 
1814     if (Subtarget.hasDQI()) {
1815       for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1816         setOperationAction(ISD::SINT_TO_FP, VT,
1817                            Subtarget.hasVLX() ? Legal : Custom);
1818         setOperationAction(ISD::UINT_TO_FP, VT,
1819                            Subtarget.hasVLX() ? Legal : Custom);
1820         setOperationAction(ISD::STRICT_SINT_TO_FP, VT,
1821                            Subtarget.hasVLX() ? Legal : Custom);
1822         setOperationAction(ISD::STRICT_UINT_TO_FP, VT,
1823                            Subtarget.hasVLX() ? Legal : Custom);
1824         setOperationAction(ISD::FP_TO_SINT, VT,
1825                            Subtarget.hasVLX() ? Legal : Custom);
1826         setOperationAction(ISD::FP_TO_UINT, VT,
1827                            Subtarget.hasVLX() ? Legal : Custom);
1828         setOperationAction(ISD::STRICT_FP_TO_SINT, VT,
1829                            Subtarget.hasVLX() ? Legal : Custom);
1830         setOperationAction(ISD::STRICT_FP_TO_UINT, VT,
1831                            Subtarget.hasVLX() ? Legal : Custom);
1832         setOperationAction(ISD::MUL,               VT, Legal);
1833       }
1834     }
1835 
1836     if (Subtarget.hasCDI()) {
1837       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1838         setOperationAction(ISD::CTLZ,            VT, Legal);
1839       }
1840     } // Subtarget.hasCDI()
1841 
1842     if (Subtarget.hasVPOPCNTDQ()) {
1843       for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1844         setOperationAction(ISD::CTPOP, VT, Legal);
1845     }
1846   }
1847 
1848   // This block control legalization of v32i1/v64i1 which are available with
1849   // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1850   // useBWIRegs.
1851   if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1852     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1853     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1854 
1855     for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1856       setOperationAction(ISD::ADD,                VT, Custom);
1857       setOperationAction(ISD::SUB,                VT, Custom);
1858       setOperationAction(ISD::MUL,                VT, Custom);
1859       setOperationAction(ISD::VSELECT,            VT, Expand);
1860       setOperationAction(ISD::UADDSAT,            VT, Custom);
1861       setOperationAction(ISD::SADDSAT,            VT, Custom);
1862       setOperationAction(ISD::USUBSAT,            VT, Custom);
1863       setOperationAction(ISD::SSUBSAT,            VT, Custom);
1864 
1865       setOperationAction(ISD::TRUNCATE,           VT, Custom);
1866       setOperationAction(ISD::SETCC,              VT, Custom);
1867       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1868       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1869       setOperationAction(ISD::SELECT,             VT, Custom);
1870       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1871       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1872       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1873       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1874     }
1875 
1876     for (auto VT : { MVT::v16i1, MVT::v32i1 })
1877       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1878 
1879     // Extends from v32i1 masks to 256-bit vectors.
1880     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1881     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1882     setOperationAction(ISD::ANY_EXTEND,         MVT::v32i8, Custom);
1883 
1884     for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1885       setOperationAction(ISD::MLOAD,  VT, Subtarget.hasVLX() ? Legal : Custom);
1886       setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1887     }
1888 
1889     // These operations are handled on non-VLX by artificially widening in
1890     // isel patterns.
1891     // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1892 
1893     if (Subtarget.hasBITALG()) {
1894       for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1895         setOperationAction(ISD::CTPOP, VT, Legal);
1896     }
1897   }
1898 
1899   if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1900     setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1901     setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1902     setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1903     setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1904     setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1905 
1906     setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1907     setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1908     setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1909     setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1910     setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1911 
1912     if (Subtarget.hasBWI()) {
1913       setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1914       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1915     }
1916 
1917     setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
1918     setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
1919     setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1920   }
1921 
1922   if (Subtarget.hasAMXTILE()) {
1923     addRegisterClass(MVT::x86amx, &X86::TILERegClass);
1924   }
1925 
1926   // We want to custom lower some of our intrinsics.
1927   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1928   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1929   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1930   if (!Subtarget.is64Bit()) {
1931     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1932   }
1933 
1934   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1935   // handle type legalization for these operations here.
1936   //
1937   // FIXME: We really should do custom legalization for addition and
1938   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1939   // than generic legalization for 64-bit multiplication-with-overflow, though.
1940   for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1941     if (VT == MVT::i64 && !Subtarget.is64Bit())
1942       continue;
1943     // Add/Sub/Mul with overflow operations are custom lowered.
1944     setOperationAction(ISD::SADDO, VT, Custom);
1945     setOperationAction(ISD::UADDO, VT, Custom);
1946     setOperationAction(ISD::SSUBO, VT, Custom);
1947     setOperationAction(ISD::USUBO, VT, Custom);
1948     setOperationAction(ISD::SMULO, VT, Custom);
1949     setOperationAction(ISD::UMULO, VT, Custom);
1950 
1951     // Support carry in as value rather than glue.
1952     setOperationAction(ISD::ADDCARRY, VT, Custom);
1953     setOperationAction(ISD::SUBCARRY, VT, Custom);
1954     setOperationAction(ISD::SETCCCARRY, VT, Custom);
1955     setOperationAction(ISD::SADDO_CARRY, VT, Custom);
1956     setOperationAction(ISD::SSUBO_CARRY, VT, Custom);
1957   }
1958 
1959   if (!Subtarget.is64Bit()) {
1960     // These libcalls are not available in 32-bit.
1961     setLibcallName(RTLIB::SHL_I128, nullptr);
1962     setLibcallName(RTLIB::SRL_I128, nullptr);
1963     setLibcallName(RTLIB::SRA_I128, nullptr);
1964     setLibcallName(RTLIB::MUL_I128, nullptr);
1965   }
1966 
1967   // Combine sin / cos into _sincos_stret if it is available.
1968   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1969       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1970     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1971     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1972   }
1973 
1974   if (Subtarget.isTargetWin64()) {
1975     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1976     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1977     setOperationAction(ISD::SREM, MVT::i128, Custom);
1978     setOperationAction(ISD::UREM, MVT::i128, Custom);
1979   }
1980 
1981   // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1982   // is. We should promote the value to 64-bits to solve this.
1983   // This is what the CRT headers do - `fmodf` is an inline header
1984   // function casting to f64 and calling `fmod`.
1985   if (Subtarget.is32Bit() &&
1986       (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
1987     for (ISD::NodeType Op :
1988          {ISD::FCEIL,  ISD::STRICT_FCEIL,
1989           ISD::FCOS,   ISD::STRICT_FCOS,
1990           ISD::FEXP,   ISD::STRICT_FEXP,
1991           ISD::FFLOOR, ISD::STRICT_FFLOOR,
1992           ISD::FREM,   ISD::STRICT_FREM,
1993           ISD::FLOG,   ISD::STRICT_FLOG,
1994           ISD::FLOG10, ISD::STRICT_FLOG10,
1995           ISD::FPOW,   ISD::STRICT_FPOW,
1996           ISD::FSIN,   ISD::STRICT_FSIN})
1997       if (isOperationExpand(Op, MVT::f32))
1998         setOperationAction(Op, MVT::f32, Promote);
1999 
2000   // We have target-specific dag combine patterns for the following nodes:
2001   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
2002   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
2003   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
2004   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
2005   setTargetDAGCombine(ISD::CONCAT_VECTORS);
2006   setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
2007   setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
2008   setTargetDAGCombine(ISD::BITCAST);
2009   setTargetDAGCombine(ISD::VSELECT);
2010   setTargetDAGCombine(ISD::SELECT);
2011   setTargetDAGCombine(ISD::SHL);
2012   setTargetDAGCombine(ISD::SRA);
2013   setTargetDAGCombine(ISD::SRL);
2014   setTargetDAGCombine(ISD::OR);
2015   setTargetDAGCombine(ISD::AND);
2016   setTargetDAGCombine(ISD::ADD);
2017   setTargetDAGCombine(ISD::FADD);
2018   setTargetDAGCombine(ISD::FSUB);
2019   setTargetDAGCombine(ISD::FNEG);
2020   setTargetDAGCombine(ISD::FMA);
2021   setTargetDAGCombine(ISD::STRICT_FMA);
2022   setTargetDAGCombine(ISD::FMINNUM);
2023   setTargetDAGCombine(ISD::FMAXNUM);
2024   setTargetDAGCombine(ISD::SUB);
2025   setTargetDAGCombine(ISD::LOAD);
2026   setTargetDAGCombine(ISD::MLOAD);
2027   setTargetDAGCombine(ISD::STORE);
2028   setTargetDAGCombine(ISD::MSTORE);
2029   setTargetDAGCombine(ISD::TRUNCATE);
2030   setTargetDAGCombine(ISD::ZERO_EXTEND);
2031   setTargetDAGCombine(ISD::ANY_EXTEND);
2032   setTargetDAGCombine(ISD::SIGN_EXTEND);
2033   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
2034   setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
2035   setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
2036   setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
2037   setTargetDAGCombine(ISD::SINT_TO_FP);
2038   setTargetDAGCombine(ISD::UINT_TO_FP);
2039   setTargetDAGCombine(ISD::STRICT_SINT_TO_FP);
2040   setTargetDAGCombine(ISD::STRICT_UINT_TO_FP);
2041   setTargetDAGCombine(ISD::SETCC);
2042   setTargetDAGCombine(ISD::MUL);
2043   setTargetDAGCombine(ISD::XOR);
2044   setTargetDAGCombine(ISD::MSCATTER);
2045   setTargetDAGCombine(ISD::MGATHER);
2046   setTargetDAGCombine(ISD::FP16_TO_FP);
2047   setTargetDAGCombine(ISD::FP_EXTEND);
2048   setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
2049   setTargetDAGCombine(ISD::FP_ROUND);
2050 
2051   computeRegisterProperties(Subtarget.getRegisterInfo());
2052 
2053   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
2054   MaxStoresPerMemsetOptSize = 8;
2055   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
2056   MaxStoresPerMemcpyOptSize = 4;
2057   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
2058   MaxStoresPerMemmoveOptSize = 4;
2059 
2060   // TODO: These control memcmp expansion in CGP and could be raised higher, but
2061   // that needs to benchmarked and balanced with the potential use of vector
2062   // load/store types (PR33329, PR33914).
2063   MaxLoadsPerMemcmp = 2;
2064   MaxLoadsPerMemcmpOptSize = 2;
2065 
2066   // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
2067   setPrefLoopAlignment(Align(1ULL << ExperimentalPrefLoopAlignment));
2068 
2069   // An out-of-order CPU can speculatively execute past a predictable branch,
2070   // but a conditional move could be stalled by an expensive earlier operation.
2071   PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
2072   EnableExtLdPromotion = true;
2073   setPrefFunctionAlignment(Align(16));
2074 
2075   verifyIntrinsicTables();
2076 
2077   // Default to having -disable-strictnode-mutation on
2078   IsStrictFPEnabled = true;
2079 }
2080 
2081 // This has so far only been implemented for 64-bit MachO.
2082 bool X86TargetLowering::useLoadStackGuardNode() const {
2083   return Subtarget.isTargetMachO() && Subtarget.is64Bit();
2084 }
2085 
2086 bool X86TargetLowering::useStackGuardXorFP() const {
2087   // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
2088   return Subtarget.getTargetTriple().isOSMSVCRT() && !Subtarget.isTargetMachO();
2089 }
2090 
2091 SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
2092                                                const SDLoc &DL) const {
2093   EVT PtrTy = getPointerTy(DAG.getDataLayout());
2094   unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
2095   MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
2096   return SDValue(Node, 0);
2097 }
2098 
2099 TargetLoweringBase::LegalizeTypeAction
2100 X86TargetLowering::getPreferredVectorAction(MVT VT) const {
2101   if ((VT == MVT::v32i1 || VT == MVT::v64i1) && Subtarget.hasAVX512() &&
2102       !Subtarget.hasBWI())
2103     return TypeSplitVector;
2104 
2105   if (VT.getVectorNumElements() != 1 &&
2106       VT.getVectorElementType() != MVT::i1)
2107     return TypeWidenVector;
2108 
2109   return TargetLoweringBase::getPreferredVectorAction(VT);
2110 }
2111 
2112 static std::pair<MVT, unsigned>
2113 handleMaskRegisterForCallingConv(unsigned NumElts, CallingConv::ID CC,
2114                                  const X86Subtarget &Subtarget) {
2115   // v2i1/v4i1/v8i1/v16i1 all pass in xmm registers unless the calling
2116   // convention is one that uses k registers.
2117   if (NumElts == 2)
2118     return {MVT::v2i64, 1};
2119   if (NumElts == 4)
2120     return {MVT::v4i32, 1};
2121   if (NumElts == 8 && CC != CallingConv::X86_RegCall &&
2122       CC != CallingConv::Intel_OCL_BI)
2123     return {MVT::v8i16, 1};
2124   if (NumElts == 16 && CC != CallingConv::X86_RegCall &&
2125       CC != CallingConv::Intel_OCL_BI)
2126     return {MVT::v16i8, 1};
2127   // v32i1 passes in ymm unless we have BWI and the calling convention is
2128   // regcall.
2129   if (NumElts == 32 && (!Subtarget.hasBWI() || CC != CallingConv::X86_RegCall))
2130     return {MVT::v32i8, 1};
2131   // Split v64i1 vectors if we don't have v64i8 available.
2132   if (NumElts == 64 && Subtarget.hasBWI() && CC != CallingConv::X86_RegCall) {
2133     if (Subtarget.useAVX512Regs())
2134       return {MVT::v64i8, 1};
2135     return {MVT::v32i8, 2};
2136   }
2137 
2138   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2139   if (!isPowerOf2_32(NumElts) || (NumElts == 64 && !Subtarget.hasBWI()) ||
2140       NumElts > 64)
2141     return {MVT::i8, NumElts};
2142 
2143   return {MVT::INVALID_SIMPLE_VALUE_TYPE, 0};
2144 }
2145 
2146 MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
2147                                                      CallingConv::ID CC,
2148                                                      EVT VT) const {
2149   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2150       Subtarget.hasAVX512()) {
2151     unsigned NumElts = VT.getVectorNumElements();
2152 
2153     MVT RegisterVT;
2154     unsigned NumRegisters;
2155     std::tie(RegisterVT, NumRegisters) =
2156         handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2157     if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2158       return RegisterVT;
2159   }
2160 
2161   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
2162 }
2163 
2164 unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
2165                                                           CallingConv::ID CC,
2166                                                           EVT VT) const {
2167   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2168       Subtarget.hasAVX512()) {
2169     unsigned NumElts = VT.getVectorNumElements();
2170 
2171     MVT RegisterVT;
2172     unsigned NumRegisters;
2173     std::tie(RegisterVT, NumRegisters) =
2174         handleMaskRegisterForCallingConv(NumElts, CC, Subtarget);
2175     if (RegisterVT != MVT::INVALID_SIMPLE_VALUE_TYPE)
2176       return NumRegisters;
2177   }
2178 
2179   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
2180 }
2181 
2182 unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
2183     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
2184     unsigned &NumIntermediates, MVT &RegisterVT) const {
2185   // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
2186   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
2187       Subtarget.hasAVX512() &&
2188       (!isPowerOf2_32(VT.getVectorNumElements()) ||
2189        (VT.getVectorNumElements() == 64 && !Subtarget.hasBWI()) ||
2190        VT.getVectorNumElements() > 64)) {
2191     RegisterVT = MVT::i8;
2192     IntermediateVT = MVT::i1;
2193     NumIntermediates = VT.getVectorNumElements();
2194     return NumIntermediates;
2195   }
2196 
2197   // Split v64i1 vectors if we don't have v64i8 available.
2198   if (VT == MVT::v64i1 && Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
2199       CC != CallingConv::X86_RegCall) {
2200     RegisterVT = MVT::v32i8;
2201     IntermediateVT = MVT::v32i1;
2202     NumIntermediates = 2;
2203     return 2;
2204   }
2205 
2206   return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
2207                                               NumIntermediates, RegisterVT);
2208 }
2209 
2210 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
2211                                           LLVMContext& Context,
2212                                           EVT VT) const {
2213   if (!VT.isVector())
2214     return MVT::i8;
2215 
2216   if (Subtarget.hasAVX512()) {
2217     const unsigned NumElts = VT.getVectorNumElements();
2218 
2219     // Figure out what this type will be legalized to.
2220     EVT LegalVT = VT;
2221     while (getTypeAction(Context, LegalVT) != TypeLegal)
2222       LegalVT = getTypeToTransformTo(Context, LegalVT);
2223 
2224     // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2225     if (LegalVT.getSimpleVT().is512BitVector())
2226       return EVT::getVectorVT(Context, MVT::i1, NumElts);
2227 
2228     if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2229       // If we legalized to less than a 512-bit vector, then we will use a vXi1
2230       // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2231       // vXi16/vXi8.
2232       MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2233       if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2234         return EVT::getVectorVT(Context, MVT::i1, NumElts);
2235     }
2236   }
2237 
2238   return VT.changeVectorElementTypeToInteger();
2239 }
2240 
2241 /// Helper for getByValTypeAlignment to determine
2242 /// the desired ByVal argument alignment.
2243 static void getMaxByValAlign(Type *Ty, Align &MaxAlign) {
2244   if (MaxAlign == 16)
2245     return;
2246   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2247     if (VTy->getPrimitiveSizeInBits().getFixedSize() == 128)
2248       MaxAlign = Align(16);
2249   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2250     Align EltAlign;
2251     getMaxByValAlign(ATy->getElementType(), EltAlign);
2252     if (EltAlign > MaxAlign)
2253       MaxAlign = EltAlign;
2254   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2255     for (auto *EltTy : STy->elements()) {
2256       Align EltAlign;
2257       getMaxByValAlign(EltTy, EltAlign);
2258       if (EltAlign > MaxAlign)
2259         MaxAlign = EltAlign;
2260       if (MaxAlign == 16)
2261         break;
2262     }
2263   }
2264 }
2265 
2266 /// Return the desired alignment for ByVal aggregate
2267 /// function arguments in the caller parameter area. For X86, aggregates
2268 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2269 /// are at 4-byte boundaries.
2270 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2271                                                   const DataLayout &DL) const {
2272   if (Subtarget.is64Bit()) {
2273     // Max of 8 and alignment of type.
2274     Align TyAlign = DL.getABITypeAlign(Ty);
2275     if (TyAlign > 8)
2276       return TyAlign.value();
2277     return 8;
2278   }
2279 
2280   Align Alignment(4);
2281   if (Subtarget.hasSSE1())
2282     getMaxByValAlign(Ty, Alignment);
2283   return Alignment.value();
2284 }
2285 
2286 /// It returns EVT::Other if the type should be determined using generic
2287 /// target-independent logic.
2288 /// For vector ops we check that the overall size isn't larger than our
2289 /// preferred vector width.
2290 EVT X86TargetLowering::getOptimalMemOpType(
2291     const MemOp &Op, const AttributeList &FuncAttributes) const {
2292   if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2293     if (Op.size() >= 16 &&
2294         (!Subtarget.isUnalignedMem16Slow() || Op.isAligned(Align(16)))) {
2295       // FIXME: Check if unaligned 64-byte accesses are slow.
2296       if (Op.size() >= 64 && Subtarget.hasAVX512() &&
2297           (Subtarget.getPreferVectorWidth() >= 512)) {
2298         return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2299       }
2300       // FIXME: Check if unaligned 32-byte accesses are slow.
2301       if (Op.size() >= 32 && Subtarget.hasAVX() &&
2302           (Subtarget.getPreferVectorWidth() >= 256)) {
2303         // Although this isn't a well-supported type for AVX1, we'll let
2304         // legalization and shuffle lowering produce the optimal codegen. If we
2305         // choose an optimal type with a vector element larger than a byte,
2306         // getMemsetStores() may create an intermediate splat (using an integer
2307         // multiply) before we splat as a vector.
2308         return MVT::v32i8;
2309       }
2310       if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2311         return MVT::v16i8;
2312       // TODO: Can SSE1 handle a byte vector?
2313       // If we have SSE1 registers we should be able to use them.
2314       if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2315           (Subtarget.getPreferVectorWidth() >= 128))
2316         return MVT::v4f32;
2317     } else if (((Op.isMemcpy() && !Op.isMemcpyStrSrc()) || Op.isZeroMemset()) &&
2318                Op.size() >= 8 && !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2319       // Do not use f64 to lower memcpy if source is string constant. It's
2320       // better to use i32 to avoid the loads.
2321       // Also, do not use f64 to lower memset unless this is a memset of zeros.
2322       // The gymnastics of splatting a byte value into an XMM register and then
2323       // only using 8-byte stores (because this is a CPU with slow unaligned
2324       // 16-byte accesses) makes that a loser.
2325       return MVT::f64;
2326     }
2327   }
2328   // This is a compromise. If we reach here, unaligned accesses may be slow on
2329   // this target. However, creating smaller, aligned accesses could be even
2330   // slower and would certainly be a lot more code.
2331   if (Subtarget.is64Bit() && Op.size() >= 8)
2332     return MVT::i64;
2333   return MVT::i32;
2334 }
2335 
2336 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2337   if (VT == MVT::f32)
2338     return X86ScalarSSEf32;
2339   else if (VT == MVT::f64)
2340     return X86ScalarSSEf64;
2341   return true;
2342 }
2343 
2344 bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2345     EVT VT, unsigned, unsigned Align, MachineMemOperand::Flags Flags,
2346     bool *Fast) const {
2347   if (Fast) {
2348     switch (VT.getSizeInBits()) {
2349     default:
2350       // 8-byte and under are always assumed to be fast.
2351       *Fast = true;
2352       break;
2353     case 128:
2354       *Fast = !Subtarget.isUnalignedMem16Slow();
2355       break;
2356     case 256:
2357       *Fast = !Subtarget.isUnalignedMem32Slow();
2358       break;
2359     // TODO: What about AVX-512 (512-bit) accesses?
2360     }
2361   }
2362   // NonTemporal vector memory ops must be aligned.
2363   if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2364     // NT loads can only be vector aligned, so if its less aligned than the
2365     // minimum vector size (which we can split the vector down to), we might as
2366     // well use a regular unaligned vector load.
2367     // We don't have any NT loads pre-SSE41.
2368     if (!!(Flags & MachineMemOperand::MOLoad))
2369       return (Align < 16 || !Subtarget.hasSSE41());
2370     return false;
2371   }
2372   // Misaligned accesses of any size are always allowed.
2373   return true;
2374 }
2375 
2376 /// Return the entry encoding for a jump table in the
2377 /// current function.  The returned value is a member of the
2378 /// MachineJumpTableInfo::JTEntryKind enum.
2379 unsigned X86TargetLowering::getJumpTableEncoding() const {
2380   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2381   // symbol.
2382   if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2383     return MachineJumpTableInfo::EK_Custom32;
2384 
2385   // Otherwise, use the normal jump table encoding heuristics.
2386   return TargetLowering::getJumpTableEncoding();
2387 }
2388 
2389 bool X86TargetLowering::useSoftFloat() const {
2390   return Subtarget.useSoftFloat();
2391 }
2392 
2393 void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2394                                               ArgListTy &Args) const {
2395 
2396   // Only relabel X86-32 for C / Stdcall CCs.
2397   if (Subtarget.is64Bit())
2398     return;
2399   if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2400     return;
2401   unsigned ParamRegs = 0;
2402   if (auto *M = MF->getFunction().getParent())
2403     ParamRegs = M->getNumberRegisterParameters();
2404 
2405   // Mark the first N int arguments as having reg
2406   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2407     Type *T = Args[Idx].Ty;
2408     if (T->isIntOrPtrTy())
2409       if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2410         unsigned numRegs = 1;
2411         if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2412           numRegs = 2;
2413         if (ParamRegs < numRegs)
2414           return;
2415         ParamRegs -= numRegs;
2416         Args[Idx].IsInReg = true;
2417       }
2418   }
2419 }
2420 
2421 const MCExpr *
2422 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2423                                              const MachineBasicBlock *MBB,
2424                                              unsigned uid,MCContext &Ctx) const{
2425   assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2426   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2427   // entries.
2428   return MCSymbolRefExpr::create(MBB->getSymbol(),
2429                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
2430 }
2431 
2432 /// Returns relocation base for the given PIC jumptable.
2433 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2434                                                     SelectionDAG &DAG) const {
2435   if (!Subtarget.is64Bit())
2436     // This doesn't have SDLoc associated with it, but is not really the
2437     // same as a Register.
2438     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2439                        getPointerTy(DAG.getDataLayout()));
2440   return Table;
2441 }
2442 
2443 /// This returns the relocation base for the given PIC jumptable,
2444 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2445 const MCExpr *X86TargetLowering::
2446 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2447                              MCContext &Ctx) const {
2448   // X86-64 uses RIP relative addressing based on the jump table label.
2449   if (Subtarget.isPICStyleRIPRel())
2450     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2451 
2452   // Otherwise, the reference is relative to the PIC base.
2453   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2454 }
2455 
2456 std::pair<const TargetRegisterClass *, uint8_t>
2457 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2458                                            MVT VT) const {
2459   const TargetRegisterClass *RRC = nullptr;
2460   uint8_t Cost = 1;
2461   switch (VT.SimpleTy) {
2462   default:
2463     return TargetLowering::findRepresentativeClass(TRI, VT);
2464   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2465     RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2466     break;
2467   case MVT::x86mmx:
2468     RRC = &X86::VR64RegClass;
2469     break;
2470   case MVT::f32: case MVT::f64:
2471   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2472   case MVT::v4f32: case MVT::v2f64:
2473   case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2474   case MVT::v8f32: case MVT::v4f64:
2475   case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2476   case MVT::v16f32: case MVT::v8f64:
2477     RRC = &X86::VR128XRegClass;
2478     break;
2479   }
2480   return std::make_pair(RRC, Cost);
2481 }
2482 
2483 unsigned X86TargetLowering::getAddressSpace() const {
2484   if (Subtarget.is64Bit())
2485     return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2486   return 256;
2487 }
2488 
2489 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2490   return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2491          (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2492 }
2493 
2494 static Constant* SegmentOffset(IRBuilder<> &IRB,
2495                                unsigned Offset, unsigned AddressSpace) {
2496   return ConstantExpr::getIntToPtr(
2497       ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2498       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2499 }
2500 
2501 Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2502   // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2503   // tcbhead_t; use it instead of the usual global variable (see
2504   // sysdeps/{i386,x86_64}/nptl/tls.h)
2505   if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2506     if (Subtarget.isTargetFuchsia()) {
2507       // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2508       return SegmentOffset(IRB, 0x10, getAddressSpace());
2509     } else {
2510       unsigned AddressSpace = getAddressSpace();
2511       // Specially, some users may customize the base reg and offset.
2512       unsigned Offset = getTargetMachine().Options.StackProtectorGuardOffset;
2513       // If we don't set -stack-protector-guard-offset value:
2514       // %fs:0x28, unless we're using a Kernel code model, in which case
2515       // it's %gs:0x28.  gs:0x14 on i386.
2516       if (Offset == (unsigned)-1)
2517         Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2518 
2519       const auto &GuardReg = getTargetMachine().Options.StackProtectorGuardReg;
2520       if (GuardReg == "fs")
2521         AddressSpace = X86AS::FS;
2522       else if (GuardReg == "gs")
2523         AddressSpace = X86AS::GS;
2524       return SegmentOffset(IRB, Offset, AddressSpace);
2525     }
2526   }
2527   return TargetLowering::getIRStackGuard(IRB);
2528 }
2529 
2530 void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2531   // MSVC CRT provides functionalities for stack protection.
2532   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2533       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2534     // MSVC CRT has a global variable holding security cookie.
2535     M.getOrInsertGlobal("__security_cookie",
2536                         Type::getInt8PtrTy(M.getContext()));
2537 
2538     // MSVC CRT has a function to validate security cookie.
2539     FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2540         "__security_check_cookie", Type::getVoidTy(M.getContext()),
2541         Type::getInt8PtrTy(M.getContext()));
2542     if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2543       F->setCallingConv(CallingConv::X86_FastCall);
2544       F->addAttribute(1, Attribute::AttrKind::InReg);
2545     }
2546     return;
2547   }
2548 
2549   auto GuardMode = getTargetMachine().Options.StackProtectorGuard;
2550 
2551   // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2552   if ((GuardMode == llvm::StackProtectorGuards::TLS ||
2553        GuardMode == llvm::StackProtectorGuards::None)
2554       && hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2555     return;
2556   TargetLowering::insertSSPDeclarations(M);
2557 }
2558 
2559 Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2560   // MSVC CRT has a global variable holding security cookie.
2561   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2562       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2563     return M.getGlobalVariable("__security_cookie");
2564   }
2565   return TargetLowering::getSDagStackGuard(M);
2566 }
2567 
2568 Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2569   // MSVC CRT has a function to validate security cookie.
2570   if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2571       Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2572     return M.getFunction("__security_check_cookie");
2573   }
2574   return TargetLowering::getSSPStackGuardCheck(M);
2575 }
2576 
2577 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2578   if (Subtarget.getTargetTriple().isOSContiki())
2579     return getDefaultSafeStackPointerLocation(IRB, false);
2580 
2581   // Android provides a fixed TLS slot for the SafeStack pointer. See the
2582   // definition of TLS_SLOT_SAFESTACK in
2583   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2584   if (Subtarget.isTargetAndroid()) {
2585     // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2586     // %gs:0x24 on i386
2587     unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2588     return SegmentOffset(IRB, Offset, getAddressSpace());
2589   }
2590 
2591   // Fuchsia is similar.
2592   if (Subtarget.isTargetFuchsia()) {
2593     // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2594     return SegmentOffset(IRB, 0x18, getAddressSpace());
2595   }
2596 
2597   return TargetLowering::getSafeStackPointerLocation(IRB);
2598 }
2599 
2600 //===----------------------------------------------------------------------===//
2601 //               Return Value Calling Convention Implementation
2602 //===----------------------------------------------------------------------===//
2603 
2604 bool X86TargetLowering::CanLowerReturn(
2605     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2606     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2607   SmallVector<CCValAssign, 16> RVLocs;
2608   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2609   return CCInfo.CheckReturn(Outs, RetCC_X86);
2610 }
2611 
2612 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2613   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2614   return ScratchRegs;
2615 }
2616 
2617 /// Lowers masks values (v*i1) to the local register values
2618 /// \returns DAG node after lowering to register type
2619 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2620                                const SDLoc &Dl, SelectionDAG &DAG) {
2621   EVT ValVT = ValArg.getValueType();
2622 
2623   if (ValVT == MVT::v1i1)
2624     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2625                        DAG.getIntPtrConstant(0, Dl));
2626 
2627   if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2628       (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2629     // Two stage lowering might be required
2630     // bitcast:   v8i1 -> i8 / v16i1 -> i16
2631     // anyextend: i8   -> i32 / i16   -> i32
2632     EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2633     SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2634     if (ValLoc == MVT::i32)
2635       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2636     return ValToCopy;
2637   }
2638 
2639   if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2640       (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2641     // One stage lowering is required
2642     // bitcast:   v32i1 -> i32 / v64i1 -> i64
2643     return DAG.getBitcast(ValLoc, ValArg);
2644   }
2645 
2646   return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2647 }
2648 
2649 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2650 static void Passv64i1ArgInRegs(
2651     const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
2652     SmallVectorImpl<std::pair<Register, SDValue>> &RegsToPass, CCValAssign &VA,
2653     CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2654   assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2655   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2656   assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2657   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2658          "The value should reside in two registers");
2659 
2660   // Before splitting the value we cast it to i64
2661   Arg = DAG.getBitcast(MVT::i64, Arg);
2662 
2663   // Splitting the value into two i32 types
2664   SDValue Lo, Hi;
2665   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2666                    DAG.getConstant(0, Dl, MVT::i32));
2667   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2668                    DAG.getConstant(1, Dl, MVT::i32));
2669 
2670   // Attach the two i32 types into corresponding registers
2671   RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2672   RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2673 }
2674 
2675 SDValue
2676 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2677                                bool isVarArg,
2678                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2679                                const SmallVectorImpl<SDValue> &OutVals,
2680                                const SDLoc &dl, SelectionDAG &DAG) const {
2681   MachineFunction &MF = DAG.getMachineFunction();
2682   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2683 
2684   // In some cases we need to disable registers from the default CSR list.
2685   // For example, when they are used for argument passing.
2686   bool ShouldDisableCalleeSavedRegister =
2687       CallConv == CallingConv::X86_RegCall ||
2688       MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2689 
2690   if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2691     report_fatal_error("X86 interrupts may not return any value");
2692 
2693   SmallVector<CCValAssign, 16> RVLocs;
2694   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2695   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2696 
2697   SmallVector<std::pair<Register, SDValue>, 4> RetVals;
2698   for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2699        ++I, ++OutsIndex) {
2700     CCValAssign &VA = RVLocs[I];
2701     assert(VA.isRegLoc() && "Can only return in registers!");
2702 
2703     // Add the register to the CalleeSaveDisableRegs list.
2704     if (ShouldDisableCalleeSavedRegister)
2705       MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2706 
2707     SDValue ValToCopy = OutVals[OutsIndex];
2708     EVT ValVT = ValToCopy.getValueType();
2709 
2710     // Promote values to the appropriate types.
2711     if (VA.getLocInfo() == CCValAssign::SExt)
2712       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2713     else if (VA.getLocInfo() == CCValAssign::ZExt)
2714       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2715     else if (VA.getLocInfo() == CCValAssign::AExt) {
2716       if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2717         ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2718       else
2719         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2720     }
2721     else if (VA.getLocInfo() == CCValAssign::BCvt)
2722       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2723 
2724     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2725            "Unexpected FP-extend for return value.");
2726 
2727     // Report an error if we have attempted to return a value via an XMM
2728     // register and SSE was disabled.
2729     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
2730       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2731       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2732     } else if (!Subtarget.hasSSE2() &&
2733                X86::FR64XRegClass.contains(VA.getLocReg()) &&
2734                ValVT == MVT::f64) {
2735       // When returning a double via an XMM register, report an error if SSE2 is
2736       // not enabled.
2737       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2738       VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2739     }
2740 
2741     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2742     // the RET instruction and handled by the FP Stackifier.
2743     if (VA.getLocReg() == X86::FP0 ||
2744         VA.getLocReg() == X86::FP1) {
2745       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2746       // change the value to the FP stack register class.
2747       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2748         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2749       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2750       // Don't emit a copytoreg.
2751       continue;
2752     }
2753 
2754     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2755     // which is returned in RAX / RDX.
2756     if (Subtarget.is64Bit()) {
2757       if (ValVT == MVT::x86mmx) {
2758         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2759           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2760           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2761                                   ValToCopy);
2762           // If we don't have SSE2 available, convert to v4f32 so the generated
2763           // register is legal.
2764           if (!Subtarget.hasSSE2())
2765             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2766         }
2767       }
2768     }
2769 
2770     if (VA.needsCustom()) {
2771       assert(VA.getValVT() == MVT::v64i1 &&
2772              "Currently the only custom case is when we split v64i1 to 2 regs");
2773 
2774       Passv64i1ArgInRegs(dl, DAG, ValToCopy, RetVals, VA, RVLocs[++I],
2775                          Subtarget);
2776 
2777       // Add the second register to the CalleeSaveDisableRegs list.
2778       if (ShouldDisableCalleeSavedRegister)
2779         MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2780     } else {
2781       RetVals.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2782     }
2783   }
2784 
2785   SDValue Flag;
2786   SmallVector<SDValue, 6> RetOps;
2787   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2788   // Operand #1 = Bytes To Pop
2789   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2790                    MVT::i32));
2791 
2792   // Copy the result values into the output registers.
2793   for (auto &RetVal : RetVals) {
2794     if (RetVal.first == X86::FP0 || RetVal.first == X86::FP1) {
2795       RetOps.push_back(RetVal.second);
2796       continue; // Don't emit a copytoreg.
2797     }
2798 
2799     Chain = DAG.getCopyToReg(Chain, dl, RetVal.first, RetVal.second, Flag);
2800     Flag = Chain.getValue(1);
2801     RetOps.push_back(
2802         DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
2803   }
2804 
2805   // Swift calling convention does not require we copy the sret argument
2806   // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2807 
2808   // All x86 ABIs require that for returning structs by value we copy
2809   // the sret argument into %rax/%eax (depending on ABI) for the return.
2810   // We saved the argument into a virtual register in the entry block,
2811   // so now we copy the value out and into %rax/%eax.
2812   //
2813   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2814   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2815   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2816   // either case FuncInfo->setSRetReturnReg() will have been called.
2817   if (Register SRetReg = FuncInfo->getSRetReturnReg()) {
2818     // When we have both sret and another return value, we should use the
2819     // original Chain stored in RetOps[0], instead of the current Chain updated
2820     // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2821 
2822     // For the case of sret and another return value, we have
2823     //   Chain_0 at the function entry
2824     //   Chain_1 = getCopyToReg(Chain_0) in the above loop
2825     // If we use Chain_1 in getCopyFromReg, we will have
2826     //   Val = getCopyFromReg(Chain_1)
2827     //   Chain_2 = getCopyToReg(Chain_1, Val) from below
2828 
2829     // getCopyToReg(Chain_0) will be glued together with
2830     // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2831     // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2832     //   Data dependency from Unit B to Unit A due to usage of Val in
2833     //     getCopyToReg(Chain_1, Val)
2834     //   Chain dependency from Unit A to Unit B
2835 
2836     // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2837     SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2838                                      getPointerTy(MF.getDataLayout()));
2839 
2840     Register RetValReg
2841         = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2842           X86::RAX : X86::EAX;
2843     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2844     Flag = Chain.getValue(1);
2845 
2846     // RAX/EAX now acts like a return value.
2847     RetOps.push_back(
2848         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2849 
2850     // Add the returned register to the CalleeSaveDisableRegs list.
2851     if (ShouldDisableCalleeSavedRegister)
2852       MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2853   }
2854 
2855   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2856   const MCPhysReg *I =
2857       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2858   if (I) {
2859     for (; *I; ++I) {
2860       if (X86::GR64RegClass.contains(*I))
2861         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2862       else
2863         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2864     }
2865   }
2866 
2867   RetOps[0] = Chain;  // Update chain.
2868 
2869   // Add the flag if we have it.
2870   if (Flag.getNode())
2871     RetOps.push_back(Flag);
2872 
2873   X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2874   if (CallConv == CallingConv::X86_INTR)
2875     opcode = X86ISD::IRET;
2876   return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2877 }
2878 
2879 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2880   if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2881     return false;
2882 
2883   SDValue TCChain = Chain;
2884   SDNode *Copy = *N->use_begin();
2885   if (Copy->getOpcode() == ISD::CopyToReg) {
2886     // If the copy has a glue operand, we conservatively assume it isn't safe to
2887     // perform a tail call.
2888     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2889       return false;
2890     TCChain = Copy->getOperand(0);
2891   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2892     return false;
2893 
2894   bool HasRet = false;
2895   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2896        UI != UE; ++UI) {
2897     if (UI->getOpcode() != X86ISD::RET_FLAG)
2898       return false;
2899     // If we are returning more than one value, we can definitely
2900     // not make a tail call see PR19530
2901     if (UI->getNumOperands() > 4)
2902       return false;
2903     if (UI->getNumOperands() == 4 &&
2904         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2905       return false;
2906     HasRet = true;
2907   }
2908 
2909   if (!HasRet)
2910     return false;
2911 
2912   Chain = TCChain;
2913   return true;
2914 }
2915 
2916 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2917                                            ISD::NodeType ExtendKind) const {
2918   MVT ReturnMVT = MVT::i32;
2919 
2920   bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2921   if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2922     // The ABI does not require i1, i8 or i16 to be extended.
2923     //
2924     // On Darwin, there is code in the wild relying on Clang's old behaviour of
2925     // always extending i8/i16 return values, so keep doing that for now.
2926     // (PR26665).
2927     ReturnMVT = MVT::i8;
2928   }
2929 
2930   EVT MinVT = getRegisterType(Context, ReturnMVT);
2931   return VT.bitsLT(MinVT) ? MinVT : VT;
2932 }
2933 
2934 /// Reads two 32 bit registers and creates a 64 bit mask value.
2935 /// \param VA The current 32 bit value that need to be assigned.
2936 /// \param NextVA The next 32 bit value that need to be assigned.
2937 /// \param Root The parent DAG node.
2938 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2939 ///                        glue purposes. In the case the DAG is already using
2940 ///                        physical register instead of virtual, we should glue
2941 ///                        our new SDValue to InFlag SDvalue.
2942 /// \return a new SDvalue of size 64bit.
2943 static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2944                                 SDValue &Root, SelectionDAG &DAG,
2945                                 const SDLoc &Dl, const X86Subtarget &Subtarget,
2946                                 SDValue *InFlag = nullptr) {
2947   assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2948   assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2949   assert(VA.getValVT() == MVT::v64i1 &&
2950          "Expecting first location of 64 bit width type");
2951   assert(NextVA.getValVT() == VA.getValVT() &&
2952          "The locations should have the same type");
2953   assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2954          "The values should reside in two registers");
2955 
2956   SDValue Lo, Hi;
2957   SDValue ArgValueLo, ArgValueHi;
2958 
2959   MachineFunction &MF = DAG.getMachineFunction();
2960   const TargetRegisterClass *RC = &X86::GR32RegClass;
2961 
2962   // Read a 32 bit value from the registers.
2963   if (nullptr == InFlag) {
2964     // When no physical register is present,
2965     // create an intermediate virtual register.
2966     Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
2967     ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2968     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2969     ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2970   } else {
2971     // When a physical register is available read the value from it and glue
2972     // the reads together.
2973     ArgValueLo =
2974       DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2975     *InFlag = ArgValueLo.getValue(2);
2976     ArgValueHi =
2977       DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2978     *InFlag = ArgValueHi.getValue(2);
2979   }
2980 
2981   // Convert the i32 type into v32i1 type.
2982   Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2983 
2984   // Convert the i32 type into v32i1 type.
2985   Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2986 
2987   // Concatenate the two values together.
2988   return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2989 }
2990 
2991 /// The function will lower a register of various sizes (8/16/32/64)
2992 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2993 /// \returns a DAG node contains the operand after lowering to mask type.
2994 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2995                                const EVT &ValLoc, const SDLoc &Dl,
2996                                SelectionDAG &DAG) {
2997   SDValue ValReturned = ValArg;
2998 
2999   if (ValVT == MVT::v1i1)
3000     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
3001 
3002   if (ValVT == MVT::v64i1) {
3003     // In 32 bit machine, this case is handled by getv64i1Argument
3004     assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
3005     // In 64 bit machine, There is no need to truncate the value only bitcast
3006   } else {
3007     MVT maskLen;
3008     switch (ValVT.getSimpleVT().SimpleTy) {
3009     case MVT::v8i1:
3010       maskLen = MVT::i8;
3011       break;
3012     case MVT::v16i1:
3013       maskLen = MVT::i16;
3014       break;
3015     case MVT::v32i1:
3016       maskLen = MVT::i32;
3017       break;
3018     default:
3019       llvm_unreachable("Expecting a vector of i1 types");
3020     }
3021 
3022     ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
3023   }
3024   return DAG.getBitcast(ValVT, ValReturned);
3025 }
3026 
3027 /// Lower the result values of a call into the
3028 /// appropriate copies out of appropriate physical registers.
3029 ///
3030 SDValue X86TargetLowering::LowerCallResult(
3031     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3032     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3033     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3034     uint32_t *RegMask) const {
3035 
3036   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3037   // Assign locations to each value returned by this call.
3038   SmallVector<CCValAssign, 16> RVLocs;
3039   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3040                  *DAG.getContext());
3041   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3042 
3043   // Copy all of the result registers out of their specified physreg.
3044   for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
3045        ++I, ++InsIndex) {
3046     CCValAssign &VA = RVLocs[I];
3047     EVT CopyVT = VA.getLocVT();
3048 
3049     // In some calling conventions we need to remove the used registers
3050     // from the register mask.
3051     if (RegMask) {
3052       for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
3053            SubRegs.isValid(); ++SubRegs)
3054         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3055     }
3056 
3057     // Report an error if there was an attempt to return FP values via XMM
3058     // registers.
3059     if (!Subtarget.hasSSE1() && X86::FR32XRegClass.contains(VA.getLocReg())) {
3060       errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
3061       if (VA.getLocReg() == X86::XMM1)
3062         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3063       else
3064         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3065     } else if (!Subtarget.hasSSE2() &&
3066                X86::FR64XRegClass.contains(VA.getLocReg()) &&
3067                CopyVT == MVT::f64) {
3068       errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
3069       if (VA.getLocReg() == X86::XMM1)
3070         VA.convertToReg(X86::FP1); // Set reg to FP1, avoid hitting asserts.
3071       else
3072         VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
3073     }
3074 
3075     // If we prefer to use the value in xmm registers, copy it out as f80 and
3076     // use a truncate to move it from fp stack reg to xmm reg.
3077     bool RoundAfterCopy = false;
3078     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3079         isScalarFPTypeInSSEReg(VA.getValVT())) {
3080       if (!Subtarget.hasX87())
3081         report_fatal_error("X87 register return with X87 disabled");
3082       CopyVT = MVT::f80;
3083       RoundAfterCopy = (CopyVT != VA.getLocVT());
3084     }
3085 
3086     SDValue Val;
3087     if (VA.needsCustom()) {
3088       assert(VA.getValVT() == MVT::v64i1 &&
3089              "Currently the only custom case is when we split v64i1 to 2 regs");
3090       Val =
3091           getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
3092     } else {
3093       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
3094                   .getValue(1);
3095       Val = Chain.getValue(0);
3096       InFlag = Chain.getValue(2);
3097     }
3098 
3099     if (RoundAfterCopy)
3100       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
3101                         // This truncation won't change the value.
3102                         DAG.getIntPtrConstant(1, dl));
3103 
3104     if (VA.isExtInLoc()) {
3105       if (VA.getValVT().isVector() &&
3106           VA.getValVT().getScalarType() == MVT::i1 &&
3107           ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3108            (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3109         // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3110         Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
3111       } else
3112         Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3113     }
3114 
3115     if (VA.getLocInfo() == CCValAssign::BCvt)
3116       Val = DAG.getBitcast(VA.getValVT(), Val);
3117 
3118     InVals.push_back(Val);
3119   }
3120 
3121   return Chain;
3122 }
3123 
3124 //===----------------------------------------------------------------------===//
3125 //                C & StdCall & Fast Calling Convention implementation
3126 //===----------------------------------------------------------------------===//
3127 //  StdCall calling convention seems to be standard for many Windows' API
3128 //  routines and around. It differs from C calling convention just a little:
3129 //  callee should clean up the stack, not caller. Symbols should be also
3130 //  decorated in some fancy way :) It doesn't support any vector arguments.
3131 //  For info on fast calling convention see Fast Calling Convention (tail call)
3132 //  implementation LowerX86_32FastCCCallTo.
3133 
3134 /// CallIsStructReturn - Determines whether a call uses struct return
3135 /// semantics.
3136 enum StructReturnType {
3137   NotStructReturn,
3138   RegStructReturn,
3139   StackStructReturn
3140 };
3141 static StructReturnType
3142 callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
3143   if (Outs.empty())
3144     return NotStructReturn;
3145 
3146   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
3147   if (!Flags.isSRet())
3148     return NotStructReturn;
3149   if (Flags.isInReg() || IsMCU)
3150     return RegStructReturn;
3151   return StackStructReturn;
3152 }
3153 
3154 /// Determines whether a function uses struct return semantics.
3155 static StructReturnType
3156 argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
3157   if (Ins.empty())
3158     return NotStructReturn;
3159 
3160   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
3161   if (!Flags.isSRet())
3162     return NotStructReturn;
3163   if (Flags.isInReg() || IsMCU)
3164     return RegStructReturn;
3165   return StackStructReturn;
3166 }
3167 
3168 /// Make a copy of an aggregate at address specified by "Src" to address
3169 /// "Dst" with size and alignment information specified by the specific
3170 /// parameter attribute. The copy will be passed as a byval function parameter.
3171 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
3172                                          SDValue Chain, ISD::ArgFlagsTy Flags,
3173                                          SelectionDAG &DAG, const SDLoc &dl) {
3174   SDValue SizeNode = DAG.getIntPtrConstant(Flags.getByValSize(), dl);
3175 
3176   return DAG.getMemcpy(
3177       Chain, dl, Dst, Src, SizeNode, Flags.getNonZeroByValAlign(),
3178       /*isVolatile*/ false, /*AlwaysInline=*/true,
3179       /*isTailCall*/ false, MachinePointerInfo(), MachinePointerInfo());
3180 }
3181 
3182 /// Return true if the calling convention is one that we can guarantee TCO for.
3183 static bool canGuaranteeTCO(CallingConv::ID CC) {
3184   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3185           CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
3186           CC == CallingConv::HHVM || CC == CallingConv::Tail);
3187 }
3188 
3189 /// Return true if we might ever do TCO for calls with this calling convention.
3190 static bool mayTailCallThisCC(CallingConv::ID CC) {
3191   switch (CC) {
3192   // C calling conventions:
3193   case CallingConv::C:
3194   case CallingConv::Win64:
3195   case CallingConv::X86_64_SysV:
3196   // Callee pop conventions:
3197   case CallingConv::X86_ThisCall:
3198   case CallingConv::X86_StdCall:
3199   case CallingConv::X86_VectorCall:
3200   case CallingConv::X86_FastCall:
3201   // Swift:
3202   case CallingConv::Swift:
3203     return true;
3204   default:
3205     return canGuaranteeTCO(CC);
3206   }
3207 }
3208 
3209 /// Return true if the function is being made into a tailcall target by
3210 /// changing its ABI.
3211 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
3212   return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) || CC == CallingConv::Tail;
3213 }
3214 
3215 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3216   if (!CI->isTailCall())
3217     return false;
3218 
3219   CallingConv::ID CalleeCC = CI->getCallingConv();
3220   if (!mayTailCallThisCC(CalleeCC))
3221     return false;
3222 
3223   return true;
3224 }
3225 
3226 SDValue
3227 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3228                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3229                                     const SDLoc &dl, SelectionDAG &DAG,
3230                                     const CCValAssign &VA,
3231                                     MachineFrameInfo &MFI, unsigned i) const {
3232   // Create the nodes corresponding to a load from this parameter slot.
3233   ISD::ArgFlagsTy Flags = Ins[i].Flags;
3234   bool AlwaysUseMutable = shouldGuaranteeTCO(
3235       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3236   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3237   EVT ValVT;
3238   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3239 
3240   // If value is passed by pointer we have address passed instead of the value
3241   // itself. No need to extend if the mask value and location share the same
3242   // absolute size.
3243   bool ExtendedInMem =
3244       VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3245       VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3246 
3247   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3248     ValVT = VA.getLocVT();
3249   else
3250     ValVT = VA.getValVT();
3251 
3252   // FIXME: For now, all byval parameter objects are marked mutable. This can be
3253   // changed with more analysis.
3254   // In case of tail call optimization mark all arguments mutable. Since they
3255   // could be overwritten by lowering of arguments in case of a tail call.
3256   if (Flags.isByVal()) {
3257     unsigned Bytes = Flags.getByValSize();
3258     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3259 
3260     // FIXME: For now, all byval parameter objects are marked as aliasing. This
3261     // can be improved with deeper analysis.
3262     int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3263                                    /*isAliased=*/true);
3264     return DAG.getFrameIndex(FI, PtrVT);
3265   }
3266 
3267   EVT ArgVT = Ins[i].ArgVT;
3268 
3269   // If this is a vector that has been split into multiple parts, and the
3270   // scalar size of the parts don't match the vector element size, then we can't
3271   // elide the copy. The parts will have padding between them instead of being
3272   // packed like a vector.
3273   bool ScalarizedAndExtendedVector =
3274       ArgVT.isVector() && !VA.getLocVT().isVector() &&
3275       VA.getLocVT().getSizeInBits() != ArgVT.getScalarSizeInBits();
3276 
3277   // This is an argument in memory. We might be able to perform copy elision.
3278   // If the argument is passed directly in memory without any extension, then we
3279   // can perform copy elision. Large vector types, for example, may be passed
3280   // indirectly by pointer.
3281   if (Flags.isCopyElisionCandidate() &&
3282       VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem &&
3283       !ScalarizedAndExtendedVector) {
3284     SDValue PartAddr;
3285     if (Ins[i].PartOffset == 0) {
3286       // If this is a one-part value or the first part of a multi-part value,
3287       // create a stack object for the entire argument value type and return a
3288       // load from our portion of it. This assumes that if the first part of an
3289       // argument is in memory, the rest will also be in memory.
3290       int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3291                                      /*IsImmutable=*/false);
3292       PartAddr = DAG.getFrameIndex(FI, PtrVT);
3293       return DAG.getLoad(
3294           ValVT, dl, Chain, PartAddr,
3295           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3296     } else {
3297       // This is not the first piece of an argument in memory. See if there is
3298       // already a fixed stack object including this offset. If so, assume it
3299       // was created by the PartOffset == 0 branch above and create a load from
3300       // the appropriate offset into it.
3301       int64_t PartBegin = VA.getLocMemOffset();
3302       int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3303       int FI = MFI.getObjectIndexBegin();
3304       for (; MFI.isFixedObjectIndex(FI); ++FI) {
3305         int64_t ObjBegin = MFI.getObjectOffset(FI);
3306         int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3307         if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3308           break;
3309       }
3310       if (MFI.isFixedObjectIndex(FI)) {
3311         SDValue Addr =
3312             DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3313                         DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3314         return DAG.getLoad(
3315             ValVT, dl, Chain, Addr,
3316             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3317                                               Ins[i].PartOffset));
3318       }
3319     }
3320   }
3321 
3322   int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3323                                  VA.getLocMemOffset(), isImmutable);
3324 
3325   // Set SExt or ZExt flag.
3326   if (VA.getLocInfo() == CCValAssign::ZExt) {
3327     MFI.setObjectZExt(FI, true);
3328   } else if (VA.getLocInfo() == CCValAssign::SExt) {
3329     MFI.setObjectSExt(FI, true);
3330   }
3331 
3332   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3333   SDValue Val = DAG.getLoad(
3334       ValVT, dl, Chain, FIN,
3335       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3336   return ExtendedInMem
3337              ? (VA.getValVT().isVector()
3338                     ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3339                     : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3340              : Val;
3341 }
3342 
3343 // FIXME: Get this from tablegen.
3344 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3345                                                 const X86Subtarget &Subtarget) {
3346   assert(Subtarget.is64Bit());
3347 
3348   if (Subtarget.isCallingConvWin64(CallConv)) {
3349     static const MCPhysReg GPR64ArgRegsWin64[] = {
3350       X86::RCX, X86::RDX, X86::R8,  X86::R9
3351     };
3352     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3353   }
3354 
3355   static const MCPhysReg GPR64ArgRegs64Bit[] = {
3356     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3357   };
3358   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3359 }
3360 
3361 // FIXME: Get this from tablegen.
3362 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3363                                                 CallingConv::ID CallConv,
3364                                                 const X86Subtarget &Subtarget) {
3365   assert(Subtarget.is64Bit());
3366   if (Subtarget.isCallingConvWin64(CallConv)) {
3367     // The XMM registers which might contain var arg parameters are shadowed
3368     // in their paired GPR.  So we only need to save the GPR to their home
3369     // slots.
3370     // TODO: __vectorcall will change this.
3371     return None;
3372   }
3373 
3374   const Function &F = MF.getFunction();
3375   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3376   bool isSoftFloat = Subtarget.useSoftFloat();
3377   assert(!(isSoftFloat && NoImplicitFloatOps) &&
3378          "SSE register cannot be used when SSE is disabled!");
3379   if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3380     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3381     // registers.
3382     return None;
3383 
3384   static const MCPhysReg XMMArgRegs64Bit[] = {
3385     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3386     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3387   };
3388   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3389 }
3390 
3391 #ifndef NDEBUG
3392 static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3393   return llvm::is_sorted(
3394       ArgLocs, [](const CCValAssign &A, const CCValAssign &B) -> bool {
3395         return A.getValNo() < B.getValNo();
3396       });
3397 }
3398 #endif
3399 
3400 namespace {
3401 /// This is a helper class for lowering variable arguments parameters.
3402 class VarArgsLoweringHelper {
3403 public:
3404   VarArgsLoweringHelper(X86MachineFunctionInfo *FuncInfo, const SDLoc &Loc,
3405                         SelectionDAG &DAG, const X86Subtarget &Subtarget,
3406                         CallingConv::ID CallConv, CCState &CCInfo)
3407       : FuncInfo(FuncInfo), DL(Loc), DAG(DAG), Subtarget(Subtarget),
3408         TheMachineFunction(DAG.getMachineFunction()),
3409         TheFunction(TheMachineFunction.getFunction()),
3410         FrameInfo(TheMachineFunction.getFrameInfo()),
3411         FrameLowering(*Subtarget.getFrameLowering()),
3412         TargLowering(DAG.getTargetLoweringInfo()), CallConv(CallConv),
3413         CCInfo(CCInfo) {}
3414 
3415   // Lower variable arguments parameters.
3416   void lowerVarArgsParameters(SDValue &Chain, unsigned StackSize);
3417 
3418 private:
3419   void createVarArgAreaAndStoreRegisters(SDValue &Chain, unsigned StackSize);
3420 
3421   void forwardMustTailParameters(SDValue &Chain);
3422 
3423   bool is64Bit() const { return Subtarget.is64Bit(); }
3424   bool isWin64() const { return Subtarget.isCallingConvWin64(CallConv); }
3425 
3426   X86MachineFunctionInfo *FuncInfo;
3427   const SDLoc &DL;
3428   SelectionDAG &DAG;
3429   const X86Subtarget &Subtarget;
3430   MachineFunction &TheMachineFunction;
3431   const Function &TheFunction;
3432   MachineFrameInfo &FrameInfo;
3433   const TargetFrameLowering &FrameLowering;
3434   const TargetLowering &TargLowering;
3435   CallingConv::ID CallConv;
3436   CCState &CCInfo;
3437 };
3438 } // namespace
3439 
3440 void VarArgsLoweringHelper::createVarArgAreaAndStoreRegisters(
3441     SDValue &Chain, unsigned StackSize) {
3442   // If the function takes variable number of arguments, make a frame index for
3443   // the start of the first vararg value... for expansion of llvm.va_start. We
3444   // can skip this if there are no va_start calls.
3445   if (is64Bit() || (CallConv != CallingConv::X86_FastCall &&
3446                     CallConv != CallingConv::X86_ThisCall)) {
3447     FuncInfo->setVarArgsFrameIndex(
3448         FrameInfo.CreateFixedObject(1, StackSize, true));
3449   }
3450 
3451   // Figure out if XMM registers are in use.
3452   assert(!(Subtarget.useSoftFloat() &&
3453            TheFunction.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3454          "SSE register cannot be used when SSE is disabled!");
3455 
3456   // 64-bit calling conventions support varargs and register parameters, so we
3457   // have to do extra work to spill them in the prologue.
3458   if (is64Bit()) {
3459     // Find the first unallocated argument registers.
3460     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3461     ArrayRef<MCPhysReg> ArgXMMs =
3462         get64BitArgumentXMMs(TheMachineFunction, CallConv, Subtarget);
3463     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3464     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3465 
3466     assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3467            "SSE register cannot be used when SSE is disabled!");
3468 
3469     if (isWin64()) {
3470       // Get to the caller-allocated home save location.  Add 8 to account
3471       // for the return address.
3472       int HomeOffset = FrameLowering.getOffsetOfLocalArea() + 8;
3473       FuncInfo->setRegSaveFrameIndex(
3474           FrameInfo.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3475       // Fixup to set vararg frame on shadow area (4 x i64).
3476       if (NumIntRegs < 4)
3477         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3478     } else {
3479       // For X86-64, if there are vararg parameters that are passed via
3480       // registers, then we must store them to their spots on the stack so
3481       // they may be loaded by dereferencing the result of va_next.
3482       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3483       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3484       FuncInfo->setRegSaveFrameIndex(FrameInfo.CreateStackObject(
3485           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, Align(16), false));
3486     }
3487 
3488     SmallVector<SDValue, 6>
3489         LiveGPRs; // list of SDValue for GPR registers keeping live input value
3490     SmallVector<SDValue, 8> LiveXMMRegs; // list of SDValue for XMM registers
3491                                          // keeping live input value
3492     SDValue ALVal; // if applicable keeps SDValue for %al register
3493 
3494     // Gather all the live in physical registers.
3495     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3496       Register GPR = TheMachineFunction.addLiveIn(Reg, &X86::GR64RegClass);
3497       LiveGPRs.push_back(DAG.getCopyFromReg(Chain, DL, GPR, MVT::i64));
3498     }
3499     const auto &AvailableXmms = ArgXMMs.slice(NumXMMRegs);
3500     if (!AvailableXmms.empty()) {
3501       Register AL = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3502       ALVal = DAG.getCopyFromReg(Chain, DL, AL, MVT::i8);
3503       for (MCPhysReg Reg : AvailableXmms) {
3504         Register XMMReg = TheMachineFunction.addLiveIn(Reg, &X86::VR128RegClass);
3505         LiveXMMRegs.push_back(
3506             DAG.getCopyFromReg(Chain, DL, XMMReg, MVT::v4f32));
3507       }
3508     }
3509 
3510     // Store the integer parameter registers.
3511     SmallVector<SDValue, 8> MemOps;
3512     SDValue RSFIN =
3513         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3514                           TargLowering.getPointerTy(DAG.getDataLayout()));
3515     unsigned Offset = FuncInfo->getVarArgsGPOffset();
3516     for (SDValue Val : LiveGPRs) {
3517       SDValue FIN = DAG.getNode(ISD::ADD, DL,
3518                                 TargLowering.getPointerTy(DAG.getDataLayout()),
3519                                 RSFIN, DAG.getIntPtrConstant(Offset, DL));
3520       SDValue Store =
3521           DAG.getStore(Val.getValue(1), DL, Val, FIN,
3522                        MachinePointerInfo::getFixedStack(
3523                            DAG.getMachineFunction(),
3524                            FuncInfo->getRegSaveFrameIndex(), Offset));
3525       MemOps.push_back(Store);
3526       Offset += 8;
3527     }
3528 
3529     // Now store the XMM (fp + vector) parameter registers.
3530     if (!LiveXMMRegs.empty()) {
3531       SmallVector<SDValue, 12> SaveXMMOps;
3532       SaveXMMOps.push_back(Chain);
3533       SaveXMMOps.push_back(ALVal);
3534       SaveXMMOps.push_back(
3535           DAG.getTargetConstant(FuncInfo->getRegSaveFrameIndex(), DL, MVT::i32));
3536       SaveXMMOps.push_back(
3537           DAG.getTargetConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32));
3538       llvm::append_range(SaveXMMOps, LiveXMMRegs);
3539       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, DL,
3540                                    MVT::Other, SaveXMMOps));
3541     }
3542 
3543     if (!MemOps.empty())
3544       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3545   }
3546 }
3547 
3548 void VarArgsLoweringHelper::forwardMustTailParameters(SDValue &Chain) {
3549   // Find the largest legal vector type.
3550   MVT VecVT = MVT::Other;
3551   // FIXME: Only some x86_32 calling conventions support AVX512.
3552   if (Subtarget.useAVX512Regs() &&
3553       (is64Bit() || (CallConv == CallingConv::X86_VectorCall ||
3554                      CallConv == CallingConv::Intel_OCL_BI)))
3555     VecVT = MVT::v16f32;
3556   else if (Subtarget.hasAVX())
3557     VecVT = MVT::v8f32;
3558   else if (Subtarget.hasSSE2())
3559     VecVT = MVT::v4f32;
3560 
3561   // We forward some GPRs and some vector types.
3562   SmallVector<MVT, 2> RegParmTypes;
3563   MVT IntVT = is64Bit() ? MVT::i64 : MVT::i32;
3564   RegParmTypes.push_back(IntVT);
3565   if (VecVT != MVT::Other)
3566     RegParmTypes.push_back(VecVT);
3567 
3568   // Compute the set of forwarded registers. The rest are scratch.
3569   SmallVectorImpl<ForwardedRegister> &Forwards =
3570       FuncInfo->getForwardedMustTailRegParms();
3571   CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3572 
3573   // Forward AL for SysV x86_64 targets, since it is used for varargs.
3574   if (is64Bit() && !isWin64() && !CCInfo.isAllocated(X86::AL)) {
3575     Register ALVReg = TheMachineFunction.addLiveIn(X86::AL, &X86::GR8RegClass);
3576     Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3577   }
3578 
3579   // Copy all forwards from physical to virtual registers.
3580   for (ForwardedRegister &FR : Forwards) {
3581     // FIXME: Can we use a less constrained schedule?
3582     SDValue RegVal = DAG.getCopyFromReg(Chain, DL, FR.VReg, FR.VT);
3583     FR.VReg = TheMachineFunction.getRegInfo().createVirtualRegister(
3584         TargLowering.getRegClassFor(FR.VT));
3585     Chain = DAG.getCopyToReg(Chain, DL, FR.VReg, RegVal);
3586   }
3587 }
3588 
3589 void VarArgsLoweringHelper::lowerVarArgsParameters(SDValue &Chain,
3590                                                    unsigned StackSize) {
3591   // Set FrameIndex to the 0xAAAAAAA value to mark unset state.
3592   // If necessary, it would be set into the correct value later.
3593   FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3594   FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3595 
3596   if (FrameInfo.hasVAStart())
3597     createVarArgAreaAndStoreRegisters(Chain, StackSize);
3598 
3599   if (FrameInfo.hasMustTailInVarArgFunc())
3600     forwardMustTailParameters(Chain);
3601 }
3602 
3603 SDValue X86TargetLowering::LowerFormalArguments(
3604     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3605     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3606     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3609 
3610   const Function &F = MF.getFunction();
3611   if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3612       F.getName() == "main")
3613     FuncInfo->setForceFramePointer(true);
3614 
3615   MachineFrameInfo &MFI = MF.getFrameInfo();
3616   bool Is64Bit = Subtarget.is64Bit();
3617   bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3618 
3619   assert(
3620       !(IsVarArg && canGuaranteeTCO(CallConv)) &&
3621       "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3622 
3623   // Assign locations to all of the incoming arguments.
3624   SmallVector<CCValAssign, 16> ArgLocs;
3625   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3626 
3627   // Allocate shadow area for Win64.
3628   if (IsWin64)
3629     CCInfo.AllocateStack(32, Align(8));
3630 
3631   CCInfo.AnalyzeArguments(Ins, CC_X86);
3632 
3633   // In vectorcall calling convention a second pass is required for the HVA
3634   // types.
3635   if (CallingConv::X86_VectorCall == CallConv) {
3636     CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3637   }
3638 
3639   // The next loop assumes that the locations are in the same order of the
3640   // input arguments.
3641   assert(isSortedByValueNo(ArgLocs) &&
3642          "Argument Location list must be sorted before lowering");
3643 
3644   SDValue ArgValue;
3645   for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3646        ++I, ++InsIndex) {
3647     assert(InsIndex < Ins.size() && "Invalid Ins index");
3648     CCValAssign &VA = ArgLocs[I];
3649 
3650     if (VA.isRegLoc()) {
3651       EVT RegVT = VA.getLocVT();
3652       if (VA.needsCustom()) {
3653         assert(
3654             VA.getValVT() == MVT::v64i1 &&
3655             "Currently the only custom case is when we split v64i1 to 2 regs");
3656 
3657         // v64i1 values, in regcall calling convention, that are
3658         // compiled to 32 bit arch, are split up into two registers.
3659         ArgValue =
3660             getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3661       } else {
3662         const TargetRegisterClass *RC;
3663         if (RegVT == MVT::i8)
3664           RC = &X86::GR8RegClass;
3665         else if (RegVT == MVT::i16)
3666           RC = &X86::GR16RegClass;
3667         else if (RegVT == MVT::i32)
3668           RC = &X86::GR32RegClass;
3669         else if (Is64Bit && RegVT == MVT::i64)
3670           RC = &X86::GR64RegClass;
3671         else if (RegVT == MVT::f32)
3672           RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3673         else if (RegVT == MVT::f64)
3674           RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3675         else if (RegVT == MVT::f80)
3676           RC = &X86::RFP80RegClass;
3677         else if (RegVT == MVT::f128)
3678           RC = &X86::VR128RegClass;
3679         else if (RegVT.is512BitVector())
3680           RC = &X86::VR512RegClass;
3681         else if (RegVT.is256BitVector())
3682           RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3683         else if (RegVT.is128BitVector())
3684           RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3685         else if (RegVT == MVT::x86mmx)
3686           RC = &X86::VR64RegClass;
3687         else if (RegVT == MVT::v1i1)
3688           RC = &X86::VK1RegClass;
3689         else if (RegVT == MVT::v8i1)
3690           RC = &X86::VK8RegClass;
3691         else if (RegVT == MVT::v16i1)
3692           RC = &X86::VK16RegClass;
3693         else if (RegVT == MVT::v32i1)
3694           RC = &X86::VK32RegClass;
3695         else if (RegVT == MVT::v64i1)
3696           RC = &X86::VK64RegClass;
3697         else
3698           llvm_unreachable("Unknown argument type!");
3699 
3700         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
3701         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3702       }
3703 
3704       // If this is an 8 or 16-bit value, it is really passed promoted to 32
3705       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
3706       // right size.
3707       if (VA.getLocInfo() == CCValAssign::SExt)
3708         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3709                                DAG.getValueType(VA.getValVT()));
3710       else if (VA.getLocInfo() == CCValAssign::ZExt)
3711         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3712                                DAG.getValueType(VA.getValVT()));
3713       else if (VA.getLocInfo() == CCValAssign::BCvt)
3714         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3715 
3716       if (VA.isExtInLoc()) {
3717         // Handle MMX values passed in XMM regs.
3718         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3719           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3720         else if (VA.getValVT().isVector() &&
3721                  VA.getValVT().getScalarType() == MVT::i1 &&
3722                  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3723                   (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3724           // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3725           ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3726         } else
3727           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3728       }
3729     } else {
3730       assert(VA.isMemLoc());
3731       ArgValue =
3732           LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3733     }
3734 
3735     // If value is passed via pointer - do a load.
3736     if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3737       ArgValue =
3738           DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3739 
3740     InVals.push_back(ArgValue);
3741   }
3742 
3743   for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3744     // Swift calling convention does not require we copy the sret argument
3745     // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3746     if (CallConv == CallingConv::Swift)
3747       continue;
3748 
3749     // All x86 ABIs require that for returning structs by value we copy the
3750     // sret argument into %rax/%eax (depending on ABI) for the return. Save
3751     // the argument into a virtual register so that we can access it from the
3752     // return points.
3753     if (Ins[I].Flags.isSRet()) {
3754       Register Reg = FuncInfo->getSRetReturnReg();
3755       if (!Reg) {
3756         MVT PtrTy = getPointerTy(DAG.getDataLayout());
3757         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3758         FuncInfo->setSRetReturnReg(Reg);
3759       }
3760       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3761       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3762       break;
3763     }
3764   }
3765 
3766   unsigned StackSize = CCInfo.getNextStackOffset();
3767   // Align stack specially for tail calls.
3768   if (shouldGuaranteeTCO(CallConv,
3769                          MF.getTarget().Options.GuaranteedTailCallOpt))
3770     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3771 
3772   if (IsVarArg)
3773     VarArgsLoweringHelper(FuncInfo, dl, DAG, Subtarget, CallConv, CCInfo)
3774         .lowerVarArgsParameters(Chain, StackSize);
3775 
3776   // Some CCs need callee pop.
3777   if (X86::isCalleePop(CallConv, Is64Bit, IsVarArg,
3778                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
3779     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3780   } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3781     // X86 interrupts must pop the error code (and the alignment padding) if
3782     // present.
3783     FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3784   } else {
3785     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3786     // If this is an sret function, the return should pop the hidden pointer.
3787     if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3788         !Subtarget.getTargetTriple().isOSMSVCRT() &&
3789         argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3790       FuncInfo->setBytesToPopOnReturn(4);
3791   }
3792 
3793   if (!Is64Bit) {
3794     // RegSaveFrameIndex is X86-64 only.
3795     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3796   }
3797 
3798   FuncInfo->setArgumentStackSize(StackSize);
3799 
3800   if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3801     EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3802     if (Personality == EHPersonality::CoreCLR) {
3803       assert(Is64Bit);
3804       // TODO: Add a mechanism to frame lowering that will allow us to indicate
3805       // that we'd prefer this slot be allocated towards the bottom of the frame
3806       // (i.e. near the stack pointer after allocating the frame).  Every
3807       // funclet needs a copy of this slot in its (mostly empty) frame, and the
3808       // offset from the bottom of this and each funclet's frame must be the
3809       // same, so the size of funclets' (mostly empty) frames is dictated by
3810       // how far this slot is from the bottom (since they allocate just enough
3811       // space to accommodate holding this slot at the correct offset).
3812       int PSPSymFI = MFI.CreateStackObject(8, Align(8), /*isSpillSlot=*/false);
3813       EHInfo->PSPSymFrameIdx = PSPSymFI;
3814     }
3815   }
3816 
3817   if (CallConv == CallingConv::X86_RegCall ||
3818       F.hasFnAttribute("no_caller_saved_registers")) {
3819     MachineRegisterInfo &MRI = MF.getRegInfo();
3820     for (std::pair<Register, Register> Pair : MRI.liveins())
3821       MRI.disableCalleeSavedRegister(Pair.first);
3822   }
3823 
3824   return Chain;
3825 }
3826 
3827 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3828                                             SDValue Arg, const SDLoc &dl,
3829                                             SelectionDAG &DAG,
3830                                             const CCValAssign &VA,
3831                                             ISD::ArgFlagsTy Flags,
3832                                             bool isByVal) const {
3833   unsigned LocMemOffset = VA.getLocMemOffset();
3834   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3835   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3836                        StackPtr, PtrOff);
3837   if (isByVal)
3838     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3839 
3840   return DAG.getStore(
3841       Chain, dl, Arg, PtrOff,
3842       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3843 }
3844 
3845 /// Emit a load of return address if tail call
3846 /// optimization is performed and it is required.
3847 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3848     SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3849     bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3850   // Adjust the Return address stack slot.
3851   EVT VT = getPointerTy(DAG.getDataLayout());
3852   OutRetAddr = getReturnAddressFrameIndex(DAG);
3853 
3854   // Load the "old" Return address.
3855   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3856   return SDValue(OutRetAddr.getNode(), 1);
3857 }
3858 
3859 /// Emit a store of the return address if tail call
3860 /// optimization is performed and it is required (FPDiff!=0).
3861 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3862                                         SDValue Chain, SDValue RetAddrFrIdx,
3863                                         EVT PtrVT, unsigned SlotSize,
3864                                         int FPDiff, const SDLoc &dl) {
3865   // Store the return address to the appropriate stack slot.
3866   if (!FPDiff) return Chain;
3867   // Calculate the new stack slot for the return address.
3868   int NewReturnAddrFI =
3869     MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3870                                          false);
3871   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3872   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3873                        MachinePointerInfo::getFixedStack(
3874                            DAG.getMachineFunction(), NewReturnAddrFI));
3875   return Chain;
3876 }
3877 
3878 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3879 /// operation of specified width.
3880 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3881                        SDValue V2) {
3882   unsigned NumElems = VT.getVectorNumElements();
3883   SmallVector<int, 8> Mask;
3884   Mask.push_back(NumElems);
3885   for (unsigned i = 1; i != NumElems; ++i)
3886     Mask.push_back(i);
3887   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3888 }
3889 
3890 SDValue
3891 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3892                              SmallVectorImpl<SDValue> &InVals) const {
3893   SelectionDAG &DAG                     = CLI.DAG;
3894   SDLoc &dl                             = CLI.DL;
3895   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3896   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3897   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3898   SDValue Chain                         = CLI.Chain;
3899   SDValue Callee                        = CLI.Callee;
3900   CallingConv::ID CallConv              = CLI.CallConv;
3901   bool &isTailCall                      = CLI.IsTailCall;
3902   bool isVarArg                         = CLI.IsVarArg;
3903 
3904   MachineFunction &MF = DAG.getMachineFunction();
3905   bool Is64Bit        = Subtarget.is64Bit();
3906   bool IsWin64        = Subtarget.isCallingConvWin64(CallConv);
3907   StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3908   bool IsSibcall      = false;
3909   bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
3910       CallConv == CallingConv::Tail;
3911   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3912   const auto *CI = dyn_cast_or_null<CallInst>(CLI.CB);
3913   const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3914   bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3915                  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3916   const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CB);
3917   bool HasNoCfCheck =
3918       (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3919 	bool IsIndirectCall = (CI && CI->isIndirectCall());
3920   const Module *M = MF.getMMI().getModule();
3921   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3922 
3923   MachineFunction::CallSiteInfo CSInfo;
3924   if (CallConv == CallingConv::X86_INTR)
3925     report_fatal_error("X86 interrupts may not be called directly");
3926 
3927   if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO) {
3928     // If we are using a GOT, disable tail calls to external symbols with
3929     // default visibility. Tail calling such a symbol requires using a GOT
3930     // relocation, which forces early binding of the symbol. This breaks code
3931     // that require lazy function symbol resolution. Using musttail or
3932     // GuaranteedTailCallOpt will override this.
3933     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3934     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3935                G->getGlobal()->hasDefaultVisibility()))
3936       isTailCall = false;
3937   }
3938 
3939   bool IsMustTail = CLI.CB && CLI.CB->isMustTailCall();
3940   if (IsMustTail) {
3941     // Force this to be a tail call.  The verifier rules are enough to ensure
3942     // that we can lower this successfully without moving the return address
3943     // around.
3944     isTailCall = true;
3945   } else if (isTailCall) {
3946     // Check if it's really possible to do a tail call.
3947     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3948                     isVarArg, SR != NotStructReturn,
3949                     MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3950                     Outs, OutVals, Ins, DAG);
3951 
3952     // Sibcalls are automatically detected tailcalls which do not require
3953     // ABI changes.
3954     if (!IsGuaranteeTCO && isTailCall)
3955       IsSibcall = true;
3956 
3957     if (isTailCall)
3958       ++NumTailCalls;
3959   }
3960 
3961   assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3962          "Var args not supported with calling convention fastcc, ghc or hipe");
3963 
3964   // Analyze operands of the call, assigning locations to each operand.
3965   SmallVector<CCValAssign, 16> ArgLocs;
3966   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3967 
3968   // Allocate shadow area for Win64.
3969   if (IsWin64)
3970     CCInfo.AllocateStack(32, Align(8));
3971 
3972   CCInfo.AnalyzeArguments(Outs, CC_X86);
3973 
3974   // In vectorcall calling convention a second pass is required for the HVA
3975   // types.
3976   if (CallingConv::X86_VectorCall == CallConv) {
3977     CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3978   }
3979 
3980   // Get a count of how many bytes are to be pushed on the stack.
3981   unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3982   if (IsSibcall)
3983     // This is a sibcall. The memory operands are available in caller's
3984     // own caller's stack.
3985     NumBytes = 0;
3986   else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
3987     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3988 
3989   int FPDiff = 0;
3990   if (isTailCall && !IsSibcall && !IsMustTail) {
3991     // Lower arguments at fp - stackoffset + fpdiff.
3992     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3993 
3994     FPDiff = NumBytesCallerPushed - NumBytes;
3995 
3996     // Set the delta of movement of the returnaddr stackslot.
3997     // But only set if delta is greater than previous delta.
3998     if (FPDiff < X86Info->getTCReturnAddrDelta())
3999       X86Info->setTCReturnAddrDelta(FPDiff);
4000   }
4001 
4002   unsigned NumBytesToPush = NumBytes;
4003   unsigned NumBytesToPop = NumBytes;
4004 
4005   // If we have an inalloca argument, all stack space has already been allocated
4006   // for us and be right at the top of the stack.  We don't support multiple
4007   // arguments passed in memory when using inalloca.
4008   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
4009     NumBytesToPush = 0;
4010     if (!ArgLocs.back().isMemLoc())
4011       report_fatal_error("cannot use inalloca attribute on a register "
4012                          "parameter");
4013     if (ArgLocs.back().getLocMemOffset() != 0)
4014       report_fatal_error("any parameter with the inalloca attribute must be "
4015                          "the only memory argument");
4016   } else if (CLI.IsPreallocated) {
4017     assert(ArgLocs.back().isMemLoc() &&
4018            "cannot use preallocated attribute on a register "
4019            "parameter");
4020     SmallVector<size_t, 4> PreallocatedOffsets;
4021     for (size_t i = 0; i < CLI.OutVals.size(); ++i) {
4022       if (CLI.CB->paramHasAttr(i, Attribute::Preallocated)) {
4023         PreallocatedOffsets.push_back(ArgLocs[i].getLocMemOffset());
4024       }
4025     }
4026     auto *MFI = DAG.getMachineFunction().getInfo<X86MachineFunctionInfo>();
4027     size_t PreallocatedId = MFI->getPreallocatedIdForCallSite(CLI.CB);
4028     MFI->setPreallocatedStackSize(PreallocatedId, NumBytes);
4029     MFI->setPreallocatedArgOffsets(PreallocatedId, PreallocatedOffsets);
4030     NumBytesToPush = 0;
4031   }
4032 
4033   if (!IsSibcall && !IsMustTail)
4034     Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
4035                                  NumBytes - NumBytesToPush, dl);
4036 
4037   SDValue RetAddrFrIdx;
4038   // Load return address for tail calls.
4039   if (isTailCall && FPDiff)
4040     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
4041                                     Is64Bit, FPDiff, dl);
4042 
4043   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
4044   SmallVector<SDValue, 8> MemOpChains;
4045   SDValue StackPtr;
4046 
4047   // The next loop assumes that the locations are in the same order of the
4048   // input arguments.
4049   assert(isSortedByValueNo(ArgLocs) &&
4050          "Argument Location list must be sorted before lowering");
4051 
4052   // Walk the register/memloc assignments, inserting copies/loads.  In the case
4053   // of tail call optimization arguments are handle later.
4054   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4055   for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
4056        ++I, ++OutIndex) {
4057     assert(OutIndex < Outs.size() && "Invalid Out index");
4058     // Skip inalloca/preallocated arguments, they have already been written.
4059     ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
4060     if (Flags.isInAlloca() || Flags.isPreallocated())
4061       continue;
4062 
4063     CCValAssign &VA = ArgLocs[I];
4064     EVT RegVT = VA.getLocVT();
4065     SDValue Arg = OutVals[OutIndex];
4066     bool isByVal = Flags.isByVal();
4067 
4068     // Promote the value if needed.
4069     switch (VA.getLocInfo()) {
4070     default: llvm_unreachable("Unknown loc info!");
4071     case CCValAssign::Full: break;
4072     case CCValAssign::SExt:
4073       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
4074       break;
4075     case CCValAssign::ZExt:
4076       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
4077       break;
4078     case CCValAssign::AExt:
4079       if (Arg.getValueType().isVector() &&
4080           Arg.getValueType().getVectorElementType() == MVT::i1)
4081         Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
4082       else if (RegVT.is128BitVector()) {
4083         // Special case: passing MMX values in XMM registers.
4084         Arg = DAG.getBitcast(MVT::i64, Arg);
4085         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
4086         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
4087       } else
4088         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
4089       break;
4090     case CCValAssign::BCvt:
4091       Arg = DAG.getBitcast(RegVT, Arg);
4092       break;
4093     case CCValAssign::Indirect: {
4094       if (isByVal) {
4095         // Memcpy the argument to a temporary stack slot to prevent
4096         // the caller from seeing any modifications the callee may make
4097         // as guaranteed by the `byval` attribute.
4098         int FrameIdx = MF.getFrameInfo().CreateStackObject(
4099             Flags.getByValSize(),
4100             std::max(Align(16), Flags.getNonZeroByValAlign()), false);
4101         SDValue StackSlot =
4102             DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
4103         Chain =
4104             CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
4105         // From now on treat this as a regular pointer
4106         Arg = StackSlot;
4107         isByVal = false;
4108       } else {
4109         // Store the argument.
4110         SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
4111         int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
4112         Chain = DAG.getStore(
4113             Chain, dl, Arg, SpillSlot,
4114             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4115         Arg = SpillSlot;
4116       }
4117       break;
4118     }
4119     }
4120 
4121     if (VA.needsCustom()) {
4122       assert(VA.getValVT() == MVT::v64i1 &&
4123              "Currently the only custom case is when we split v64i1 to 2 regs");
4124       // Split v64i1 value into two registers
4125       Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
4126     } else if (VA.isRegLoc()) {
4127       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4128       const TargetOptions &Options = DAG.getTarget().Options;
4129       if (Options.EmitCallSiteInfo)
4130         CSInfo.emplace_back(VA.getLocReg(), I);
4131       if (isVarArg && IsWin64) {
4132         // Win64 ABI requires argument XMM reg to be copied to the corresponding
4133         // shadow reg if callee is a varargs function.
4134         Register ShadowReg;
4135         switch (VA.getLocReg()) {
4136         case X86::XMM0: ShadowReg = X86::RCX; break;
4137         case X86::XMM1: ShadowReg = X86::RDX; break;
4138         case X86::XMM2: ShadowReg = X86::R8; break;
4139         case X86::XMM3: ShadowReg = X86::R9; break;
4140         }
4141         if (ShadowReg)
4142           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
4143       }
4144     } else if (!IsSibcall && (!isTailCall || isByVal)) {
4145       assert(VA.isMemLoc());
4146       if (!StackPtr.getNode())
4147         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4148                                       getPointerTy(DAG.getDataLayout()));
4149       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
4150                                              dl, DAG, VA, Flags, isByVal));
4151     }
4152   }
4153 
4154   if (!MemOpChains.empty())
4155     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4156 
4157   if (Subtarget.isPICStyleGOT()) {
4158     // ELF / PIC requires GOT in the EBX register before function calls via PLT
4159     // GOT pointer (except regcall).
4160     if (!isTailCall) {
4161       // Indirect call with RegCall calling convertion may use up all the
4162       // general registers, so it is not suitable to bind EBX reister for
4163       // GOT address, just let register allocator handle it.
4164       if (CallConv != CallingConv::X86_RegCall)
4165         RegsToPass.push_back(std::make_pair(
4166           Register(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
4167                                           getPointerTy(DAG.getDataLayout()))));
4168     } else {
4169       // If we are tail calling and generating PIC/GOT style code load the
4170       // address of the callee into ECX. The value in ecx is used as target of
4171       // the tail jump. This is done to circumvent the ebx/callee-saved problem
4172       // for tail calls on PIC/GOT architectures. Normally we would just put the
4173       // address of GOT into ebx and then call target@PLT. But for tail calls
4174       // ebx would be restored (since ebx is callee saved) before jumping to the
4175       // target@PLT.
4176 
4177       // Note: The actual moving to ECX is done further down.
4178       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4179       if (G && !G->getGlobal()->hasLocalLinkage() &&
4180           G->getGlobal()->hasDefaultVisibility())
4181         Callee = LowerGlobalAddress(Callee, DAG);
4182       else if (isa<ExternalSymbolSDNode>(Callee))
4183         Callee = LowerExternalSymbol(Callee, DAG);
4184     }
4185   }
4186 
4187   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
4188     // From AMD64 ABI document:
4189     // For calls that may call functions that use varargs or stdargs
4190     // (prototype-less calls or calls to functions containing ellipsis (...) in
4191     // the declaration) %al is used as hidden argument to specify the number
4192     // of SSE registers used. The contents of %al do not need to match exactly
4193     // the number of registers, but must be an ubound on the number of SSE
4194     // registers used and is in the range 0 - 8 inclusive.
4195 
4196     // Count the number of XMM registers allocated.
4197     static const MCPhysReg XMMArgRegs[] = {
4198       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4199       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
4200     };
4201     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
4202     assert((Subtarget.hasSSE1() || !NumXMMRegs)
4203            && "SSE registers cannot be used when SSE is disabled");
4204     RegsToPass.push_back(std::make_pair(Register(X86::AL),
4205                                         DAG.getConstant(NumXMMRegs, dl,
4206                                                         MVT::i8)));
4207   }
4208 
4209   if (isVarArg && IsMustTail) {
4210     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
4211     for (const auto &F : Forwards) {
4212       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
4213       RegsToPass.push_back(std::make_pair(F.PReg, Val));
4214     }
4215   }
4216 
4217   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
4218   // don't need this because the eligibility check rejects calls that require
4219   // shuffling arguments passed in memory.
4220   if (!IsSibcall && isTailCall) {
4221     // Force all the incoming stack arguments to be loaded from the stack
4222     // before any new outgoing arguments are stored to the stack, because the
4223     // outgoing stack slots may alias the incoming argument stack slots, and
4224     // the alias isn't otherwise explicit. This is slightly more conservative
4225     // than necessary, because it means that each store effectively depends
4226     // on every argument instead of just those arguments it would clobber.
4227     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
4228 
4229     SmallVector<SDValue, 8> MemOpChains2;
4230     SDValue FIN;
4231     int FI = 0;
4232     for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
4233          ++I, ++OutsIndex) {
4234       CCValAssign &VA = ArgLocs[I];
4235 
4236       if (VA.isRegLoc()) {
4237         if (VA.needsCustom()) {
4238           assert((CallConv == CallingConv::X86_RegCall) &&
4239                  "Expecting custom case only in regcall calling convention");
4240           // This means that we are in special case where one argument was
4241           // passed through two register locations - Skip the next location
4242           ++I;
4243         }
4244 
4245         continue;
4246       }
4247 
4248       assert(VA.isMemLoc());
4249       SDValue Arg = OutVals[OutsIndex];
4250       ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
4251       // Skip inalloca/preallocated arguments.  They don't require any work.
4252       if (Flags.isInAlloca() || Flags.isPreallocated())
4253         continue;
4254       // Create frame index.
4255       int32_t Offset = VA.getLocMemOffset()+FPDiff;
4256       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
4257       FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4258       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4259 
4260       if (Flags.isByVal()) {
4261         // Copy relative to framepointer.
4262         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
4263         if (!StackPtr.getNode())
4264           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
4265                                         getPointerTy(DAG.getDataLayout()));
4266         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
4267                              StackPtr, Source);
4268 
4269         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
4270                                                          ArgChain,
4271                                                          Flags, DAG, dl));
4272       } else {
4273         // Store relative to framepointer.
4274         MemOpChains2.push_back(DAG.getStore(
4275             ArgChain, dl, Arg, FIN,
4276             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4277       }
4278     }
4279 
4280     if (!MemOpChains2.empty())
4281       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4282 
4283     // Store the return address to the appropriate stack slot.
4284     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
4285                                      getPointerTy(DAG.getDataLayout()),
4286                                      RegInfo->getSlotSize(), FPDiff, dl);
4287   }
4288 
4289   // Build a sequence of copy-to-reg nodes chained together with token chain
4290   // and flag operands which copy the outgoing args into registers.
4291   SDValue InFlag;
4292   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4293     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4294                              RegsToPass[i].second, InFlag);
4295     InFlag = Chain.getValue(1);
4296   }
4297 
4298   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
4299     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
4300     // In the 64-bit large code model, we have to make all calls
4301     // through a register, since the call instruction's 32-bit
4302     // pc-relative offset may not be large enough to hold the whole
4303     // address.
4304   } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4305              Callee->getOpcode() == ISD::ExternalSymbol) {
4306     // Lower direct calls to global addresses and external symbols. Setting
4307     // ForCall to true here has the effect of removing WrapperRIP when possible
4308     // to allow direct calls to be selected without first materializing the
4309     // address into a register.
4310     Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4311   } else if (Subtarget.isTarget64BitILP32() &&
4312              Callee->getValueType(0) == MVT::i32) {
4313     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4314     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4315   }
4316 
4317   // Returns a chain & a flag for retval copy to use.
4318   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4319   SmallVector<SDValue, 8> Ops;
4320 
4321   if (!IsSibcall && isTailCall && !IsMustTail) {
4322     Chain = DAG.getCALLSEQ_END(Chain,
4323                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4324                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4325     InFlag = Chain.getValue(1);
4326   }
4327 
4328   Ops.push_back(Chain);
4329   Ops.push_back(Callee);
4330 
4331   if (isTailCall)
4332     Ops.push_back(DAG.getTargetConstant(FPDiff, dl, MVT::i32));
4333 
4334   // Add argument registers to the end of the list so that they are known live
4335   // into the call.
4336   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4337     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4338                                   RegsToPass[i].second.getValueType()));
4339 
4340   // Add a register mask operand representing the call-preserved registers.
4341   // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
4342   // set X86_INTR calling convention because it has the same CSR mask
4343   // (same preserved registers).
4344   const uint32_t *Mask = RegInfo->getCallPreservedMask(
4345       MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
4346   assert(Mask && "Missing call preserved mask for calling convention");
4347 
4348   // If this is an invoke in a 32-bit function using a funclet-based
4349   // personality, assume the function clobbers all registers. If an exception
4350   // is thrown, the runtime will not restore CSRs.
4351   // FIXME: Model this more precisely so that we can register allocate across
4352   // the normal edge and spill and fill across the exceptional edge.
4353   if (!Is64Bit && CLI.CB && isa<InvokeInst>(CLI.CB)) {
4354     const Function &CallerFn = MF.getFunction();
4355     EHPersonality Pers =
4356         CallerFn.hasPersonalityFn()
4357             ? classifyEHPersonality(CallerFn.getPersonalityFn())
4358             : EHPersonality::Unknown;
4359     if (isFuncletEHPersonality(Pers))
4360       Mask = RegInfo->getNoPreservedMask();
4361   }
4362 
4363   // Define a new register mask from the existing mask.
4364   uint32_t *RegMask = nullptr;
4365 
4366   // In some calling conventions we need to remove the used physical registers
4367   // from the reg mask.
4368   if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4369     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4370 
4371     // Allocate a new Reg Mask and copy Mask.
4372     RegMask = MF.allocateRegMask();
4373     unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4374     memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4375 
4376     // Make sure all sub registers of the argument registers are reset
4377     // in the RegMask.
4378     for (auto const &RegPair : RegsToPass)
4379       for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4380            SubRegs.isValid(); ++SubRegs)
4381         RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4382 
4383     // Create the RegMask Operand according to our updated mask.
4384     Ops.push_back(DAG.getRegisterMask(RegMask));
4385   } else {
4386     // Create the RegMask Operand according to the static mask.
4387     Ops.push_back(DAG.getRegisterMask(Mask));
4388   }
4389 
4390   if (InFlag.getNode())
4391     Ops.push_back(InFlag);
4392 
4393   if (isTailCall) {
4394     // We used to do:
4395     //// If this is the first return lowered for this function, add the regs
4396     //// to the liveout set for the function.
4397     // This isn't right, although it's probably harmless on x86; liveouts
4398     // should be computed from returns not tail calls.  Consider a void
4399     // function making a tail call to a function returning int.
4400     MF.getFrameInfo().setHasTailCall();
4401     SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4402     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4403     return Ret;
4404   }
4405 
4406   if (HasNoCfCheck && IsCFProtectionSupported && IsIndirectCall) {
4407     Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4408   } else {
4409     Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4410   }
4411   InFlag = Chain.getValue(1);
4412   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
4413   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4414 
4415   // Save heapallocsite metadata.
4416   if (CLI.CB)
4417     if (MDNode *HeapAlloc = CLI.CB->getMetadata("heapallocsite"))
4418       DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4419 
4420   // Create the CALLSEQ_END node.
4421   unsigned NumBytesForCalleeToPop;
4422   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4423                        DAG.getTarget().Options.GuaranteedTailCallOpt))
4424     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
4425   else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4426            !Subtarget.getTargetTriple().isOSMSVCRT() &&
4427            SR == StackStructReturn)
4428     // If this is a call to a struct-return function, the callee
4429     // pops the hidden struct pointer, so we have to push it back.
4430     // This is common for Darwin/X86, Linux & Mingw32 targets.
4431     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4432     NumBytesForCalleeToPop = 4;
4433   else
4434     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
4435 
4436   // Returns a flag for retval copy to use.
4437   if (!IsSibcall) {
4438     Chain = DAG.getCALLSEQ_END(Chain,
4439                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4440                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4441                                                      true),
4442                                InFlag, dl);
4443     InFlag = Chain.getValue(1);
4444   }
4445 
4446   // Handle result values, copying them out of physregs into vregs that we
4447   // return.
4448   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4449                          InVals, RegMask);
4450 }
4451 
4452 //===----------------------------------------------------------------------===//
4453 //                Fast Calling Convention (tail call) implementation
4454 //===----------------------------------------------------------------------===//
4455 
4456 //  Like std call, callee cleans arguments, convention except that ECX is
4457 //  reserved for storing the tail called function address. Only 2 registers are
4458 //  free for argument passing (inreg). Tail call optimization is performed
4459 //  provided:
4460 //                * tailcallopt is enabled
4461 //                * caller/callee are fastcc
4462 //  On X86_64 architecture with GOT-style position independent code only local
4463 //  (within module) calls are supported at the moment.
4464 //  To keep the stack aligned according to platform abi the function
4465 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
4466 //  of stack alignment. (Dynamic linkers need this - Darwin's dyld for example)
4467 //  If a tail called function callee has more arguments than the caller the
4468 //  caller needs to make sure that there is room to move the RETADDR to. This is
4469 //  achieved by reserving an area the size of the argument delta right after the
4470 //  original RETADDR, but before the saved framepointer or the spilled registers
4471 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4472 //  stack layout:
4473 //    arg1
4474 //    arg2
4475 //    RETADDR
4476 //    [ new RETADDR
4477 //      move area ]
4478 //    (possible EBP)
4479 //    ESI
4480 //    EDI
4481 //    local1 ..
4482 
4483 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4484 /// requirement.
4485 unsigned
4486 X86TargetLowering::GetAlignedArgumentStackSize(const unsigned StackSize,
4487                                                SelectionDAG &DAG) const {
4488   const Align StackAlignment = Subtarget.getFrameLowering()->getStackAlign();
4489   const uint64_t SlotSize = Subtarget.getRegisterInfo()->getSlotSize();
4490   assert(StackSize % SlotSize == 0 &&
4491          "StackSize must be a multiple of SlotSize");
4492   return alignTo(StackSize + SlotSize, StackAlignment) - SlotSize;
4493 }
4494 
4495 /// Return true if the given stack call argument is already available in the
4496 /// same position (relatively) of the caller's incoming argument stack.
4497 static
4498 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4499                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4500                          const X86InstrInfo *TII, const CCValAssign &VA) {
4501   unsigned Bytes = Arg.getValueSizeInBits() / 8;
4502 
4503   for (;;) {
4504     // Look through nodes that don't alter the bits of the incoming value.
4505     unsigned Op = Arg.getOpcode();
4506     if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4507       Arg = Arg.getOperand(0);
4508       continue;
4509     }
4510     if (Op == ISD::TRUNCATE) {
4511       const SDValue &TruncInput = Arg.getOperand(0);
4512       if (TruncInput.getOpcode() == ISD::AssertZext &&
4513           cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4514               Arg.getValueType()) {
4515         Arg = TruncInput.getOperand(0);
4516         continue;
4517       }
4518     }
4519     break;
4520   }
4521 
4522   int FI = INT_MAX;
4523   if (Arg.getOpcode() == ISD::CopyFromReg) {
4524     Register VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4525     if (!VR.isVirtual())
4526       return false;
4527     MachineInstr *Def = MRI->getVRegDef(VR);
4528     if (!Def)
4529       return false;
4530     if (!Flags.isByVal()) {
4531       if (!TII->isLoadFromStackSlot(*Def, FI))
4532         return false;
4533     } else {
4534       unsigned Opcode = Def->getOpcode();
4535       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4536            Opcode == X86::LEA64_32r) &&
4537           Def->getOperand(1).isFI()) {
4538         FI = Def->getOperand(1).getIndex();
4539         Bytes = Flags.getByValSize();
4540       } else
4541         return false;
4542     }
4543   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4544     if (Flags.isByVal())
4545       // ByVal argument is passed in as a pointer but it's now being
4546       // dereferenced. e.g.
4547       // define @foo(%struct.X* %A) {
4548       //   tail call @bar(%struct.X* byval %A)
4549       // }
4550       return false;
4551     SDValue Ptr = Ld->getBasePtr();
4552     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4553     if (!FINode)
4554       return false;
4555     FI = FINode->getIndex();
4556   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4557     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4558     FI = FINode->getIndex();
4559     Bytes = Flags.getByValSize();
4560   } else
4561     return false;
4562 
4563   assert(FI != INT_MAX);
4564   if (!MFI.isFixedObjectIndex(FI))
4565     return false;
4566 
4567   if (Offset != MFI.getObjectOffset(FI))
4568     return false;
4569 
4570   // If this is not byval, check that the argument stack object is immutable.
4571   // inalloca and argument copy elision can create mutable argument stack
4572   // objects. Byval objects can be mutated, but a byval call intends to pass the
4573   // mutated memory.
4574   if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4575     return false;
4576 
4577   if (VA.getLocVT().getFixedSizeInBits() >
4578       Arg.getValueSizeInBits().getFixedSize()) {
4579     // If the argument location is wider than the argument type, check that any
4580     // extension flags match.
4581     if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4582         Flags.isSExt() != MFI.isObjectSExt(FI)) {
4583       return false;
4584     }
4585   }
4586 
4587   return Bytes == MFI.getObjectSize(FI);
4588 }
4589 
4590 /// Check whether the call is eligible for tail call optimization. Targets
4591 /// that want to do tail call optimization should implement this function.
4592 bool X86TargetLowering::IsEligibleForTailCallOptimization(
4593     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4594     bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4595     const SmallVectorImpl<ISD::OutputArg> &Outs,
4596     const SmallVectorImpl<SDValue> &OutVals,
4597     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4598   if (!mayTailCallThisCC(CalleeCC))
4599     return false;
4600 
4601   // If -tailcallopt is specified, make fastcc functions tail-callable.
4602   MachineFunction &MF = DAG.getMachineFunction();
4603   const Function &CallerF = MF.getFunction();
4604 
4605   // If the function return type is x86_fp80 and the callee return type is not,
4606   // then the FP_EXTEND of the call result is not a nop. It's not safe to
4607   // perform a tailcall optimization here.
4608   if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4609     return false;
4610 
4611   CallingConv::ID CallerCC = CallerF.getCallingConv();
4612   bool CCMatch = CallerCC == CalleeCC;
4613   bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4614   bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4615   bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
4616       CalleeCC == CallingConv::Tail;
4617 
4618   // Win64 functions have extra shadow space for argument homing. Don't do the
4619   // sibcall if the caller and callee have mismatched expectations for this
4620   // space.
4621   if (IsCalleeWin64 != IsCallerWin64)
4622     return false;
4623 
4624   if (IsGuaranteeTCO) {
4625     if (canGuaranteeTCO(CalleeCC) && CCMatch)
4626       return true;
4627     return false;
4628   }
4629 
4630   // Look for obvious safe cases to perform tail call optimization that do not
4631   // require ABI changes. This is what gcc calls sibcall.
4632 
4633   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4634   // emit a special epilogue.
4635   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4636   if (RegInfo->needsStackRealignment(MF))
4637     return false;
4638 
4639   // Also avoid sibcall optimization if either caller or callee uses struct
4640   // return semantics.
4641   if (isCalleeStructRet || isCallerStructRet)
4642     return false;
4643 
4644   // Do not sibcall optimize vararg calls unless all arguments are passed via
4645   // registers.
4646   LLVMContext &C = *DAG.getContext();
4647   if (isVarArg && !Outs.empty()) {
4648     // Optimizing for varargs on Win64 is unlikely to be safe without
4649     // additional testing.
4650     if (IsCalleeWin64 || IsCallerWin64)
4651       return false;
4652 
4653     SmallVector<CCValAssign, 16> ArgLocs;
4654     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4655 
4656     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4657     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4658       if (!ArgLocs[i].isRegLoc())
4659         return false;
4660   }
4661 
4662   // If the call result is in ST0 / ST1, it needs to be popped off the x87
4663   // stack.  Therefore, if it's not used by the call it is not safe to optimize
4664   // this into a sibcall.
4665   bool Unused = false;
4666   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4667     if (!Ins[i].Used) {
4668       Unused = true;
4669       break;
4670     }
4671   }
4672   if (Unused) {
4673     SmallVector<CCValAssign, 16> RVLocs;
4674     CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4675     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4676     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4677       CCValAssign &VA = RVLocs[i];
4678       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4679         return false;
4680     }
4681   }
4682 
4683   // Check that the call results are passed in the same way.
4684   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4685                                   RetCC_X86, RetCC_X86))
4686     return false;
4687   // The callee has to preserve all registers the caller needs to preserve.
4688   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4689   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4690   if (!CCMatch) {
4691     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4692     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4693       return false;
4694   }
4695 
4696   unsigned StackArgsSize = 0;
4697 
4698   // If the callee takes no arguments then go on to check the results of the
4699   // call.
4700   if (!Outs.empty()) {
4701     // Check if stack adjustment is needed. For now, do not do this if any
4702     // argument is passed on the stack.
4703     SmallVector<CCValAssign, 16> ArgLocs;
4704     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4705 
4706     // Allocate shadow area for Win64
4707     if (IsCalleeWin64)
4708       CCInfo.AllocateStack(32, Align(8));
4709 
4710     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4711     StackArgsSize = CCInfo.getNextStackOffset();
4712 
4713     if (CCInfo.getNextStackOffset()) {
4714       // Check if the arguments are already laid out in the right way as
4715       // the caller's fixed stack objects.
4716       MachineFrameInfo &MFI = MF.getFrameInfo();
4717       const MachineRegisterInfo *MRI = &MF.getRegInfo();
4718       const X86InstrInfo *TII = Subtarget.getInstrInfo();
4719       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4720         CCValAssign &VA = ArgLocs[i];
4721         SDValue Arg = OutVals[i];
4722         ISD::ArgFlagsTy Flags = Outs[i].Flags;
4723         if (VA.getLocInfo() == CCValAssign::Indirect)
4724           return false;
4725         if (!VA.isRegLoc()) {
4726           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4727                                    MFI, MRI, TII, VA))
4728             return false;
4729         }
4730       }
4731     }
4732 
4733     bool PositionIndependent = isPositionIndependent();
4734     // If the tailcall address may be in a register, then make sure it's
4735     // possible to register allocate for it. In 32-bit, the call address can
4736     // only target EAX, EDX, or ECX since the tail call must be scheduled after
4737     // callee-saved registers are restored. These happen to be the same
4738     // registers used to pass 'inreg' arguments so watch out for those.
4739     if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4740                                   !isa<ExternalSymbolSDNode>(Callee)) ||
4741                                  PositionIndependent)) {
4742       unsigned NumInRegs = 0;
4743       // In PIC we need an extra register to formulate the address computation
4744       // for the callee.
4745       unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4746 
4747       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4748         CCValAssign &VA = ArgLocs[i];
4749         if (!VA.isRegLoc())
4750           continue;
4751         Register Reg = VA.getLocReg();
4752         switch (Reg) {
4753         default: break;
4754         case X86::EAX: case X86::EDX: case X86::ECX:
4755           if (++NumInRegs == MaxInRegs)
4756             return false;
4757           break;
4758         }
4759       }
4760     }
4761 
4762     const MachineRegisterInfo &MRI = MF.getRegInfo();
4763     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4764       return false;
4765   }
4766 
4767   bool CalleeWillPop =
4768       X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4769                        MF.getTarget().Options.GuaranteedTailCallOpt);
4770 
4771   if (unsigned BytesToPop =
4772           MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4773     // If we have bytes to pop, the callee must pop them.
4774     bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4775     if (!CalleePopMatches)
4776       return false;
4777   } else if (CalleeWillPop && StackArgsSize > 0) {
4778     // If we don't have bytes to pop, make sure the callee doesn't pop any.
4779     return false;
4780   }
4781 
4782   return true;
4783 }
4784 
4785 FastISel *
4786 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4787                                   const TargetLibraryInfo *libInfo) const {
4788   return X86::createFastISel(funcInfo, libInfo);
4789 }
4790 
4791 //===----------------------------------------------------------------------===//
4792 //                           Other Lowering Hooks
4793 //===----------------------------------------------------------------------===//
4794 
4795 static bool MayFoldLoad(SDValue Op) {
4796   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4797 }
4798 
4799 static bool MayFoldIntoStore(SDValue Op) {
4800   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4801 }
4802 
4803 static bool MayFoldIntoZeroExtend(SDValue Op) {
4804   if (Op.hasOneUse()) {
4805     unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4806     return (ISD::ZERO_EXTEND == Opcode);
4807   }
4808   return false;
4809 }
4810 
4811 static bool isTargetShuffle(unsigned Opcode) {
4812   switch(Opcode) {
4813   default: return false;
4814   case X86ISD::BLENDI:
4815   case X86ISD::PSHUFB:
4816   case X86ISD::PSHUFD:
4817   case X86ISD::PSHUFHW:
4818   case X86ISD::PSHUFLW:
4819   case X86ISD::SHUFP:
4820   case X86ISD::INSERTPS:
4821   case X86ISD::EXTRQI:
4822   case X86ISD::INSERTQI:
4823   case X86ISD::VALIGN:
4824   case X86ISD::PALIGNR:
4825   case X86ISD::VSHLDQ:
4826   case X86ISD::VSRLDQ:
4827   case X86ISD::MOVLHPS:
4828   case X86ISD::MOVHLPS:
4829   case X86ISD::MOVSHDUP:
4830   case X86ISD::MOVSLDUP:
4831   case X86ISD::MOVDDUP:
4832   case X86ISD::MOVSS:
4833   case X86ISD::MOVSD:
4834   case X86ISD::UNPCKL:
4835   case X86ISD::UNPCKH:
4836   case X86ISD::VBROADCAST:
4837   case X86ISD::VPERMILPI:
4838   case X86ISD::VPERMILPV:
4839   case X86ISD::VPERM2X128:
4840   case X86ISD::SHUF128:
4841   case X86ISD::VPERMIL2:
4842   case X86ISD::VPERMI:
4843   case X86ISD::VPPERM:
4844   case X86ISD::VPERMV:
4845   case X86ISD::VPERMV3:
4846   case X86ISD::VZEXT_MOVL:
4847     return true;
4848   }
4849 }
4850 
4851 static bool isTargetShuffleVariableMask(unsigned Opcode) {
4852   switch (Opcode) {
4853   default: return false;
4854   // Target Shuffles.
4855   case X86ISD::PSHUFB:
4856   case X86ISD::VPERMILPV:
4857   case X86ISD::VPERMIL2:
4858   case X86ISD::VPPERM:
4859   case X86ISD::VPERMV:
4860   case X86ISD::VPERMV3:
4861     return true;
4862   // 'Faux' Target Shuffles.
4863   case ISD::OR:
4864   case ISD::AND:
4865   case X86ISD::ANDNP:
4866     return true;
4867   }
4868 }
4869 
4870 static bool isTargetShuffleSplat(SDValue Op) {
4871   unsigned Opcode = Op.getOpcode();
4872   if (Opcode == ISD::EXTRACT_SUBVECTOR)
4873     return isTargetShuffleSplat(Op.getOperand(0));
4874   return Opcode == X86ISD::VBROADCAST || Opcode == X86ISD::VBROADCAST_LOAD;
4875 }
4876 
4877 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4878   MachineFunction &MF = DAG.getMachineFunction();
4879   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4880   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4881   int ReturnAddrIndex = FuncInfo->getRAIndex();
4882 
4883   if (ReturnAddrIndex == 0) {
4884     // Set up a frame object for the return address.
4885     unsigned SlotSize = RegInfo->getSlotSize();
4886     ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4887                                                           -(int64_t)SlotSize,
4888                                                           false);
4889     FuncInfo->setRAIndex(ReturnAddrIndex);
4890   }
4891 
4892   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4893 }
4894 
4895 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4896                                        bool hasSymbolicDisplacement) {
4897   // Offset should fit into 32 bit immediate field.
4898   if (!isInt<32>(Offset))
4899     return false;
4900 
4901   // If we don't have a symbolic displacement - we don't have any extra
4902   // restrictions.
4903   if (!hasSymbolicDisplacement)
4904     return true;
4905 
4906   // FIXME: Some tweaks might be needed for medium code model.
4907   if (M != CodeModel::Small && M != CodeModel::Kernel)
4908     return false;
4909 
4910   // For small code model we assume that latest object is 16MB before end of 31
4911   // bits boundary. We may also accept pretty large negative constants knowing
4912   // that all objects are in the positive half of address space.
4913   if (M == CodeModel::Small && Offset < 16*1024*1024)
4914     return true;
4915 
4916   // For kernel code model we know that all object resist in the negative half
4917   // of 32bits address space. We may not accept negative offsets, since they may
4918   // be just off and we may accept pretty large positive ones.
4919   if (M == CodeModel::Kernel && Offset >= 0)
4920     return true;
4921 
4922   return false;
4923 }
4924 
4925 /// Determines whether the callee is required to pop its own arguments.
4926 /// Callee pop is necessary to support tail calls.
4927 bool X86::isCalleePop(CallingConv::ID CallingConv,
4928                       bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4929   // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4930   // can guarantee TCO.
4931   if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4932     return true;
4933 
4934   switch (CallingConv) {
4935   default:
4936     return false;
4937   case CallingConv::X86_StdCall:
4938   case CallingConv::X86_FastCall:
4939   case CallingConv::X86_ThisCall:
4940   case CallingConv::X86_VectorCall:
4941     return !is64Bit;
4942   }
4943 }
4944 
4945 /// Return true if the condition is an signed comparison operation.
4946 static bool isX86CCSigned(unsigned X86CC) {
4947   switch (X86CC) {
4948   default:
4949     llvm_unreachable("Invalid integer condition!");
4950   case X86::COND_E:
4951   case X86::COND_NE:
4952   case X86::COND_B:
4953   case X86::COND_A:
4954   case X86::COND_BE:
4955   case X86::COND_AE:
4956     return false;
4957   case X86::COND_G:
4958   case X86::COND_GE:
4959   case X86::COND_L:
4960   case X86::COND_LE:
4961     return true;
4962   }
4963 }
4964 
4965 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4966   switch (SetCCOpcode) {
4967   default: llvm_unreachable("Invalid integer condition!");
4968   case ISD::SETEQ:  return X86::COND_E;
4969   case ISD::SETGT:  return X86::COND_G;
4970   case ISD::SETGE:  return X86::COND_GE;
4971   case ISD::SETLT:  return X86::COND_L;
4972   case ISD::SETLE:  return X86::COND_LE;
4973   case ISD::SETNE:  return X86::COND_NE;
4974   case ISD::SETULT: return X86::COND_B;
4975   case ISD::SETUGT: return X86::COND_A;
4976   case ISD::SETULE: return X86::COND_BE;
4977   case ISD::SETUGE: return X86::COND_AE;
4978   }
4979 }
4980 
4981 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4982 /// condition code, returning the condition code and the LHS/RHS of the
4983 /// comparison to make.
4984 static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4985                                bool isFP, SDValue &LHS, SDValue &RHS,
4986                                SelectionDAG &DAG) {
4987   if (!isFP) {
4988     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4989       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4990         // X > -1   -> X == 0, jump !sign.
4991         RHS = DAG.getConstant(0, DL, RHS.getValueType());
4992         return X86::COND_NS;
4993       }
4994       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4995         // X < 0   -> X == 0, jump on sign.
4996         return X86::COND_S;
4997       }
4998       if (SetCCOpcode == ISD::SETGE && RHSC->isNullValue()) {
4999         // X >= 0   -> X == 0, jump on !sign.
5000         return X86::COND_NS;
5001       }
5002       if (SetCCOpcode == ISD::SETLT && RHSC->isOne()) {
5003         // X < 1   -> X <= 0
5004         RHS = DAG.getConstant(0, DL, RHS.getValueType());
5005         return X86::COND_LE;
5006       }
5007     }
5008 
5009     return TranslateIntegerX86CC(SetCCOpcode);
5010   }
5011 
5012   // First determine if it is required or is profitable to flip the operands.
5013 
5014   // If LHS is a foldable load, but RHS is not, flip the condition.
5015   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
5016       !ISD::isNON_EXTLoad(RHS.getNode())) {
5017     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
5018     std::swap(LHS, RHS);
5019   }
5020 
5021   switch (SetCCOpcode) {
5022   default: break;
5023   case ISD::SETOLT:
5024   case ISD::SETOLE:
5025   case ISD::SETUGT:
5026   case ISD::SETUGE:
5027     std::swap(LHS, RHS);
5028     break;
5029   }
5030 
5031   // On a floating point condition, the flags are set as follows:
5032   // ZF  PF  CF   op
5033   //  0 | 0 | 0 | X > Y
5034   //  0 | 0 | 1 | X < Y
5035   //  1 | 0 | 0 | X == Y
5036   //  1 | 1 | 1 | unordered
5037   switch (SetCCOpcode) {
5038   default: llvm_unreachable("Condcode should be pre-legalized away");
5039   case ISD::SETUEQ:
5040   case ISD::SETEQ:   return X86::COND_E;
5041   case ISD::SETOLT:              // flipped
5042   case ISD::SETOGT:
5043   case ISD::SETGT:   return X86::COND_A;
5044   case ISD::SETOLE:              // flipped
5045   case ISD::SETOGE:
5046   case ISD::SETGE:   return X86::COND_AE;
5047   case ISD::SETUGT:              // flipped
5048   case ISD::SETULT:
5049   case ISD::SETLT:   return X86::COND_B;
5050   case ISD::SETUGE:              // flipped
5051   case ISD::SETULE:
5052   case ISD::SETLE:   return X86::COND_BE;
5053   case ISD::SETONE:
5054   case ISD::SETNE:   return X86::COND_NE;
5055   case ISD::SETUO:   return X86::COND_P;
5056   case ISD::SETO:    return X86::COND_NP;
5057   case ISD::SETOEQ:
5058   case ISD::SETUNE:  return X86::COND_INVALID;
5059   }
5060 }
5061 
5062 /// Is there a floating point cmov for the specific X86 condition code?
5063 /// Current x86 isa includes the following FP cmov instructions:
5064 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
5065 static bool hasFPCMov(unsigned X86CC) {
5066   switch (X86CC) {
5067   default:
5068     return false;
5069   case X86::COND_B:
5070   case X86::COND_BE:
5071   case X86::COND_E:
5072   case X86::COND_P:
5073   case X86::COND_A:
5074   case X86::COND_AE:
5075   case X86::COND_NE:
5076   case X86::COND_NP:
5077     return true;
5078   }
5079 }
5080 
5081 
5082 bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5083                                            const CallInst &I,
5084                                            MachineFunction &MF,
5085                                            unsigned Intrinsic) const {
5086   Info.flags = MachineMemOperand::MONone;
5087   Info.offset = 0;
5088 
5089   const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
5090   if (!IntrData) {
5091     switch (Intrinsic) {
5092     case Intrinsic::x86_aesenc128kl:
5093     case Intrinsic::x86_aesdec128kl:
5094       Info.opc = ISD::INTRINSIC_W_CHAIN;
5095       Info.ptrVal = I.getArgOperand(1);
5096       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5097       Info.align = Align(1);
5098       Info.flags |= MachineMemOperand::MOLoad;
5099       return true;
5100     case Intrinsic::x86_aesenc256kl:
5101     case Intrinsic::x86_aesdec256kl:
5102       Info.opc = ISD::INTRINSIC_W_CHAIN;
5103       Info.ptrVal = I.getArgOperand(1);
5104       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5105       Info.align = Align(1);
5106       Info.flags |= MachineMemOperand::MOLoad;
5107       return true;
5108     case Intrinsic::x86_aesencwide128kl:
5109     case Intrinsic::x86_aesdecwide128kl:
5110       Info.opc = ISD::INTRINSIC_W_CHAIN;
5111       Info.ptrVal = I.getArgOperand(0);
5112       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 48);
5113       Info.align = Align(1);
5114       Info.flags |= MachineMemOperand::MOLoad;
5115       return true;
5116     case Intrinsic::x86_aesencwide256kl:
5117     case Intrinsic::x86_aesdecwide256kl:
5118       Info.opc = ISD::INTRINSIC_W_CHAIN;
5119       Info.ptrVal = I.getArgOperand(0);
5120       Info.memVT = EVT::getIntegerVT(I.getType()->getContext(), 64);
5121       Info.align = Align(1);
5122       Info.flags |= MachineMemOperand::MOLoad;
5123       return true;
5124     }
5125     return false;
5126   }
5127 
5128   switch (IntrData->Type) {
5129   case TRUNCATE_TO_MEM_VI8:
5130   case TRUNCATE_TO_MEM_VI16:
5131   case TRUNCATE_TO_MEM_VI32: {
5132     Info.opc = ISD::INTRINSIC_VOID;
5133     Info.ptrVal = I.getArgOperand(0);
5134     MVT VT  = MVT::getVT(I.getArgOperand(1)->getType());
5135     MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
5136     if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
5137       ScalarVT = MVT::i8;
5138     else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
5139       ScalarVT = MVT::i16;
5140     else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
5141       ScalarVT = MVT::i32;
5142 
5143     Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
5144     Info.align = Align(1);
5145     Info.flags |= MachineMemOperand::MOStore;
5146     break;
5147   }
5148   case GATHER:
5149   case GATHER_AVX2: {
5150     Info.opc = ISD::INTRINSIC_W_CHAIN;
5151     Info.ptrVal = nullptr;
5152     MVT DataVT = MVT::getVT(I.getType());
5153     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5154     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5155                                 IndexVT.getVectorNumElements());
5156     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5157     Info.align = Align(1);
5158     Info.flags |= MachineMemOperand::MOLoad;
5159     break;
5160   }
5161   case SCATTER: {
5162     Info.opc = ISD::INTRINSIC_VOID;
5163     Info.ptrVal = nullptr;
5164     MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
5165     MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
5166     unsigned NumElts = std::min(DataVT.getVectorNumElements(),
5167                                 IndexVT.getVectorNumElements());
5168     Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
5169     Info.align = Align(1);
5170     Info.flags |= MachineMemOperand::MOStore;
5171     break;
5172   }
5173   default:
5174     return false;
5175   }
5176 
5177   return true;
5178 }
5179 
5180 /// Returns true if the target can instruction select the
5181 /// specified FP immediate natively. If false, the legalizer will
5182 /// materialize the FP immediate as a load from a constant pool.
5183 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
5184                                      bool ForCodeSize) const {
5185   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
5186     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
5187       return true;
5188   }
5189   return false;
5190 }
5191 
5192 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
5193                                               ISD::LoadExtType ExtTy,
5194                                               EVT NewVT) const {
5195   assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow");
5196 
5197   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
5198   // relocation target a movq or addq instruction: don't let the load shrink.
5199   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
5200   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
5201     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
5202       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
5203 
5204   // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
5205   // those uses are extracted directly into a store, then the extract + store
5206   // can be store-folded. Therefore, it's probably not worth splitting the load.
5207   EVT VT = Load->getValueType(0);
5208   if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
5209     for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
5210       // Skip uses of the chain value. Result 0 of the node is the load value.
5211       if (UI.getUse().getResNo() != 0)
5212         continue;
5213 
5214       // If this use is not an extract + store, it's probably worth splitting.
5215       if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
5216           UI->use_begin()->getOpcode() != ISD::STORE)
5217         return true;
5218     }
5219     // All non-chain uses are extract + store.
5220     return false;
5221   }
5222 
5223   return true;
5224 }
5225 
5226 /// Returns true if it is beneficial to convert a load of a constant
5227 /// to just the constant itself.
5228 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5229                                                           Type *Ty) const {
5230   assert(Ty->isIntegerTy());
5231 
5232   unsigned BitSize = Ty->getPrimitiveSizeInBits();
5233   if (BitSize == 0 || BitSize > 64)
5234     return false;
5235   return true;
5236 }
5237 
5238 bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
5239   // If we are using XMM registers in the ABI and the condition of the select is
5240   // a floating-point compare and we have blendv or conditional move, then it is
5241   // cheaper to select instead of doing a cross-register move and creating a
5242   // load that depends on the compare result.
5243   bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
5244   return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
5245 }
5246 
5247 bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
5248   // TODO: It might be a win to ease or lift this restriction, but the generic
5249   // folds in DAGCombiner conflict with vector folds for an AVX512 target.
5250   if (VT.isVector() && Subtarget.hasAVX512())
5251     return false;
5252 
5253   return true;
5254 }
5255 
5256 bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
5257                                                SDValue C) const {
5258   // TODO: We handle scalars using custom code, but generic combining could make
5259   // that unnecessary.
5260   APInt MulC;
5261   if (!ISD::isConstantSplatVector(C.getNode(), MulC))
5262     return false;
5263 
5264   // Find the type this will be legalized too. Otherwise we might prematurely
5265   // convert this to shl+add/sub and then still have to type legalize those ops.
5266   // Another choice would be to defer the decision for illegal types until
5267   // after type legalization. But constant splat vectors of i64 can't make it
5268   // through type legalization on 32-bit targets so we would need to special
5269   // case vXi64.
5270   while (getTypeAction(Context, VT) != TypeLegal)
5271     VT = getTypeToTransformTo(Context, VT);
5272 
5273   // If vector multiply is legal, assume that's faster than shl + add/sub.
5274   // TODO: Multiply is a complex op with higher latency and lower throughput in
5275   //       most implementations, so this check could be loosened based on type
5276   //       and/or a CPU attribute.
5277   if (isOperationLegal(ISD::MUL, VT))
5278     return false;
5279 
5280   // shl+add, shl+sub, shl+add+neg
5281   return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
5282          (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
5283 }
5284 
5285 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
5286                                                 unsigned Index) const {
5287   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
5288     return false;
5289 
5290   // Mask vectors support all subregister combinations and operations that
5291   // extract half of vector.
5292   if (ResVT.getVectorElementType() == MVT::i1)
5293     return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
5294                           (Index == ResVT.getVectorNumElements()));
5295 
5296   return (Index % ResVT.getVectorNumElements()) == 0;
5297 }
5298 
5299 bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
5300   unsigned Opc = VecOp.getOpcode();
5301 
5302   // Assume target opcodes can't be scalarized.
5303   // TODO - do we have any exceptions?
5304   if (Opc >= ISD::BUILTIN_OP_END)
5305     return false;
5306 
5307   // If the vector op is not supported, try to convert to scalar.
5308   EVT VecVT = VecOp.getValueType();
5309   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
5310     return true;
5311 
5312   // If the vector op is supported, but the scalar op is not, the transform may
5313   // not be worthwhile.
5314   EVT ScalarVT = VecVT.getScalarType();
5315   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
5316 }
5317 
5318 bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT,
5319                                              bool) const {
5320   // TODO: Allow vectors?
5321   if (VT.isVector())
5322     return false;
5323   return VT.isSimple() || !isOperationExpand(Opcode, VT);
5324 }
5325 
5326 bool X86TargetLowering::isCheapToSpeculateCttz() const {
5327   // Speculate cttz only if we can directly use TZCNT.
5328   return Subtarget.hasBMI();
5329 }
5330 
5331 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5332   // Speculate ctlz only if we can directly use LZCNT.
5333   return Subtarget.hasLZCNT();
5334 }
5335 
5336 bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5337                                                 const SelectionDAG &DAG,
5338                                                 const MachineMemOperand &MMO) const {
5339   if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5340       BitcastVT.getVectorElementType() == MVT::i1)
5341     return false;
5342 
5343   if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5344     return false;
5345 
5346   // If both types are legal vectors, it's always ok to convert them.
5347   if (LoadVT.isVector() && BitcastVT.isVector() &&
5348       isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5349     return true;
5350 
5351   return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5352 }
5353 
5354 bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5355                                          const SelectionDAG &DAG) const {
5356   // Do not merge to float value size (128 bytes) if no implicit
5357   // float attribute is set.
5358   bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
5359       Attribute::NoImplicitFloat);
5360 
5361   if (NoFloat) {
5362     unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5363     return (MemVT.getSizeInBits() <= MaxIntSize);
5364   }
5365   // Make sure we don't merge greater than our preferred vector
5366   // width.
5367   if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5368     return false;
5369 
5370   return true;
5371 }
5372 
5373 bool X86TargetLowering::isCtlzFast() const {
5374   return Subtarget.hasFastLZCNT();
5375 }
5376 
5377 bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5378     const Instruction &AndI) const {
5379   return true;
5380 }
5381 
5382 bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5383   EVT VT = Y.getValueType();
5384 
5385   if (VT.isVector())
5386     return false;
5387 
5388   if (!Subtarget.hasBMI())
5389     return false;
5390 
5391   // There are only 32-bit and 64-bit forms for 'andn'.
5392   if (VT != MVT::i32 && VT != MVT::i64)
5393     return false;
5394 
5395   return !isa<ConstantSDNode>(Y);
5396 }
5397 
5398 bool X86TargetLowering::hasAndNot(SDValue Y) const {
5399   EVT VT = Y.getValueType();
5400 
5401   if (!VT.isVector())
5402     return hasAndNotCompare(Y);
5403 
5404   // Vector.
5405 
5406   if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5407     return false;
5408 
5409   if (VT == MVT::v4i32)
5410     return true;
5411 
5412   return Subtarget.hasSSE2();
5413 }
5414 
5415 bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5416   return X.getValueType().isScalarInteger(); // 'bt'
5417 }
5418 
5419 bool X86TargetLowering::
5420     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5421         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5422         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5423         SelectionDAG &DAG) const {
5424   // Does baseline recommend not to perform the fold by default?
5425   if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5426           X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5427     return false;
5428   // For scalars this transform is always beneficial.
5429   if (X.getValueType().isScalarInteger())
5430     return true;
5431   // If all the shift amounts are identical, then transform is beneficial even
5432   // with rudimentary SSE2 shifts.
5433   if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5434     return true;
5435   // If we have AVX2 with it's powerful shift operations, then it's also good.
5436   if (Subtarget.hasAVX2())
5437     return true;
5438   // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5439   return NewShiftOpcode == ISD::SHL;
5440 }
5441 
5442 bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5443     const SDNode *N, CombineLevel Level) const {
5444   assert(((N->getOpcode() == ISD::SHL &&
5445            N->getOperand(0).getOpcode() == ISD::SRL) ||
5446           (N->getOpcode() == ISD::SRL &&
5447            N->getOperand(0).getOpcode() == ISD::SHL)) &&
5448          "Expected shift-shift mask");
5449   EVT VT = N->getValueType(0);
5450   if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5451       (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5452     // Only fold if the shift values are equal - so it folds to AND.
5453     // TODO - we should fold if either is a non-uniform vector but we don't do
5454     // the fold for non-splats yet.
5455     return N->getOperand(1) == N->getOperand(0).getOperand(1);
5456   }
5457   return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5458 }
5459 
5460 bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5461   EVT VT = Y.getValueType();
5462 
5463   // For vectors, we don't have a preference, but we probably want a mask.
5464   if (VT.isVector())
5465     return false;
5466 
5467   // 64-bit shifts on 32-bit targets produce really bad bloated code.
5468   if (VT == MVT::i64 && !Subtarget.is64Bit())
5469     return false;
5470 
5471   return true;
5472 }
5473 
5474 bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5475                                           SDNode *N) const {
5476   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5477       !Subtarget.isOSWindows())
5478     return false;
5479   return true;
5480 }
5481 
5482 bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5483   // Any legal vector type can be splatted more efficiently than
5484   // loading/spilling from memory.
5485   return isTypeLegal(VT);
5486 }
5487 
5488 MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5489   MVT VT = MVT::getIntegerVT(NumBits);
5490   if (isTypeLegal(VT))
5491     return VT;
5492 
5493   // PMOVMSKB can handle this.
5494   if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5495     return MVT::v16i8;
5496 
5497   // VPMOVMSKB can handle this.
5498   if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5499     return MVT::v32i8;
5500 
5501   // TODO: Allow 64-bit type for 32-bit target.
5502   // TODO: 512-bit types should be allowed, but make sure that those
5503   // cases are handled in combineVectorSizedSetCCEquality().
5504 
5505   return MVT::INVALID_SIMPLE_VALUE_TYPE;
5506 }
5507 
5508 /// Val is the undef sentinel value or equal to the specified value.
5509 static bool isUndefOrEqual(int Val, int CmpVal) {
5510   return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5511 }
5512 
5513 /// Return true if every element in Mask is the undef sentinel value or equal to
5514 /// the specified value..
5515 static bool isUndefOrEqual(ArrayRef<int> Mask, int CmpVal) {
5516   return llvm::all_of(Mask, [CmpVal](int M) {
5517     return (M == SM_SentinelUndef) || (M == CmpVal);
5518   });
5519 }
5520 
5521 /// Val is either the undef or zero sentinel value.
5522 static bool isUndefOrZero(int Val) {
5523   return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5524 }
5525 
5526 /// Return true if every element in Mask, beginning from position Pos and ending
5527 /// in Pos+Size is the undef sentinel value.
5528 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5529   return llvm::all_of(Mask.slice(Pos, Size),
5530                       [](int M) { return M == SM_SentinelUndef; });
5531 }
5532 
5533 /// Return true if the mask creates a vector whose lower half is undefined.
5534 static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5535   unsigned NumElts = Mask.size();
5536   return isUndefInRange(Mask, 0, NumElts / 2);
5537 }
5538 
5539 /// Return true if the mask creates a vector whose upper half is undefined.
5540 static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5541   unsigned NumElts = Mask.size();
5542   return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5543 }
5544 
5545 /// Return true if Val falls within the specified range (L, H].
5546 static bool isInRange(int Val, int Low, int Hi) {
5547   return (Val >= Low && Val < Hi);
5548 }
5549 
5550 /// Return true if the value of any element in Mask falls within the specified
5551 /// range (L, H].
5552 static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5553   return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
5554 }
5555 
5556 /// Return true if the value of any element in Mask is the zero sentinel value.
5557 static bool isAnyZero(ArrayRef<int> Mask) {
5558   return llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
5559 }
5560 
5561 /// Return true if the value of any element in Mask is the zero or undef
5562 /// sentinel values.
5563 static bool isAnyZeroOrUndef(ArrayRef<int> Mask) {
5564   return llvm::any_of(Mask, [](int M) {
5565     return M == SM_SentinelZero || M == SM_SentinelUndef;
5566   });
5567 }
5568 
5569 /// Return true if Val is undef or if its value falls within the
5570 /// specified range (L, H].
5571 static bool isUndefOrInRange(int Val, int Low, int Hi) {
5572   return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5573 }
5574 
5575 /// Return true if every element in Mask is undef or if its value
5576 /// falls within the specified range (L, H].
5577 static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5578   return llvm::all_of(
5579       Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
5580 }
5581 
5582 /// Return true if Val is undef, zero or if its value falls within the
5583 /// specified range (L, H].
5584 static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5585   return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5586 }
5587 
5588 /// Return true if every element in Mask is undef, zero or if its value
5589 /// falls within the specified range (L, H].
5590 static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5591   return llvm::all_of(
5592       Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
5593 }
5594 
5595 /// Return true if every element in Mask, beginning
5596 /// from position Pos and ending in Pos + Size, falls within the specified
5597 /// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
5598 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5599                                        unsigned Size, int Low, int Step = 1) {
5600   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5601     if (!isUndefOrEqual(Mask[i], Low))
5602       return false;
5603   return true;
5604 }
5605 
5606 /// Return true if every element in Mask, beginning
5607 /// from position Pos and ending in Pos+Size, falls within the specified
5608 /// sequential range (Low, Low+Size], or is undef or is zero.
5609 static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5610                                              unsigned Size, int Low,
5611                                              int Step = 1) {
5612   for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5613     if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5614       return false;
5615   return true;
5616 }
5617 
5618 /// Return true if every element in Mask, beginning
5619 /// from position Pos and ending in Pos+Size is undef or is zero.
5620 static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5621                                  unsigned Size) {
5622   return llvm::all_of(Mask.slice(Pos, Size),
5623                       [](int M) { return isUndefOrZero(M); });
5624 }
5625 
5626 /// Helper function to test whether a shuffle mask could be
5627 /// simplified by widening the elements being shuffled.
5628 ///
5629 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5630 /// leaves it in an unspecified state.
5631 ///
5632 /// NOTE: This must handle normal vector shuffle masks and *target* vector
5633 /// shuffle masks. The latter have the special property of a '-2' representing
5634 /// a zero-ed lane of a vector.
5635 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5636                                     SmallVectorImpl<int> &WidenedMask) {
5637   WidenedMask.assign(Mask.size() / 2, 0);
5638   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5639     int M0 = Mask[i];
5640     int M1 = Mask[i + 1];
5641 
5642     // If both elements are undef, its trivial.
5643     if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5644       WidenedMask[i / 2] = SM_SentinelUndef;
5645       continue;
5646     }
5647 
5648     // Check for an undef mask and a mask value properly aligned to fit with
5649     // a pair of values. If we find such a case, use the non-undef mask's value.
5650     if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5651       WidenedMask[i / 2] = M1 / 2;
5652       continue;
5653     }
5654     if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5655       WidenedMask[i / 2] = M0 / 2;
5656       continue;
5657     }
5658 
5659     // When zeroing, we need to spread the zeroing across both lanes to widen.
5660     if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5661       if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5662           (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5663         WidenedMask[i / 2] = SM_SentinelZero;
5664         continue;
5665       }
5666       return false;
5667     }
5668 
5669     // Finally check if the two mask values are adjacent and aligned with
5670     // a pair.
5671     if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5672       WidenedMask[i / 2] = M0 / 2;
5673       continue;
5674     }
5675 
5676     // Otherwise we can't safely widen the elements used in this shuffle.
5677     return false;
5678   }
5679   assert(WidenedMask.size() == Mask.size() / 2 &&
5680          "Incorrect size of mask after widening the elements!");
5681 
5682   return true;
5683 }
5684 
5685 static bool canWidenShuffleElements(ArrayRef<int> Mask,
5686                                     const APInt &Zeroable,
5687                                     bool V2IsZero,
5688                                     SmallVectorImpl<int> &WidenedMask) {
5689   // Create an alternative mask with info about zeroable elements.
5690   // Here we do not set undef elements as zeroable.
5691   SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
5692   if (V2IsZero) {
5693     assert(!Zeroable.isNullValue() && "V2's non-undef elements are used?!");
5694     for (int i = 0, Size = Mask.size(); i != Size; ++i)
5695       if (Mask[i] != SM_SentinelUndef && Zeroable[i])
5696         ZeroableMask[i] = SM_SentinelZero;
5697   }
5698   return canWidenShuffleElements(ZeroableMask, WidenedMask);
5699 }
5700 
5701 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5702   SmallVector<int, 32> WidenedMask;
5703   return canWidenShuffleElements(Mask, WidenedMask);
5704 }
5705 
5706 // Attempt to narrow/widen shuffle mask until it matches the target number of
5707 // elements.
5708 static bool scaleShuffleElements(ArrayRef<int> Mask, unsigned NumDstElts,
5709                                  SmallVectorImpl<int> &ScaledMask) {
5710   unsigned NumSrcElts = Mask.size();
5711   assert(((NumSrcElts % NumDstElts) == 0 || (NumDstElts % NumSrcElts) == 0) &&
5712          "Illegal shuffle scale factor");
5713 
5714   // Narrowing is guaranteed to work.
5715   if (NumDstElts >= NumSrcElts) {
5716     int Scale = NumDstElts / NumSrcElts;
5717     llvm::narrowShuffleMaskElts(Scale, Mask, ScaledMask);
5718     return true;
5719   }
5720 
5721   // We have to repeat the widening until we reach the target size, but we can
5722   // split out the first widening as it sets up ScaledMask for us.
5723   if (canWidenShuffleElements(Mask, ScaledMask)) {
5724     while (ScaledMask.size() > NumDstElts) {
5725       SmallVector<int, 16> WidenedMask;
5726       if (!canWidenShuffleElements(ScaledMask, WidenedMask))
5727         return false;
5728       ScaledMask = std::move(WidenedMask);
5729     }
5730     return true;
5731   }
5732 
5733   return false;
5734 }
5735 
5736 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
5737 bool X86::isZeroNode(SDValue Elt) {
5738   return isNullConstant(Elt) || isNullFPConstant(Elt);
5739 }
5740 
5741 // Build a vector of constants.
5742 // Use an UNDEF node if MaskElt == -1.
5743 // Split 64-bit constants in the 32-bit mode.
5744 static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5745                               const SDLoc &dl, bool IsMask = false) {
5746 
5747   SmallVector<SDValue, 32>  Ops;
5748   bool Split = false;
5749 
5750   MVT ConstVecVT = VT;
5751   unsigned NumElts = VT.getVectorNumElements();
5752   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5753   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5754     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5755     Split = true;
5756   }
5757 
5758   MVT EltVT = ConstVecVT.getVectorElementType();
5759   for (unsigned i = 0; i < NumElts; ++i) {
5760     bool IsUndef = Values[i] < 0 && IsMask;
5761     SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5762       DAG.getConstant(Values[i], dl, EltVT);
5763     Ops.push_back(OpNode);
5764     if (Split)
5765       Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5766                     DAG.getConstant(0, dl, EltVT));
5767   }
5768   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5769   if (Split)
5770     ConstsNode = DAG.getBitcast(VT, ConstsNode);
5771   return ConstsNode;
5772 }
5773 
5774 static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5775                               MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5776   assert(Bits.size() == Undefs.getBitWidth() &&
5777          "Unequal constant and undef arrays");
5778   SmallVector<SDValue, 32> Ops;
5779   bool Split = false;
5780 
5781   MVT ConstVecVT = VT;
5782   unsigned NumElts = VT.getVectorNumElements();
5783   bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5784   if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5785     ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5786     Split = true;
5787   }
5788 
5789   MVT EltVT = ConstVecVT.getVectorElementType();
5790   for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5791     if (Undefs[i]) {
5792       Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5793       continue;
5794     }
5795     const APInt &V = Bits[i];
5796     assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes");
5797     if (Split) {
5798       Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5799       Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5800     } else if (EltVT == MVT::f32) {
5801       APFloat FV(APFloat::IEEEsingle(), V);
5802       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5803     } else if (EltVT == MVT::f64) {
5804       APFloat FV(APFloat::IEEEdouble(), V);
5805       Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5806     } else {
5807       Ops.push_back(DAG.getConstant(V, dl, EltVT));
5808     }
5809   }
5810 
5811   SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5812   return DAG.getBitcast(VT, ConstsNode);
5813 }
5814 
5815 /// Returns a vector of specified type with all zero elements.
5816 static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5817                              SelectionDAG &DAG, const SDLoc &dl) {
5818   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||
5819           VT.getVectorElementType() == MVT::i1) &&
5820          "Unexpected vector type");
5821 
5822   // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5823   // type. This ensures they get CSE'd. But if the integer type is not
5824   // available, use a floating-point +0.0 instead.
5825   SDValue Vec;
5826   if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5827     Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5828   } else if (VT.isFloatingPoint()) {
5829     Vec = DAG.getConstantFP(+0.0, dl, VT);
5830   } else if (VT.getVectorElementType() == MVT::i1) {
5831     assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
5832            "Unexpected vector type");
5833     Vec = DAG.getConstant(0, dl, VT);
5834   } else {
5835     unsigned Num32BitElts = VT.getSizeInBits() / 32;
5836     Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5837   }
5838   return DAG.getBitcast(VT, Vec);
5839 }
5840 
5841 static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5842                                 const SDLoc &dl, unsigned vectorWidth) {
5843   EVT VT = Vec.getValueType();
5844   EVT ElVT = VT.getVectorElementType();
5845   unsigned Factor = VT.getSizeInBits()/vectorWidth;
5846   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5847                                   VT.getVectorNumElements()/Factor);
5848 
5849   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
5850   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5851   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5852 
5853   // This is the index of the first element of the vectorWidth-bit chunk
5854   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5855   IdxVal &= ~(ElemsPerChunk - 1);
5856 
5857   // If the input is a buildvector just emit a smaller one.
5858   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5859     return DAG.getBuildVector(ResultVT, dl,
5860                               Vec->ops().slice(IdxVal, ElemsPerChunk));
5861 
5862   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5863   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5864 }
5865 
5866 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
5867 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5868 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5869 /// instructions or a simple subregister reference. Idx is an index in the
5870 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
5871 /// lowering EXTRACT_VECTOR_ELT operations easier.
5872 static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5873                                    SelectionDAG &DAG, const SDLoc &dl) {
5874   assert((Vec.getValueType().is256BitVector() ||
5875           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
5876   return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5877 }
5878 
5879 /// Generate a DAG to grab 256-bits from a 512-bit vector.
5880 static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5881                                    SelectionDAG &DAG, const SDLoc &dl) {
5882   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
5883   return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5884 }
5885 
5886 static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5887                                SelectionDAG &DAG, const SDLoc &dl,
5888                                unsigned vectorWidth) {
5889   assert((vectorWidth == 128 || vectorWidth == 256) &&
5890          "Unsupported vector width");
5891   // Inserting UNDEF is Result
5892   if (Vec.isUndef())
5893     return Result;
5894   EVT VT = Vec.getValueType();
5895   EVT ElVT = VT.getVectorElementType();
5896   EVT ResultVT = Result.getValueType();
5897 
5898   // Insert the relevant vectorWidth bits.
5899   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5900   assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
5901 
5902   // This is the index of the first element of the vectorWidth-bit chunk
5903   // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5904   IdxVal &= ~(ElemsPerChunk - 1);
5905 
5906   SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5907   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5908 }
5909 
5910 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
5911 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5912 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5913 /// simple superregister reference.  Idx is an index in the 128 bits
5914 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
5915 /// lowering INSERT_VECTOR_ELT operations easier.
5916 static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5917                                   SelectionDAG &DAG, const SDLoc &dl) {
5918   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
5919   return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5920 }
5921 
5922 /// Widen a vector to a larger size with the same scalar type, with the new
5923 /// elements either zero or undef.
5924 static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5925                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5926                               const SDLoc &dl) {
5927   assert(Vec.getValueSizeInBits().getFixedSize() < VT.getFixedSizeInBits() &&
5928          Vec.getValueType().getScalarType() == VT.getScalarType() &&
5929          "Unsupported vector widening type");
5930   SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5931                                 : DAG.getUNDEF(VT);
5932   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5933                      DAG.getIntPtrConstant(0, dl));
5934 }
5935 
5936 /// Widen a vector to a larger size with the same scalar type, with the new
5937 /// elements either zero or undef.
5938 static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
5939                               const X86Subtarget &Subtarget, SelectionDAG &DAG,
5940                               const SDLoc &dl, unsigned WideSizeInBits) {
5941   assert(Vec.getValueSizeInBits() < WideSizeInBits &&
5942          (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&
5943          "Unsupported vector widening type");
5944   unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
5945   MVT SVT = Vec.getSimpleValueType().getScalarType();
5946   MVT VT = MVT::getVectorVT(SVT, WideNumElts);
5947   return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
5948 }
5949 
5950 // Helper function to collect subvector ops that are concatenated together,
5951 // either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
5952 // The subvectors in Ops are guaranteed to be the same type.
5953 static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
5954   assert(Ops.empty() && "Expected an empty ops vector");
5955 
5956   if (N->getOpcode() == ISD::CONCAT_VECTORS) {
5957     Ops.append(N->op_begin(), N->op_end());
5958     return true;
5959   }
5960 
5961   if (N->getOpcode() == ISD::INSERT_SUBVECTOR) {
5962     SDValue Src = N->getOperand(0);
5963     SDValue Sub = N->getOperand(1);
5964     const APInt &Idx = N->getConstantOperandAPInt(2);
5965     EVT VT = Src.getValueType();
5966     EVT SubVT = Sub.getValueType();
5967 
5968     // TODO - Handle more general insert_subvector chains.
5969     if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
5970         Idx == (VT.getVectorNumElements() / 2)) {
5971       // insert_subvector(insert_subvector(undef, x, lo), y, hi)
5972       if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
5973           Src.getOperand(1).getValueType() == SubVT &&
5974           isNullConstant(Src.getOperand(2))) {
5975         Ops.push_back(Src.getOperand(1));
5976         Ops.push_back(Sub);
5977         return true;
5978       }
5979       // insert_subvector(x, extract_subvector(x, lo), hi)
5980       if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5981           Sub.getOperand(0) == Src && isNullConstant(Sub.getOperand(1))) {
5982         Ops.append(2, Sub);
5983         return true;
5984       }
5985     }
5986   }
5987 
5988   return false;
5989 }
5990 
5991 static std::pair<SDValue, SDValue> splitVector(SDValue Op, SelectionDAG &DAG,
5992                                                const SDLoc &dl) {
5993   EVT VT = Op.getValueType();
5994   unsigned NumElems = VT.getVectorNumElements();
5995   unsigned SizeInBits = VT.getSizeInBits();
5996   assert((NumElems % 2) == 0 && (SizeInBits % 2) == 0 &&
5997          "Can't split odd sized vector");
5998 
5999   SDValue Lo = extractSubVector(Op, 0, DAG, dl, SizeInBits / 2);
6000   SDValue Hi = extractSubVector(Op, NumElems / 2, DAG, dl, SizeInBits / 2);
6001   return std::make_pair(Lo, Hi);
6002 }
6003 
6004 // Split an unary integer op into 2 half sized ops.
6005 static SDValue splitVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
6006   EVT VT = Op.getValueType();
6007 
6008   // Make sure we only try to split 256/512-bit types to avoid creating
6009   // narrow vectors.
6010   assert((Op.getOperand(0).getValueType().is256BitVector() ||
6011           Op.getOperand(0).getValueType().is512BitVector()) &&
6012          (VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6013   assert(Op.getOperand(0).getValueType().getVectorNumElements() ==
6014              VT.getVectorNumElements() &&
6015          "Unexpected VTs!");
6016 
6017   SDLoc dl(Op);
6018 
6019   // Extract the Lo/Hi vectors
6020   SDValue Lo, Hi;
6021   std::tie(Lo, Hi) = splitVector(Op.getOperand(0), DAG, dl);
6022 
6023   EVT LoVT, HiVT;
6024   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6025   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6026                      DAG.getNode(Op.getOpcode(), dl, LoVT, Lo),
6027                      DAG.getNode(Op.getOpcode(), dl, HiVT, Hi));
6028 }
6029 
6030 /// Break a binary integer operation into 2 half sized ops and then
6031 /// concatenate the result back.
6032 static SDValue splitVectorIntBinary(SDValue Op, SelectionDAG &DAG) {
6033   EVT VT = Op.getValueType();
6034 
6035   // Sanity check that all the types match.
6036   assert(Op.getOperand(0).getValueType() == VT &&
6037          Op.getOperand(1).getValueType() == VT && "Unexpected VTs!");
6038   assert((VT.is256BitVector() || VT.is512BitVector()) && "Unsupported VT!");
6039 
6040   SDLoc dl(Op);
6041 
6042   // Extract the LHS Lo/Hi vectors
6043   SDValue LHS1, LHS2;
6044   std::tie(LHS1, LHS2) = splitVector(Op.getOperand(0), DAG, dl);
6045 
6046   // Extract the RHS Lo/Hi vectors
6047   SDValue RHS1, RHS2;
6048   std::tie(RHS1, RHS2) = splitVector(Op.getOperand(1), DAG, dl);
6049 
6050   EVT LoVT, HiVT;
6051   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
6052   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
6053                      DAG.getNode(Op.getOpcode(), dl, LoVT, LHS1, RHS1),
6054                      DAG.getNode(Op.getOpcode(), dl, HiVT, LHS2, RHS2));
6055 }
6056 
6057 // Helper for splitting operands of an operation to legal target size and
6058 // apply a function on each part.
6059 // Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
6060 // 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
6061 // deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
6062 // The argument Builder is a function that will be applied on each split part:
6063 // SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
6064 template <typename F>
6065 SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
6066                          const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
6067                          F Builder, bool CheckBWI = true) {
6068   assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2");
6069   unsigned NumSubs = 1;
6070   if ((CheckBWI && Subtarget.useBWIRegs()) ||
6071       (!CheckBWI && Subtarget.useAVX512Regs())) {
6072     if (VT.getSizeInBits() > 512) {
6073       NumSubs = VT.getSizeInBits() / 512;
6074       assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size");
6075     }
6076   } else if (Subtarget.hasAVX2()) {
6077     if (VT.getSizeInBits() > 256) {
6078       NumSubs = VT.getSizeInBits() / 256;
6079       assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size");
6080     }
6081   } else {
6082     if (VT.getSizeInBits() > 128) {
6083       NumSubs = VT.getSizeInBits() / 128;
6084       assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size");
6085     }
6086   }
6087 
6088   if (NumSubs == 1)
6089     return Builder(DAG, DL, Ops);
6090 
6091   SmallVector<SDValue, 4> Subs;
6092   for (unsigned i = 0; i != NumSubs; ++i) {
6093     SmallVector<SDValue, 2> SubOps;
6094     for (SDValue Op : Ops) {
6095       EVT OpVT = Op.getValueType();
6096       unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
6097       unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
6098       SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
6099     }
6100     Subs.push_back(Builder(DAG, DL, SubOps));
6101   }
6102   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
6103 }
6104 
6105 /// Insert i1-subvector to i1-vector.
6106 static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
6107                                 const X86Subtarget &Subtarget) {
6108 
6109   SDLoc dl(Op);
6110   SDValue Vec = Op.getOperand(0);
6111   SDValue SubVec = Op.getOperand(1);
6112   SDValue Idx = Op.getOperand(2);
6113   unsigned IdxVal = Op.getConstantOperandVal(2);
6114 
6115   // Inserting undef is a nop. We can just return the original vector.
6116   if (SubVec.isUndef())
6117     return Vec;
6118 
6119   if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
6120     return Op;
6121 
6122   MVT OpVT = Op.getSimpleValueType();
6123   unsigned NumElems = OpVT.getVectorNumElements();
6124   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6125 
6126   // Extend to natively supported kshift.
6127   MVT WideOpVT = OpVT;
6128   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
6129     WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
6130 
6131   // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
6132   // if necessary.
6133   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
6134     // May need to promote to a legal type.
6135     Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6136                      DAG.getConstant(0, dl, WideOpVT),
6137                      SubVec, Idx);
6138     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6139   }
6140 
6141   MVT SubVecVT = SubVec.getSimpleValueType();
6142   unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
6143   assert(IdxVal + SubVecNumElems <= NumElems &&
6144          IdxVal % SubVecVT.getSizeInBits() == 0 &&
6145          "Unexpected index value in INSERT_SUBVECTOR");
6146 
6147   SDValue Undef = DAG.getUNDEF(WideOpVT);
6148 
6149   if (IdxVal == 0) {
6150     // Zero lower bits of the Vec
6151     SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
6152     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
6153                       ZeroIdx);
6154     Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6155     Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6156     // Merge them together, SubVec should be zero extended.
6157     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6158                          DAG.getConstant(0, dl, WideOpVT),
6159                          SubVec, ZeroIdx);
6160     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6161     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6162   }
6163 
6164   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6165                        Undef, SubVec, ZeroIdx);
6166 
6167   if (Vec.isUndef()) {
6168     assert(IdxVal != 0 && "Unexpected index");
6169     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6170                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6171     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6172   }
6173 
6174   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
6175     assert(IdxVal != 0 && "Unexpected index");
6176     NumElems = WideOpVT.getVectorNumElements();
6177     unsigned ShiftLeft = NumElems - SubVecNumElems;
6178     unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6179     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6180                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6181     if (ShiftRight != 0)
6182       SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6183                            DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6184     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6185   }
6186 
6187   // Simple case when we put subvector in the upper part
6188   if (IdxVal + SubVecNumElems == NumElems) {
6189     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6190                          DAG.getTargetConstant(IdxVal, dl, MVT::i8));
6191     if (SubVecNumElems * 2 == NumElems) {
6192       // Special case, use legal zero extending insert_subvector. This allows
6193       // isel to optimize when bits are known zero.
6194       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
6195       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6196                         DAG.getConstant(0, dl, WideOpVT),
6197                         Vec, ZeroIdx);
6198     } else {
6199       // Otherwise use explicit shifts to zero the bits.
6200       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
6201                         Undef, Vec, ZeroIdx);
6202       NumElems = WideOpVT.getVectorNumElements();
6203       SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
6204       Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
6205       Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
6206     }
6207     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6208     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6209   }
6210 
6211   // Inserting into the middle is more complicated.
6212 
6213   NumElems = WideOpVT.getVectorNumElements();
6214 
6215   // Widen the vector if needed.
6216   Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
6217 
6218   unsigned ShiftLeft = NumElems - SubVecNumElems;
6219   unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
6220 
6221   // Do an optimization for the the most frequently used types.
6222   if (WideOpVT != MVT::v64i1 || Subtarget.is64Bit()) {
6223     APInt Mask0 = APInt::getBitsSet(NumElems, IdxVal, IdxVal + SubVecNumElems);
6224     Mask0.flipAllBits();
6225     SDValue CMask0 = DAG.getConstant(Mask0, dl, MVT::getIntegerVT(NumElems));
6226     SDValue VMask0 = DAG.getNode(ISD::BITCAST, dl, WideOpVT, CMask0);
6227     Vec = DAG.getNode(ISD::AND, dl, WideOpVT, Vec, VMask0);
6228     SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6229                          DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6230     SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6231                          DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6232     Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
6233 
6234     // Reduce to original width if needed.
6235     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
6236   }
6237 
6238   // Clear the upper bits of the subvector and move it to its insert position.
6239   SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
6240                        DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
6241   SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
6242                        DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
6243 
6244   // Isolate the bits below the insertion point.
6245   unsigned LowShift = NumElems - IdxVal;
6246   SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
6247                             DAG.getTargetConstant(LowShift, dl, MVT::i8));
6248   Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
6249                     DAG.getTargetConstant(LowShift, dl, MVT::i8));
6250 
6251   // Isolate the bits after the last inserted bit.
6252   unsigned HighShift = IdxVal + SubVecNumElems;
6253   SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
6254                             DAG.getTargetConstant(HighShift, dl, MVT::i8));
6255   High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
6256                     DAG.getTargetConstant(HighShift, dl, MVT::i8));
6257 
6258   // Now OR all 3 pieces together.
6259   Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
6260   SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
6261 
6262   // Reduce to original width if needed.
6263   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
6264 }
6265 
6266 static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
6267                                 const SDLoc &dl) {
6268   assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch");
6269   EVT SubVT = V1.getValueType();
6270   EVT SubSVT = SubVT.getScalarType();
6271   unsigned SubNumElts = SubVT.getVectorNumElements();
6272   unsigned SubVectorWidth = SubVT.getSizeInBits();
6273   EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
6274   SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
6275   return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
6276 }
6277 
6278 /// Returns a vector of specified type with all bits set.
6279 /// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
6280 /// Then bitcast to their original type, ensuring they get CSE'd.
6281 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6282   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6283          "Expected a 128/256/512-bit vector type");
6284 
6285   APInt Ones = APInt::getAllOnesValue(32);
6286   unsigned NumElts = VT.getSizeInBits() / 32;
6287   SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
6288   return DAG.getBitcast(VT, Vec);
6289 }
6290 
6291 // Convert *_EXTEND_VECTOR_INREG to *_EXTEND opcode.
6292 static unsigned getOpcode_EXTEND(unsigned Opcode) {
6293   switch (Opcode) {
6294   case ISD::ANY_EXTEND:
6295   case ISD::ANY_EXTEND_VECTOR_INREG:
6296     return ISD::ANY_EXTEND;
6297   case ISD::ZERO_EXTEND:
6298   case ISD::ZERO_EXTEND_VECTOR_INREG:
6299     return ISD::ZERO_EXTEND;
6300   case ISD::SIGN_EXTEND:
6301   case ISD::SIGN_EXTEND_VECTOR_INREG:
6302     return ISD::SIGN_EXTEND;
6303   }
6304   llvm_unreachable("Unknown opcode");
6305 }
6306 
6307 // Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
6308 static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
6309   switch (Opcode) {
6310   case ISD::ANY_EXTEND:
6311   case ISD::ANY_EXTEND_VECTOR_INREG:
6312     return ISD::ANY_EXTEND_VECTOR_INREG;
6313   case ISD::ZERO_EXTEND:
6314   case ISD::ZERO_EXTEND_VECTOR_INREG:
6315     return ISD::ZERO_EXTEND_VECTOR_INREG;
6316   case ISD::SIGN_EXTEND:
6317   case ISD::SIGN_EXTEND_VECTOR_INREG:
6318     return ISD::SIGN_EXTEND_VECTOR_INREG;
6319   }
6320   llvm_unreachable("Unknown opcode");
6321 }
6322 
6323 static SDValue getEXTEND_VECTOR_INREG(unsigned Opcode, const SDLoc &DL, EVT VT,
6324                                       SDValue In, SelectionDAG &DAG) {
6325   EVT InVT = In.getValueType();
6326   assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.");
6327   assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
6328           ISD::ZERO_EXTEND == Opcode) &&
6329          "Unknown extension opcode");
6330 
6331   // For 256-bit vectors, we only need the lower (128-bit) input half.
6332   // For 512-bit vectors, we only need the lower input half or quarter.
6333   if (InVT.getSizeInBits() > 128) {
6334     assert(VT.getSizeInBits() == InVT.getSizeInBits() &&
6335            "Expected VTs to be the same size!");
6336     unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
6337     In = extractSubVector(In, 0, DAG, DL,
6338                           std::max(128U, (unsigned)VT.getSizeInBits() / Scale));
6339     InVT = In.getValueType();
6340   }
6341 
6342   if (VT.getVectorNumElements() != InVT.getVectorNumElements())
6343     Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
6344 
6345   return DAG.getNode(Opcode, DL, VT, In);
6346 }
6347 
6348 // Match (xor X, -1) -> X.
6349 // Match extract_subvector(xor X, -1) -> extract_subvector(X).
6350 // Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
6351 static SDValue IsNOT(SDValue V, SelectionDAG &DAG, bool OneUse = false) {
6352   V = OneUse ? peekThroughOneUseBitcasts(V) : peekThroughBitcasts(V);
6353   if (V.getOpcode() == ISD::XOR &&
6354       ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
6355     return V.getOperand(0);
6356   if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6357       (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
6358     if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
6359       Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
6360       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
6361                          Not, V.getOperand(1));
6362     }
6363   }
6364   SmallVector<SDValue, 2> CatOps;
6365   if (collectConcatOps(V.getNode(), CatOps)) {
6366     for (SDValue &CatOp : CatOps) {
6367       SDValue NotCat = IsNOT(CatOp, DAG);
6368       if (!NotCat) return SDValue();
6369       CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
6370     }
6371     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(V), V.getValueType(), CatOps);
6372   }
6373   return SDValue();
6374 }
6375 
6376 void llvm::createUnpackShuffleMask(EVT VT, SmallVectorImpl<int> &Mask,
6377                                    bool Lo, bool Unary) {
6378   assert(VT.getScalarType().isSimple() && (VT.getSizeInBits() % 128) == 0 &&
6379          "Illegal vector type to unpack");
6380   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6381   int NumElts = VT.getVectorNumElements();
6382   int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6383   for (int i = 0; i < NumElts; ++i) {
6384     unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6385     int Pos = (i % NumEltsInLane) / 2 + LaneStart;
6386     Pos += (Unary ? 0 : NumElts * (i % 2));
6387     Pos += (Lo ? 0 : NumEltsInLane / 2);
6388     Mask.push_back(Pos);
6389   }
6390 }
6391 
6392 /// Similar to unpacklo/unpackhi, but without the 128-bit lane limitation
6393 /// imposed by AVX and specific to the unary pattern. Example:
6394 /// v8iX Lo --> <0, 0, 1, 1, 2, 2, 3, 3>
6395 /// v8iX Hi --> <4, 4, 5, 5, 6, 6, 7, 7>
6396 void llvm::createSplat2ShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6397                                    bool Lo) {
6398   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6399   int NumElts = VT.getVectorNumElements();
6400   for (int i = 0; i < NumElts; ++i) {
6401     int Pos = i / 2;
6402     Pos += (Lo ? 0 : NumElts / 2);
6403     Mask.push_back(Pos);
6404   }
6405 }
6406 
6407 /// Returns a vector_shuffle node for an unpackl operation.
6408 static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
6409                           SDValue V1, SDValue V2) {
6410   SmallVector<int, 8> Mask;
6411   createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
6412   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6413 }
6414 
6415 /// Returns a vector_shuffle node for an unpackh operation.
6416 static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, EVT VT,
6417                           SDValue V1, SDValue V2) {
6418   SmallVector<int, 8> Mask;
6419   createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
6420   return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
6421 }
6422 
6423 /// Return a vector_shuffle of the specified vector of zero or undef vector.
6424 /// This produces a shuffle where the low element of V2 is swizzled into the
6425 /// zero/undef vector, landing at element Idx.
6426 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
6427 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
6428                                            bool IsZero,
6429                                            const X86Subtarget &Subtarget,
6430                                            SelectionDAG &DAG) {
6431   MVT VT = V2.getSimpleValueType();
6432   SDValue V1 = IsZero
6433     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
6434   int NumElems = VT.getVectorNumElements();
6435   SmallVector<int, 16> MaskVec(NumElems);
6436   for (int i = 0; i != NumElems; ++i)
6437     // If this is the insertion idx, put the low elt of V2 here.
6438     MaskVec[i] = (i == Idx) ? NumElems : i;
6439   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
6440 }
6441 
6442 static const Constant *getTargetConstantFromBasePtr(SDValue Ptr) {
6443   if (Ptr.getOpcode() == X86ISD::Wrapper ||
6444       Ptr.getOpcode() == X86ISD::WrapperRIP)
6445     Ptr = Ptr.getOperand(0);
6446 
6447   auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
6448   if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
6449     return nullptr;
6450 
6451   return CNode->getConstVal();
6452 }
6453 
6454 static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
6455   if (!Load || !ISD::isNormalLoad(Load))
6456     return nullptr;
6457   return getTargetConstantFromBasePtr(Load->getBasePtr());
6458 }
6459 
6460 static const Constant *getTargetConstantFromNode(SDValue Op) {
6461   Op = peekThroughBitcasts(Op);
6462   return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
6463 }
6464 
6465 const Constant *
6466 X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
6467   assert(LD && "Unexpected null LoadSDNode");
6468   return getTargetConstantFromNode(LD);
6469 }
6470 
6471 // Extract raw constant bits from constant pools.
6472 static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
6473                                           APInt &UndefElts,
6474                                           SmallVectorImpl<APInt> &EltBits,
6475                                           bool AllowWholeUndefs = true,
6476                                           bool AllowPartialUndefs = true) {
6477   assert(EltBits.empty() && "Expected an empty EltBits vector");
6478 
6479   Op = peekThroughBitcasts(Op);
6480 
6481   EVT VT = Op.getValueType();
6482   unsigned SizeInBits = VT.getSizeInBits();
6483   assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!");
6484   unsigned NumElts = SizeInBits / EltSizeInBits;
6485 
6486   // Bitcast a source array of element bits to the target size.
6487   auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
6488     unsigned NumSrcElts = UndefSrcElts.getBitWidth();
6489     unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
6490     assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&
6491            "Constant bit sizes don't match");
6492 
6493     // Don't split if we don't allow undef bits.
6494     bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
6495     if (UndefSrcElts.getBoolValue() && !AllowUndefs)
6496       return false;
6497 
6498     // If we're already the right size, don't bother bitcasting.
6499     if (NumSrcElts == NumElts) {
6500       UndefElts = UndefSrcElts;
6501       EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
6502       return true;
6503     }
6504 
6505     // Extract all the undef/constant element data and pack into single bitsets.
6506     APInt UndefBits(SizeInBits, 0);
6507     APInt MaskBits(SizeInBits, 0);
6508 
6509     for (unsigned i = 0; i != NumSrcElts; ++i) {
6510       unsigned BitOffset = i * SrcEltSizeInBits;
6511       if (UndefSrcElts[i])
6512         UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
6513       MaskBits.insertBits(SrcEltBits[i], BitOffset);
6514     }
6515 
6516     // Split the undef/constant single bitset data into the target elements.
6517     UndefElts = APInt(NumElts, 0);
6518     EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
6519 
6520     for (unsigned i = 0; i != NumElts; ++i) {
6521       unsigned BitOffset = i * EltSizeInBits;
6522       APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
6523 
6524       // Only treat an element as UNDEF if all bits are UNDEF.
6525       if (UndefEltBits.isAllOnesValue()) {
6526         if (!AllowWholeUndefs)
6527           return false;
6528         UndefElts.setBit(i);
6529         continue;
6530       }
6531 
6532       // If only some bits are UNDEF then treat them as zero (or bail if not
6533       // supported).
6534       if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
6535         return false;
6536 
6537       EltBits[i] = MaskBits.extractBits(EltSizeInBits, BitOffset);
6538     }
6539     return true;
6540   };
6541 
6542   // Collect constant bits and insert into mask/undef bit masks.
6543   auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
6544                                 unsigned UndefBitIndex) {
6545     if (!Cst)
6546       return false;
6547     if (isa<UndefValue>(Cst)) {
6548       Undefs.setBit(UndefBitIndex);
6549       return true;
6550     }
6551     if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
6552       Mask = CInt->getValue();
6553       return true;
6554     }
6555     if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
6556       Mask = CFP->getValueAPF().bitcastToAPInt();
6557       return true;
6558     }
6559     return false;
6560   };
6561 
6562   // Handle UNDEFs.
6563   if (Op.isUndef()) {
6564     APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
6565     SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
6566     return CastBitData(UndefSrcElts, SrcEltBits);
6567   }
6568 
6569   // Extract scalar constant bits.
6570   if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
6571     APInt UndefSrcElts = APInt::getNullValue(1);
6572     SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
6573     return CastBitData(UndefSrcElts, SrcEltBits);
6574   }
6575   if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
6576     APInt UndefSrcElts = APInt::getNullValue(1);
6577     APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6578     SmallVector<APInt, 64> SrcEltBits(1, RawBits);
6579     return CastBitData(UndefSrcElts, SrcEltBits);
6580   }
6581 
6582   // Extract constant bits from build vector.
6583   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
6584     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6585     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6586 
6587     APInt UndefSrcElts(NumSrcElts, 0);
6588     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6589     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6590       const SDValue &Src = Op.getOperand(i);
6591       if (Src.isUndef()) {
6592         UndefSrcElts.setBit(i);
6593         continue;
6594       }
6595       auto *Cst = cast<ConstantSDNode>(Src);
6596       SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
6597     }
6598     return CastBitData(UndefSrcElts, SrcEltBits);
6599   }
6600   if (ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) {
6601     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6602     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6603 
6604     APInt UndefSrcElts(NumSrcElts, 0);
6605     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6606     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
6607       const SDValue &Src = Op.getOperand(i);
6608       if (Src.isUndef()) {
6609         UndefSrcElts.setBit(i);
6610         continue;
6611       }
6612       auto *Cst = cast<ConstantFPSDNode>(Src);
6613       APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
6614       SrcEltBits[i] = RawBits.zextOrTrunc(SrcEltSizeInBits);
6615     }
6616     return CastBitData(UndefSrcElts, SrcEltBits);
6617   }
6618 
6619   // Extract constant bits from constant pool vector.
6620   if (auto *Cst = getTargetConstantFromNode(Op)) {
6621     Type *CstTy = Cst->getType();
6622     unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
6623     if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
6624       return false;
6625 
6626     unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
6627     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6628 
6629     APInt UndefSrcElts(NumSrcElts, 0);
6630     SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
6631     for (unsigned i = 0; i != NumSrcElts; ++i)
6632       if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
6633                                UndefSrcElts, i))
6634         return false;
6635 
6636     return CastBitData(UndefSrcElts, SrcEltBits);
6637   }
6638 
6639   // Extract constant bits from a broadcasted constant pool scalar.
6640   if (Op.getOpcode() == X86ISD::VBROADCAST_LOAD &&
6641       EltSizeInBits <= VT.getScalarSizeInBits()) {
6642     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
6643     if (MemIntr->getMemoryVT().getScalarSizeInBits() != VT.getScalarSizeInBits())
6644       return false;
6645 
6646     SDValue Ptr = MemIntr->getBasePtr();
6647     if (const Constant *C = getTargetConstantFromBasePtr(Ptr)) {
6648       unsigned SrcEltSizeInBits = C->getType()->getScalarSizeInBits();
6649       unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6650 
6651       APInt UndefSrcElts(NumSrcElts, 0);
6652       SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
6653       if (CollectConstantBits(C, SrcEltBits[0], UndefSrcElts, 0)) {
6654         if (UndefSrcElts[0])
6655           UndefSrcElts.setBits(0, NumSrcElts);
6656         SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
6657         return CastBitData(UndefSrcElts, SrcEltBits);
6658       }
6659     }
6660   }
6661 
6662   // Extract constant bits from a subvector broadcast.
6663   if (Op.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
6664     auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
6665     SDValue Ptr = MemIntr->getBasePtr();
6666     if (const Constant *Cst = getTargetConstantFromBasePtr(Ptr)) {
6667       Type *CstTy = Cst->getType();
6668       unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
6669       if (!CstTy->isVectorTy() || (SizeInBits % CstSizeInBits) != 0)
6670         return false;
6671       unsigned SubEltSizeInBits = CstTy->getScalarSizeInBits();
6672       unsigned NumSubElts = CstSizeInBits / SubEltSizeInBits;
6673       unsigned NumSubVecs = SizeInBits / CstSizeInBits;
6674       APInt UndefSubElts(NumSubElts, 0);
6675       SmallVector<APInt, 64> SubEltBits(NumSubElts * NumSubVecs,
6676                                         APInt(SubEltSizeInBits, 0));
6677       for (unsigned i = 0; i != NumSubElts; ++i) {
6678         if (!CollectConstantBits(Cst->getAggregateElement(i), SubEltBits[i],
6679                                  UndefSubElts, i))
6680           return false;
6681         for (unsigned j = 1; j != NumSubVecs; ++j)
6682           SubEltBits[i + (j * NumSubElts)] = SubEltBits[i];
6683       }
6684       UndefSubElts = APInt::getSplat(NumSubVecs * UndefSubElts.getBitWidth(),
6685                                      UndefSubElts);
6686       return CastBitData(UndefSubElts, SubEltBits);
6687     }
6688   }
6689 
6690   // Extract a rematerialized scalar constant insertion.
6691   if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
6692       Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6693       isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
6694     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6695     unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
6696 
6697     APInt UndefSrcElts(NumSrcElts, 0);
6698     SmallVector<APInt, 64> SrcEltBits;
6699     auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
6700     SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
6701     SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
6702     return CastBitData(UndefSrcElts, SrcEltBits);
6703   }
6704 
6705   // Insert constant bits from a base and sub vector sources.
6706   if (Op.getOpcode() == ISD::INSERT_SUBVECTOR) {
6707     // If bitcasts to larger elements we might lose track of undefs - don't
6708     // allow any to be safe.
6709     unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
6710     bool AllowUndefs = EltSizeInBits >= SrcEltSizeInBits;
6711 
6712     APInt UndefSrcElts, UndefSubElts;
6713     SmallVector<APInt, 32> EltSrcBits, EltSubBits;
6714     if (getTargetConstantBitsFromNode(Op.getOperand(1), SrcEltSizeInBits,
6715                                       UndefSubElts, EltSubBits,
6716                                       AllowWholeUndefs && AllowUndefs,
6717                                       AllowPartialUndefs && AllowUndefs) &&
6718         getTargetConstantBitsFromNode(Op.getOperand(0), SrcEltSizeInBits,
6719                                       UndefSrcElts, EltSrcBits,
6720                                       AllowWholeUndefs && AllowUndefs,
6721                                       AllowPartialUndefs && AllowUndefs)) {
6722       unsigned BaseIdx = Op.getConstantOperandVal(2);
6723       UndefSrcElts.insertBits(UndefSubElts, BaseIdx);
6724       for (unsigned i = 0, e = EltSubBits.size(); i != e; ++i)
6725         EltSrcBits[BaseIdx + i] = EltSubBits[i];
6726       return CastBitData(UndefSrcElts, EltSrcBits);
6727     }
6728   }
6729 
6730   // Extract constant bits from a subvector's source.
6731   if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6732     // TODO - support extract_subvector through bitcasts.
6733     if (EltSizeInBits != VT.getScalarSizeInBits())
6734       return false;
6735 
6736     if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6737                                       UndefElts, EltBits, AllowWholeUndefs,
6738                                       AllowPartialUndefs)) {
6739       EVT SrcVT = Op.getOperand(0).getValueType();
6740       unsigned NumSrcElts = SrcVT.getVectorNumElements();
6741       unsigned NumSubElts = VT.getVectorNumElements();
6742       unsigned BaseIdx = Op.getConstantOperandVal(1);
6743       UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
6744       if ((BaseIdx + NumSubElts) != NumSrcElts)
6745         EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
6746       if (BaseIdx != 0)
6747         EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
6748       return true;
6749     }
6750   }
6751 
6752   // Extract constant bits from shuffle node sources.
6753   if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
6754     // TODO - support shuffle through bitcasts.
6755     if (EltSizeInBits != VT.getScalarSizeInBits())
6756       return false;
6757 
6758     ArrayRef<int> Mask = SVN->getMask();
6759     if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
6760         llvm::any_of(Mask, [](int M) { return M < 0; }))
6761       return false;
6762 
6763     APInt UndefElts0, UndefElts1;
6764     SmallVector<APInt, 32> EltBits0, EltBits1;
6765     if (isAnyInRange(Mask, 0, NumElts) &&
6766         !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6767                                        UndefElts0, EltBits0, AllowWholeUndefs,
6768                                        AllowPartialUndefs))
6769       return false;
6770     if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
6771         !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6772                                        UndefElts1, EltBits1, AllowWholeUndefs,
6773                                        AllowPartialUndefs))
6774       return false;
6775 
6776     UndefElts = APInt::getNullValue(NumElts);
6777     for (int i = 0; i != (int)NumElts; ++i) {
6778       int M = Mask[i];
6779       if (M < 0) {
6780         UndefElts.setBit(i);
6781         EltBits.push_back(APInt::getNullValue(EltSizeInBits));
6782       } else if (M < (int)NumElts) {
6783         if (UndefElts0[M])
6784           UndefElts.setBit(i);
6785         EltBits.push_back(EltBits0[M]);
6786       } else {
6787         if (UndefElts1[M - NumElts])
6788           UndefElts.setBit(i);
6789         EltBits.push_back(EltBits1[M - NumElts]);
6790       }
6791     }
6792     return true;
6793   }
6794 
6795   return false;
6796 }
6797 
6798 namespace llvm {
6799 namespace X86 {
6800 bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs) {
6801   APInt UndefElts;
6802   SmallVector<APInt, 16> EltBits;
6803   if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
6804                                     UndefElts, EltBits, true,
6805                                     AllowPartialUndefs)) {
6806     int SplatIndex = -1;
6807     for (int i = 0, e = EltBits.size(); i != e; ++i) {
6808       if (UndefElts[i])
6809         continue;
6810       if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
6811         SplatIndex = -1;
6812         break;
6813       }
6814       SplatIndex = i;
6815     }
6816     if (0 <= SplatIndex) {
6817       SplatVal = EltBits[SplatIndex];
6818       return true;
6819     }
6820   }
6821 
6822   return false;
6823 }
6824 } // namespace X86
6825 } // namespace llvm
6826 
6827 static bool getTargetShuffleMaskIndices(SDValue MaskNode,
6828                                         unsigned MaskEltSizeInBits,
6829                                         SmallVectorImpl<uint64_t> &RawMask,
6830                                         APInt &UndefElts) {
6831   // Extract the raw target constant bits.
6832   SmallVector<APInt, 64> EltBits;
6833   if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
6834                                      EltBits, /* AllowWholeUndefs */ true,
6835                                      /* AllowPartialUndefs */ false))
6836     return false;
6837 
6838   // Insert the extracted elements into the mask.
6839   for (const APInt &Elt : EltBits)
6840     RawMask.push_back(Elt.getZExtValue());
6841 
6842   return true;
6843 }
6844 
6845 /// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
6846 /// A multi-stage pack shuffle mask is created by specifying NumStages > 1.
6847 /// Note: This ignores saturation, so inputs must be checked first.
6848 static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6849                                   bool Unary, unsigned NumStages = 1) {
6850   assert(Mask.empty() && "Expected an empty shuffle mask vector");
6851   unsigned NumElts = VT.getVectorNumElements();
6852   unsigned NumLanes = VT.getSizeInBits() / 128;
6853   unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
6854   unsigned Offset = Unary ? 0 : NumElts;
6855   unsigned Repetitions = 1u << (NumStages - 1);
6856   unsigned Increment = 1u << NumStages;
6857   assert((NumEltsPerLane >> NumStages) > 0 && "Illegal packing compaction");
6858 
6859   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
6860     for (unsigned Stage = 0; Stage != Repetitions; ++Stage) {
6861       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
6862         Mask.push_back(Elt + (Lane * NumEltsPerLane));
6863       for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += Increment)
6864         Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
6865     }
6866   }
6867 }
6868 
6869 // Split the demanded elts of a PACKSS/PACKUS node between its operands.
6870 static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
6871                                 APInt &DemandedLHS, APInt &DemandedRHS) {
6872   int NumLanes = VT.getSizeInBits() / 128;
6873   int NumElts = DemandedElts.getBitWidth();
6874   int NumInnerElts = NumElts / 2;
6875   int NumEltsPerLane = NumElts / NumLanes;
6876   int NumInnerEltsPerLane = NumInnerElts / NumLanes;
6877 
6878   DemandedLHS = APInt::getNullValue(NumInnerElts);
6879   DemandedRHS = APInt::getNullValue(NumInnerElts);
6880 
6881   // Map DemandedElts to the packed operands.
6882   for (int Lane = 0; Lane != NumLanes; ++Lane) {
6883     for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
6884       int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6885       int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6886       if (DemandedElts[OuterIdx])
6887         DemandedLHS.setBit(InnerIdx);
6888       if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6889         DemandedRHS.setBit(InnerIdx);
6890     }
6891   }
6892 }
6893 
6894 // Split the demanded elts of a HADD/HSUB node between its operands.
6895 static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
6896                                  APInt &DemandedLHS, APInt &DemandedRHS) {
6897   int NumLanes = VT.getSizeInBits() / 128;
6898   int NumElts = DemandedElts.getBitWidth();
6899   int NumEltsPerLane = NumElts / NumLanes;
6900   int HalfEltsPerLane = NumEltsPerLane / 2;
6901 
6902   DemandedLHS = APInt::getNullValue(NumElts);
6903   DemandedRHS = APInt::getNullValue(NumElts);
6904 
6905   // Map DemandedElts to the horizontal operands.
6906   for (int Idx = 0; Idx != NumElts; ++Idx) {
6907     if (!DemandedElts[Idx])
6908       continue;
6909     int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
6910     int LocalIdx = Idx % NumEltsPerLane;
6911     if (LocalIdx < HalfEltsPerLane) {
6912       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6913       DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6914     } else {
6915       LocalIdx -= HalfEltsPerLane;
6916       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6917       DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6918     }
6919   }
6920 }
6921 
6922 /// Calculates the shuffle mask corresponding to the target-specific opcode.
6923 /// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6924 /// operands in \p Ops, and returns true.
6925 /// Sets \p IsUnary to true if only one source is used. Note that this will set
6926 /// IsUnary for shuffles which use a single input multiple times, and in those
6927 /// cases it will adjust the mask to only have indices within that single input.
6928 /// It is an error to call this with non-empty Mask/Ops vectors.
6929 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
6930                                  SmallVectorImpl<SDValue> &Ops,
6931                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
6932   unsigned NumElems = VT.getVectorNumElements();
6933   unsigned MaskEltSize = VT.getScalarSizeInBits();
6934   SmallVector<uint64_t, 32> RawMask;
6935   APInt RawUndefs;
6936   uint64_t ImmN;
6937 
6938   assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector");
6939   assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector");
6940 
6941   IsUnary = false;
6942   bool IsFakeUnary = false;
6943   switch (N->getOpcode()) {
6944   case X86ISD::BLENDI:
6945     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6946     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6947     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6948     DecodeBLENDMask(NumElems, ImmN, Mask);
6949     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6950     break;
6951   case X86ISD::SHUFP:
6952     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6953     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6954     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6955     DecodeSHUFPMask(NumElems, MaskEltSize, ImmN, Mask);
6956     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6957     break;
6958   case X86ISD::INSERTPS:
6959     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6960     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6961     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
6962     DecodeINSERTPSMask(ImmN, Mask);
6963     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6964     break;
6965   case X86ISD::EXTRQI:
6966     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6967     if (isa<ConstantSDNode>(N->getOperand(1)) &&
6968         isa<ConstantSDNode>(N->getOperand(2))) {
6969       int BitLen = N->getConstantOperandVal(1);
6970       int BitIdx = N->getConstantOperandVal(2);
6971       DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6972       IsUnary = true;
6973     }
6974     break;
6975   case X86ISD::INSERTQI:
6976     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6977     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6978     if (isa<ConstantSDNode>(N->getOperand(2)) &&
6979         isa<ConstantSDNode>(N->getOperand(3))) {
6980       int BitLen = N->getConstantOperandVal(2);
6981       int BitIdx = N->getConstantOperandVal(3);
6982       DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6983       IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6984     }
6985     break;
6986   case X86ISD::UNPCKH:
6987     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6988     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6989     DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6990     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6991     break;
6992   case X86ISD::UNPCKL:
6993     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
6994     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
6995     DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6996     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6997     break;
6998   case X86ISD::MOVHLPS:
6999     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7000     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7001     DecodeMOVHLPSMask(NumElems, Mask);
7002     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7003     break;
7004   case X86ISD::MOVLHPS:
7005     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7006     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7007     DecodeMOVLHPSMask(NumElems, Mask);
7008     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7009     break;
7010   case X86ISD::VALIGN:
7011     assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
7012            "Only 32-bit and 64-bit elements are supported!");
7013     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7014     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7015     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7016     DecodeVALIGNMask(NumElems, ImmN, Mask);
7017     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7018     Ops.push_back(N->getOperand(1));
7019     Ops.push_back(N->getOperand(0));
7020     break;
7021   case X86ISD::PALIGNR:
7022     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7023     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7024     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7025     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7026     DecodePALIGNRMask(NumElems, ImmN, Mask);
7027     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7028     Ops.push_back(N->getOperand(1));
7029     Ops.push_back(N->getOperand(0));
7030     break;
7031   case X86ISD::VSHLDQ:
7032     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7033     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7034     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7035     DecodePSLLDQMask(NumElems, ImmN, Mask);
7036     IsUnary = true;
7037     break;
7038   case X86ISD::VSRLDQ:
7039     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7040     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7041     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7042     DecodePSRLDQMask(NumElems, ImmN, Mask);
7043     IsUnary = true;
7044     break;
7045   case X86ISD::PSHUFD:
7046   case X86ISD::VPERMILPI:
7047     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7048     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7049     DecodePSHUFMask(NumElems, MaskEltSize, ImmN, Mask);
7050     IsUnary = true;
7051     break;
7052   case X86ISD::PSHUFHW:
7053     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7054     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7055     DecodePSHUFHWMask(NumElems, ImmN, Mask);
7056     IsUnary = true;
7057     break;
7058   case X86ISD::PSHUFLW:
7059     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7060     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7061     DecodePSHUFLWMask(NumElems, ImmN, Mask);
7062     IsUnary = true;
7063     break;
7064   case X86ISD::VZEXT_MOVL:
7065     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7066     DecodeZeroMoveLowMask(NumElems, Mask);
7067     IsUnary = true;
7068     break;
7069   case X86ISD::VBROADCAST:
7070     // We only decode broadcasts of same-sized vectors, peeking through to
7071     // extracted subvectors is likely to cause hasOneUse issues with
7072     // SimplifyDemandedBits etc.
7073     if (N->getOperand(0).getValueType() == VT) {
7074       DecodeVectorBroadcast(NumElems, Mask);
7075       IsUnary = true;
7076       break;
7077     }
7078     return false;
7079   case X86ISD::VPERMILPV: {
7080     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7081     IsUnary = true;
7082     SDValue MaskNode = N->getOperand(1);
7083     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7084                                     RawUndefs)) {
7085       DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
7086       break;
7087     }
7088     return false;
7089   }
7090   case X86ISD::PSHUFB: {
7091     assert(VT.getScalarType() == MVT::i8 && "Byte vector expected");
7092     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7093     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7094     IsUnary = true;
7095     SDValue MaskNode = N->getOperand(1);
7096     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7097       DecodePSHUFBMask(RawMask, RawUndefs, Mask);
7098       break;
7099     }
7100     return false;
7101   }
7102   case X86ISD::VPERMI:
7103     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7104     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7105     DecodeVPERMMask(NumElems, ImmN, Mask);
7106     IsUnary = true;
7107     break;
7108   case X86ISD::MOVSS:
7109   case X86ISD::MOVSD:
7110     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7111     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7112     DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
7113     break;
7114   case X86ISD::VPERM2X128:
7115     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7116     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7117     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7118     DecodeVPERM2X128Mask(NumElems, ImmN, Mask);
7119     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7120     break;
7121   case X86ISD::SHUF128:
7122     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7123     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7124     ImmN = N->getConstantOperandVal(N->getNumOperands() - 1);
7125     decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize, ImmN, Mask);
7126     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7127     break;
7128   case X86ISD::MOVSLDUP:
7129     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7130     DecodeMOVSLDUPMask(NumElems, Mask);
7131     IsUnary = true;
7132     break;
7133   case X86ISD::MOVSHDUP:
7134     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7135     DecodeMOVSHDUPMask(NumElems, Mask);
7136     IsUnary = true;
7137     break;
7138   case X86ISD::MOVDDUP:
7139     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7140     DecodeMOVDDUPMask(NumElems, Mask);
7141     IsUnary = true;
7142     break;
7143   case X86ISD::VPERMIL2: {
7144     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7145     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7146     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7147     SDValue MaskNode = N->getOperand(2);
7148     SDValue CtrlNode = N->getOperand(3);
7149     if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
7150       unsigned CtrlImm = CtrlOp->getZExtValue();
7151       if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7152                                       RawUndefs)) {
7153         DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
7154                             Mask);
7155         break;
7156       }
7157     }
7158     return false;
7159   }
7160   case X86ISD::VPPERM: {
7161     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7162     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7163     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
7164     SDValue MaskNode = N->getOperand(2);
7165     if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
7166       DecodeVPPERMMask(RawMask, RawUndefs, Mask);
7167       break;
7168     }
7169     return false;
7170   }
7171   case X86ISD::VPERMV: {
7172     assert(N->getOperand(1).getValueType() == VT && "Unexpected value type");
7173     IsUnary = true;
7174     // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
7175     Ops.push_back(N->getOperand(1));
7176     SDValue MaskNode = N->getOperand(0);
7177     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7178                                     RawUndefs)) {
7179       DecodeVPERMVMask(RawMask, RawUndefs, Mask);
7180       break;
7181     }
7182     return false;
7183   }
7184   case X86ISD::VPERMV3: {
7185     assert(N->getOperand(0).getValueType() == VT && "Unexpected value type");
7186     assert(N->getOperand(2).getValueType() == VT && "Unexpected value type");
7187     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
7188     // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
7189     Ops.push_back(N->getOperand(0));
7190     Ops.push_back(N->getOperand(2));
7191     SDValue MaskNode = N->getOperand(1);
7192     if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
7193                                     RawUndefs)) {
7194       DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
7195       break;
7196     }
7197     return false;
7198   }
7199   default: llvm_unreachable("unknown target shuffle node");
7200   }
7201 
7202   // Empty mask indicates the decode failed.
7203   if (Mask.empty())
7204     return false;
7205 
7206   // Check if we're getting a shuffle mask with zero'd elements.
7207   if (!AllowSentinelZero && isAnyZero(Mask))
7208     return false;
7209 
7210   // If we have a fake unary shuffle, the shuffle mask is spread across two
7211   // inputs that are actually the same node. Re-map the mask to always point
7212   // into the first input.
7213   if (IsFakeUnary)
7214     for (int &M : Mask)
7215       if (M >= (int)Mask.size())
7216         M -= Mask.size();
7217 
7218   // If we didn't already add operands in the opcode-specific code, default to
7219   // adding 1 or 2 operands starting at 0.
7220   if (Ops.empty()) {
7221     Ops.push_back(N->getOperand(0));
7222     if (!IsUnary || IsFakeUnary)
7223       Ops.push_back(N->getOperand(1));
7224   }
7225 
7226   return true;
7227 }
7228 
7229 /// Compute whether each element of a shuffle is zeroable.
7230 ///
7231 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7232 /// Either it is an undef element in the shuffle mask, the element of the input
7233 /// referenced is undef, or the element of the input referenced is known to be
7234 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7235 /// as many lanes with this technique as possible to simplify the remaining
7236 /// shuffle.
7237 static void computeZeroableShuffleElements(ArrayRef<int> Mask,
7238                                            SDValue V1, SDValue V2,
7239                                            APInt &KnownUndef, APInt &KnownZero) {
7240   int Size = Mask.size();
7241   KnownUndef = KnownZero = APInt::getNullValue(Size);
7242 
7243   V1 = peekThroughBitcasts(V1);
7244   V2 = peekThroughBitcasts(V2);
7245 
7246   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7247   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7248 
7249   int VectorSizeInBits = V1.getValueSizeInBits();
7250   int ScalarSizeInBits = VectorSizeInBits / Size;
7251   assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size");
7252 
7253   for (int i = 0; i < Size; ++i) {
7254     int M = Mask[i];
7255     // Handle the easy cases.
7256     if (M < 0) {
7257       KnownUndef.setBit(i);
7258       continue;
7259     }
7260     if ((M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7261       KnownZero.setBit(i);
7262       continue;
7263     }
7264 
7265     // Determine shuffle input and normalize the mask.
7266     SDValue V = M < Size ? V1 : V2;
7267     M %= Size;
7268 
7269     // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
7270     if (V.getOpcode() != ISD::BUILD_VECTOR)
7271       continue;
7272 
7273     // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
7274     // the (larger) source element must be UNDEF/ZERO.
7275     if ((Size % V.getNumOperands()) == 0) {
7276       int Scale = Size / V->getNumOperands();
7277       SDValue Op = V.getOperand(M / Scale);
7278       if (Op.isUndef())
7279         KnownUndef.setBit(i);
7280       if (X86::isZeroNode(Op))
7281         KnownZero.setBit(i);
7282       else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
7283         APInt Val = Cst->getAPIntValue();
7284         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7285         if (Val == 0)
7286           KnownZero.setBit(i);
7287       } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
7288         APInt Val = Cst->getValueAPF().bitcastToAPInt();
7289         Val = Val.extractBits(ScalarSizeInBits, (M % Scale) * ScalarSizeInBits);
7290         if (Val == 0)
7291           KnownZero.setBit(i);
7292       }
7293       continue;
7294     }
7295 
7296     // If the BUILD_VECTOR has more elements then all the (smaller) source
7297     // elements must be UNDEF or ZERO.
7298     if ((V.getNumOperands() % Size) == 0) {
7299       int Scale = V->getNumOperands() / Size;
7300       bool AllUndef = true;
7301       bool AllZero = true;
7302       for (int j = 0; j < Scale; ++j) {
7303         SDValue Op = V.getOperand((M * Scale) + j);
7304         AllUndef &= Op.isUndef();
7305         AllZero &= X86::isZeroNode(Op);
7306       }
7307       if (AllUndef)
7308         KnownUndef.setBit(i);
7309       if (AllZero)
7310         KnownZero.setBit(i);
7311       continue;
7312     }
7313   }
7314 }
7315 
7316 /// Decode a target shuffle mask and inputs and see if any values are
7317 /// known to be undef or zero from their inputs.
7318 /// Returns true if the target shuffle mask was decoded.
7319 /// FIXME: Merge this with computeZeroableShuffleElements?
7320 static bool getTargetShuffleAndZeroables(SDValue N, SmallVectorImpl<int> &Mask,
7321                                          SmallVectorImpl<SDValue> &Ops,
7322                                          APInt &KnownUndef, APInt &KnownZero) {
7323   bool IsUnary;
7324   if (!isTargetShuffle(N.getOpcode()))
7325     return false;
7326 
7327   MVT VT = N.getSimpleValueType();
7328   if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
7329     return false;
7330 
7331   int Size = Mask.size();
7332   SDValue V1 = Ops[0];
7333   SDValue V2 = IsUnary ? V1 : Ops[1];
7334   KnownUndef = KnownZero = APInt::getNullValue(Size);
7335 
7336   V1 = peekThroughBitcasts(V1);
7337   V2 = peekThroughBitcasts(V2);
7338 
7339   assert((VT.getSizeInBits() % Size) == 0 &&
7340          "Illegal split of shuffle value type");
7341   unsigned EltSizeInBits = VT.getSizeInBits() / Size;
7342 
7343   // Extract known constant input data.
7344   APInt UndefSrcElts[2];
7345   SmallVector<APInt, 32> SrcEltBits[2];
7346   bool IsSrcConstant[2] = {
7347       getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
7348                                     SrcEltBits[0], true, false),
7349       getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
7350                                     SrcEltBits[1], true, false)};
7351 
7352   for (int i = 0; i < Size; ++i) {
7353     int M = Mask[i];
7354 
7355     // Already decoded as SM_SentinelZero / SM_SentinelUndef.
7356     if (M < 0) {
7357       assert(isUndefOrZero(M) && "Unknown shuffle sentinel value!");
7358       if (SM_SentinelUndef == M)
7359         KnownUndef.setBit(i);
7360       if (SM_SentinelZero == M)
7361         KnownZero.setBit(i);
7362       continue;
7363     }
7364 
7365     // Determine shuffle input and normalize the mask.
7366     unsigned SrcIdx = M / Size;
7367     SDValue V = M < Size ? V1 : V2;
7368     M %= Size;
7369 
7370     // We are referencing an UNDEF input.
7371     if (V.isUndef()) {
7372       KnownUndef.setBit(i);
7373       continue;
7374     }
7375 
7376     // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
7377     // TODO: We currently only set UNDEF for integer types - floats use the same
7378     // registers as vectors and many of the scalar folded loads rely on the
7379     // SCALAR_TO_VECTOR pattern.
7380     if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7381         (Size % V.getValueType().getVectorNumElements()) == 0) {
7382       int Scale = Size / V.getValueType().getVectorNumElements();
7383       int Idx = M / Scale;
7384       if (Idx != 0 && !VT.isFloatingPoint())
7385         KnownUndef.setBit(i);
7386       else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
7387         KnownZero.setBit(i);
7388       continue;
7389     }
7390 
7391     // INSERT_SUBVECTOR - to widen vectors we often insert them into UNDEF
7392     // base vectors.
7393     if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
7394       SDValue Vec = V.getOperand(0);
7395       int NumVecElts = Vec.getValueType().getVectorNumElements();
7396       if (Vec.isUndef() && Size == NumVecElts) {
7397         int Idx = V.getConstantOperandVal(2);
7398         int NumSubElts = V.getOperand(1).getValueType().getVectorNumElements();
7399         if (M < Idx || (Idx + NumSubElts) <= M)
7400           KnownUndef.setBit(i);
7401       }
7402       continue;
7403     }
7404 
7405     // Attempt to extract from the source's constant bits.
7406     if (IsSrcConstant[SrcIdx]) {
7407       if (UndefSrcElts[SrcIdx][M])
7408         KnownUndef.setBit(i);
7409       else if (SrcEltBits[SrcIdx][M] == 0)
7410         KnownZero.setBit(i);
7411     }
7412   }
7413 
7414   assert(VT.getVectorNumElements() == (unsigned)Size &&
7415          "Different mask size from vector size!");
7416   return true;
7417 }
7418 
7419 // Replace target shuffle mask elements with known undef/zero sentinels.
7420 static void resolveTargetShuffleFromZeroables(SmallVectorImpl<int> &Mask,
7421                                               const APInt &KnownUndef,
7422                                               const APInt &KnownZero,
7423                                               bool ResolveKnownZeros= true) {
7424   unsigned NumElts = Mask.size();
7425   assert(KnownUndef.getBitWidth() == NumElts &&
7426          KnownZero.getBitWidth() == NumElts && "Shuffle mask size mismatch");
7427 
7428   for (unsigned i = 0; i != NumElts; ++i) {
7429     if (KnownUndef[i])
7430       Mask[i] = SM_SentinelUndef;
7431     else if (ResolveKnownZeros && KnownZero[i])
7432       Mask[i] = SM_SentinelZero;
7433   }
7434 }
7435 
7436 // Extract target shuffle mask sentinel elements to known undef/zero bitmasks.
7437 static void resolveZeroablesFromTargetShuffle(const SmallVectorImpl<int> &Mask,
7438                                               APInt &KnownUndef,
7439                                               APInt &KnownZero) {
7440   unsigned NumElts = Mask.size();
7441   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
7442 
7443   for (unsigned i = 0; i != NumElts; ++i) {
7444     int M = Mask[i];
7445     if (SM_SentinelUndef == M)
7446       KnownUndef.setBit(i);
7447     if (SM_SentinelZero == M)
7448       KnownZero.setBit(i);
7449   }
7450 }
7451 
7452 // Forward declaration (for getFauxShuffleMask recursive check).
7453 // TODO: Use DemandedElts variant.
7454 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7455                                    SmallVectorImpl<int> &Mask,
7456                                    const SelectionDAG &DAG, unsigned Depth,
7457                                    bool ResolveKnownElts);
7458 
7459 // Attempt to decode ops that could be represented as a shuffle mask.
7460 // The decoded shuffle mask may contain a different number of elements to the
7461 // destination value type.
7462 static bool getFauxShuffleMask(SDValue N, const APInt &DemandedElts,
7463                                SmallVectorImpl<int> &Mask,
7464                                SmallVectorImpl<SDValue> &Ops,
7465                                const SelectionDAG &DAG, unsigned Depth,
7466                                bool ResolveKnownElts) {
7467   Mask.clear();
7468   Ops.clear();
7469 
7470   MVT VT = N.getSimpleValueType();
7471   unsigned NumElts = VT.getVectorNumElements();
7472   unsigned NumSizeInBits = VT.getSizeInBits();
7473   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7474   if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
7475     return false;
7476   assert(NumElts == DemandedElts.getBitWidth() && "Unexpected vector size");
7477   unsigned NumSizeInBytes = NumSizeInBits / 8;
7478   unsigned NumBytesPerElt = NumBitsPerElt / 8;
7479 
7480   unsigned Opcode = N.getOpcode();
7481   switch (Opcode) {
7482   case ISD::VECTOR_SHUFFLE: {
7483     // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
7484     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
7485     if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
7486       Mask.append(ShuffleMask.begin(), ShuffleMask.end());
7487       Ops.push_back(N.getOperand(0));
7488       Ops.push_back(N.getOperand(1));
7489       return true;
7490     }
7491     return false;
7492   }
7493   case ISD::AND:
7494   case X86ISD::ANDNP: {
7495     // Attempt to decode as a per-byte mask.
7496     APInt UndefElts;
7497     SmallVector<APInt, 32> EltBits;
7498     SDValue N0 = N.getOperand(0);
7499     SDValue N1 = N.getOperand(1);
7500     bool IsAndN = (X86ISD::ANDNP == Opcode);
7501     uint64_t ZeroMask = IsAndN ? 255 : 0;
7502     if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
7503       return false;
7504     for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
7505       if (UndefElts[i]) {
7506         Mask.push_back(SM_SentinelUndef);
7507         continue;
7508       }
7509       const APInt &ByteBits = EltBits[i];
7510       if (ByteBits != 0 && ByteBits != 255)
7511         return false;
7512       Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
7513     }
7514     Ops.push_back(IsAndN ? N1 : N0);
7515     return true;
7516   }
7517   case ISD::OR: {
7518     // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
7519     // is a valid shuffle index.
7520     SDValue N0 = peekThroughBitcasts(N.getOperand(0));
7521     SDValue N1 = peekThroughBitcasts(N.getOperand(1));
7522     if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
7523       return false;
7524     SmallVector<int, 64> SrcMask0, SrcMask1;
7525     SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
7526     if (!getTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG, Depth + 1,
7527                                 true) ||
7528         !getTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG, Depth + 1,
7529                                 true))
7530       return false;
7531 
7532     size_t MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
7533     SmallVector<int, 64> Mask0, Mask1;
7534     narrowShuffleMaskElts(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
7535     narrowShuffleMaskElts(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
7536     for (int i = 0; i != (int)MaskSize; ++i) {
7537       if (Mask0[i] == SM_SentinelUndef && Mask1[i] == SM_SentinelUndef)
7538         Mask.push_back(SM_SentinelUndef);
7539       else if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
7540         Mask.push_back(SM_SentinelZero);
7541       else if (Mask1[i] == SM_SentinelZero)
7542         Mask.push_back(i);
7543       else if (Mask0[i] == SM_SentinelZero)
7544         Mask.push_back(i + MaskSize);
7545       else
7546         return false;
7547     }
7548     Ops.push_back(N0);
7549     Ops.push_back(N1);
7550     return true;
7551   }
7552   case ISD::INSERT_SUBVECTOR: {
7553     SDValue Src = N.getOperand(0);
7554     SDValue Sub = N.getOperand(1);
7555     EVT SubVT = Sub.getValueType();
7556     unsigned NumSubElts = SubVT.getVectorNumElements();
7557     if (!N->isOnlyUserOf(Sub.getNode()))
7558       return false;
7559     uint64_t InsertIdx = N.getConstantOperandVal(2);
7560     // Handle INSERT_SUBVECTOR(SRC0, EXTRACT_SUBVECTOR(SRC1)).
7561     if (Sub.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
7562         Sub.getOperand(0).getValueType() == VT) {
7563       uint64_t ExtractIdx = Sub.getConstantOperandVal(1);
7564       for (int i = 0; i != (int)NumElts; ++i)
7565         Mask.push_back(i);
7566       for (int i = 0; i != (int)NumSubElts; ++i)
7567         Mask[InsertIdx + i] = NumElts + ExtractIdx + i;
7568       Ops.push_back(Src);
7569       Ops.push_back(Sub.getOperand(0));
7570       return true;
7571     }
7572     // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
7573     SmallVector<int, 64> SubMask;
7574     SmallVector<SDValue, 2> SubInputs;
7575     if (!getTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
7576                                 SubMask, DAG, Depth + 1, ResolveKnownElts))
7577       return false;
7578 
7579     // Subvector shuffle inputs must not be larger than the subvector.
7580     if (llvm::any_of(SubInputs, [SubVT](SDValue SubInput) {
7581           return SubVT.getFixedSizeInBits() <
7582                  SubInput.getValueSizeInBits().getFixedSize();
7583         }))
7584       return false;
7585 
7586     if (SubMask.size() != NumSubElts) {
7587       assert(((SubMask.size() % NumSubElts) == 0 ||
7588               (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale");
7589       if ((NumSubElts % SubMask.size()) == 0) {
7590         int Scale = NumSubElts / SubMask.size();
7591         SmallVector<int,64> ScaledSubMask;
7592         narrowShuffleMaskElts(Scale, SubMask, ScaledSubMask);
7593         SubMask = ScaledSubMask;
7594       } else {
7595         int Scale = SubMask.size() / NumSubElts;
7596         NumSubElts = SubMask.size();
7597         NumElts *= Scale;
7598         InsertIdx *= Scale;
7599       }
7600     }
7601     Ops.push_back(Src);
7602     Ops.append(SubInputs.begin(), SubInputs.end());
7603     if (ISD::isBuildVectorAllZeros(Src.getNode()))
7604       Mask.append(NumElts, SM_SentinelZero);
7605     else
7606       for (int i = 0; i != (int)NumElts; ++i)
7607         Mask.push_back(i);
7608     for (int i = 0; i != (int)NumSubElts; ++i) {
7609       int M = SubMask[i];
7610       if (0 <= M) {
7611         int InputIdx = M / NumSubElts;
7612         M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
7613       }
7614       Mask[i + InsertIdx] = M;
7615     }
7616     return true;
7617   }
7618   case X86ISD::PINSRB:
7619   case X86ISD::PINSRW:
7620   case ISD::SCALAR_TO_VECTOR:
7621   case ISD::INSERT_VECTOR_ELT: {
7622     // Match against a insert_vector_elt/scalar_to_vector of an extract from a
7623     // vector, for matching src/dst vector types.
7624     SDValue Scl = N.getOperand(Opcode == ISD::SCALAR_TO_VECTOR ? 0 : 1);
7625 
7626     unsigned DstIdx = 0;
7627     if (Opcode != ISD::SCALAR_TO_VECTOR) {
7628       // Check we have an in-range constant insertion index.
7629       if (!isa<ConstantSDNode>(N.getOperand(2)) ||
7630           N.getConstantOperandAPInt(2).uge(NumElts))
7631         return false;
7632       DstIdx = N.getConstantOperandVal(2);
7633 
7634       // Attempt to recognise an INSERT*(VEC, 0, DstIdx) shuffle pattern.
7635       if (X86::isZeroNode(Scl)) {
7636         Ops.push_back(N.getOperand(0));
7637         for (unsigned i = 0; i != NumElts; ++i)
7638           Mask.push_back(i == DstIdx ? SM_SentinelZero : (int)i);
7639         return true;
7640       }
7641     }
7642 
7643     // Peek through trunc/aext/zext.
7644     // TODO: aext shouldn't require SM_SentinelZero padding.
7645     // TODO: handle shift of scalars.
7646     unsigned MinBitsPerElt = Scl.getScalarValueSizeInBits();
7647     while (Scl.getOpcode() == ISD::TRUNCATE ||
7648            Scl.getOpcode() == ISD::ANY_EXTEND ||
7649            Scl.getOpcode() == ISD::ZERO_EXTEND) {
7650       Scl = Scl.getOperand(0);
7651       MinBitsPerElt =
7652           std::min<unsigned>(MinBitsPerElt, Scl.getScalarValueSizeInBits());
7653     }
7654     if ((MinBitsPerElt % 8) != 0)
7655       return false;
7656 
7657     // Attempt to find the source vector the scalar was extracted from.
7658     SDValue SrcExtract;
7659     if ((Scl.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
7660          Scl.getOpcode() == X86ISD::PEXTRW ||
7661          Scl.getOpcode() == X86ISD::PEXTRB) &&
7662         Scl.getOperand(0).getValueSizeInBits() == NumSizeInBits) {
7663       SrcExtract = Scl;
7664     }
7665     if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
7666       return false;
7667 
7668     SDValue SrcVec = SrcExtract.getOperand(0);
7669     EVT SrcVT = SrcVec.getValueType();
7670     if (!SrcVT.getScalarType().isByteSized())
7671       return false;
7672     unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
7673     unsigned SrcByte = SrcIdx * (SrcVT.getScalarSizeInBits() / 8);
7674     unsigned DstByte = DstIdx * NumBytesPerElt;
7675     MinBitsPerElt =
7676         std::min<unsigned>(MinBitsPerElt, SrcVT.getScalarSizeInBits());
7677 
7678     // Create 'identity' byte level shuffle mask and then add inserted bytes.
7679     if (Opcode == ISD::SCALAR_TO_VECTOR) {
7680       Ops.push_back(SrcVec);
7681       Mask.append(NumSizeInBytes, SM_SentinelUndef);
7682     } else {
7683       Ops.push_back(SrcVec);
7684       Ops.push_back(N.getOperand(0));
7685       for (int i = 0; i != (int)NumSizeInBytes; ++i)
7686         Mask.push_back(NumSizeInBytes + i);
7687     }
7688 
7689     unsigned MinBytesPerElts = MinBitsPerElt / 8;
7690     MinBytesPerElts = std::min(MinBytesPerElts, NumBytesPerElt);
7691     for (unsigned i = 0; i != MinBytesPerElts; ++i)
7692       Mask[DstByte + i] = SrcByte + i;
7693     for (unsigned i = MinBytesPerElts; i < NumBytesPerElt; ++i)
7694       Mask[DstByte + i] = SM_SentinelZero;
7695     return true;
7696   }
7697   case X86ISD::PACKSS:
7698   case X86ISD::PACKUS: {
7699     SDValue N0 = N.getOperand(0);
7700     SDValue N1 = N.getOperand(1);
7701     assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
7702            N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
7703            "Unexpected input value type");
7704 
7705     APInt EltsLHS, EltsRHS;
7706     getPackDemandedElts(VT, DemandedElts, EltsLHS, EltsRHS);
7707 
7708     // If we know input saturation won't happen (or we don't care for particular
7709     // lanes), we can treat this as a truncation shuffle.
7710     bool Offset0 = false, Offset1 = false;
7711     if (Opcode == X86ISD::PACKSS) {
7712       if ((!(N0.isUndef() || EltsLHS.isNullValue()) &&
7713            DAG.ComputeNumSignBits(N0, EltsLHS, Depth + 1) <= NumBitsPerElt) ||
7714           (!(N1.isUndef() || EltsRHS.isNullValue()) &&
7715            DAG.ComputeNumSignBits(N1, EltsRHS, Depth + 1) <= NumBitsPerElt))
7716         return false;
7717       // We can't easily fold ASHR into a shuffle, but if it was feeding a
7718       // PACKSS then it was likely being used for sign-extension for a
7719       // truncation, so just peek through and adjust the mask accordingly.
7720       if (N0.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N0.getNode()) &&
7721           N0.getConstantOperandAPInt(1) == NumBitsPerElt) {
7722         Offset0 = true;
7723         N0 = N0.getOperand(0);
7724       }
7725       if (N1.getOpcode() == X86ISD::VSRAI && N->isOnlyUserOf(N1.getNode()) &&
7726           N1.getConstantOperandAPInt(1) == NumBitsPerElt) {
7727         Offset1 = true;
7728         N1 = N1.getOperand(0);
7729       }
7730     } else {
7731       APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
7732       if ((!(N0.isUndef() || EltsLHS.isNullValue()) &&
7733            !DAG.MaskedValueIsZero(N0, ZeroMask, EltsLHS, Depth + 1)) ||
7734           (!(N1.isUndef() || EltsRHS.isNullValue()) &&
7735            !DAG.MaskedValueIsZero(N1, ZeroMask, EltsRHS, Depth + 1)))
7736         return false;
7737     }
7738 
7739     bool IsUnary = (N0 == N1);
7740 
7741     Ops.push_back(N0);
7742     if (!IsUnary)
7743       Ops.push_back(N1);
7744 
7745     createPackShuffleMask(VT, Mask, IsUnary);
7746 
7747     if (Offset0 || Offset1) {
7748       for (int &M : Mask)
7749         if ((Offset0 && isInRange(M, 0, NumElts)) ||
7750             (Offset1 && isInRange(M, NumElts, 2 * NumElts)))
7751           ++M;
7752     }
7753     return true;
7754   }
7755   case X86ISD::VTRUNC: {
7756     SDValue Src = N.getOperand(0);
7757     EVT SrcVT = Src.getValueType();
7758     // Truncated source must be a simple vector.
7759     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7760         (SrcVT.getScalarSizeInBits() % 8) != 0)
7761       return false;
7762     unsigned NumSrcElts = SrcVT.getVectorNumElements();
7763     unsigned NumBitsPerSrcElt = SrcVT.getScalarSizeInBits();
7764     unsigned Scale = NumBitsPerSrcElt / NumBitsPerElt;
7765     assert((NumBitsPerSrcElt % NumBitsPerElt) == 0 && "Illegal truncation");
7766     for (unsigned i = 0; i != NumSrcElts; ++i)
7767       Mask.push_back(i * Scale);
7768     Mask.append(NumElts - NumSrcElts, SM_SentinelZero);
7769     Ops.push_back(Src);
7770     return true;
7771   }
7772   case X86ISD::VSHLI:
7773   case X86ISD::VSRLI: {
7774     uint64_t ShiftVal = N.getConstantOperandVal(1);
7775     // Out of range bit shifts are guaranteed to be zero.
7776     if (NumBitsPerElt <= ShiftVal) {
7777       Mask.append(NumElts, SM_SentinelZero);
7778       return true;
7779     }
7780 
7781     // We can only decode 'whole byte' bit shifts as shuffles.
7782     if ((ShiftVal % 8) != 0)
7783       break;
7784 
7785     uint64_t ByteShift = ShiftVal / 8;
7786     Ops.push_back(N.getOperand(0));
7787 
7788     // Clear mask to all zeros and insert the shifted byte indices.
7789     Mask.append(NumSizeInBytes, SM_SentinelZero);
7790 
7791     if (X86ISD::VSHLI == Opcode) {
7792       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7793         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7794           Mask[i + j] = i + j - ByteShift;
7795     } else {
7796       for (unsigned i = 0; i != NumSizeInBytes; i += NumBytesPerElt)
7797         for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
7798           Mask[i + j - ByteShift] = i + j;
7799     }
7800     return true;
7801   }
7802   case X86ISD::VROTLI:
7803   case X86ISD::VROTRI: {
7804     // We can only decode 'whole byte' bit rotates as shuffles.
7805     uint64_t RotateVal = N.getConstantOperandAPInt(1).urem(NumBitsPerElt);
7806     if ((RotateVal % 8) != 0)
7807       return false;
7808     Ops.push_back(N.getOperand(0));
7809     int Offset = RotateVal / 8;
7810     Offset = (X86ISD::VROTLI == Opcode ? NumBytesPerElt - Offset : Offset);
7811     for (int i = 0; i != (int)NumElts; ++i) {
7812       int BaseIdx = i * NumBytesPerElt;
7813       for (int j = 0; j != (int)NumBytesPerElt; ++j) {
7814         Mask.push_back(BaseIdx + ((Offset + j) % NumBytesPerElt));
7815       }
7816     }
7817     return true;
7818   }
7819   case X86ISD::VBROADCAST: {
7820     SDValue Src = N.getOperand(0);
7821     if (!Src.getSimpleValueType().isVector())
7822       return false;
7823     Ops.push_back(Src);
7824     Mask.append(NumElts, 0);
7825     return true;
7826   }
7827   case ISD::ZERO_EXTEND:
7828   case ISD::ANY_EXTEND:
7829   case ISD::ZERO_EXTEND_VECTOR_INREG:
7830   case ISD::ANY_EXTEND_VECTOR_INREG: {
7831     SDValue Src = N.getOperand(0);
7832     EVT SrcVT = Src.getValueType();
7833 
7834     // Extended source must be a simple vector.
7835     if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
7836         (SrcVT.getScalarSizeInBits() % 8) != 0)
7837       return false;
7838 
7839     bool IsAnyExtend =
7840         (ISD::ANY_EXTEND == Opcode || ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
7841     DecodeZeroExtendMask(SrcVT.getScalarSizeInBits(), NumBitsPerElt, NumElts,
7842                          IsAnyExtend, Mask);
7843     Ops.push_back(Src);
7844     return true;
7845   }
7846   }
7847 
7848   return false;
7849 }
7850 
7851 /// Removes unused/repeated shuffle source inputs and adjusts the shuffle mask.
7852 static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
7853                                               SmallVectorImpl<int> &Mask) {
7854   int MaskWidth = Mask.size();
7855   SmallVector<SDValue, 16> UsedInputs;
7856   for (int i = 0, e = Inputs.size(); i < e; ++i) {
7857     int lo = UsedInputs.size() * MaskWidth;
7858     int hi = lo + MaskWidth;
7859 
7860     // Strip UNDEF input usage.
7861     if (Inputs[i].isUndef())
7862       for (int &M : Mask)
7863         if ((lo <= M) && (M < hi))
7864           M = SM_SentinelUndef;
7865 
7866     // Check for unused inputs.
7867     if (none_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
7868       for (int &M : Mask)
7869         if (lo <= M)
7870           M -= MaskWidth;
7871       continue;
7872     }
7873 
7874     // Check for repeated inputs.
7875     bool IsRepeat = false;
7876     for (int j = 0, ue = UsedInputs.size(); j != ue; ++j) {
7877       if (UsedInputs[j] != Inputs[i])
7878         continue;
7879       for (int &M : Mask)
7880         if (lo <= M)
7881           M = (M < hi) ? ((M - lo) + (j * MaskWidth)) : (M - MaskWidth);
7882       IsRepeat = true;
7883       break;
7884     }
7885     if (IsRepeat)
7886       continue;
7887 
7888     UsedInputs.push_back(Inputs[i]);
7889   }
7890   Inputs = UsedInputs;
7891 }
7892 
7893 /// Calls getTargetShuffleAndZeroables to resolve a target shuffle mask's inputs
7894 /// and then sets the SM_SentinelUndef and SM_SentinelZero values.
7895 /// Returns true if the target shuffle mask was decoded.
7896 static bool getTargetShuffleInputs(SDValue Op, const APInt &DemandedElts,
7897                                    SmallVectorImpl<SDValue> &Inputs,
7898                                    SmallVectorImpl<int> &Mask,
7899                                    APInt &KnownUndef, APInt &KnownZero,
7900                                    const SelectionDAG &DAG, unsigned Depth,
7901                                    bool ResolveKnownElts) {
7902   EVT VT = Op.getValueType();
7903   if (!VT.isSimple() || !VT.isVector())
7904     return false;
7905 
7906   if (getTargetShuffleAndZeroables(Op, Mask, Inputs, KnownUndef, KnownZero)) {
7907     if (ResolveKnownElts)
7908       resolveTargetShuffleFromZeroables(Mask, KnownUndef, KnownZero);
7909     return true;
7910   }
7911   if (getFauxShuffleMask(Op, DemandedElts, Mask, Inputs, DAG, Depth,
7912                          ResolveKnownElts)) {
7913     resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
7914     return true;
7915   }
7916   return false;
7917 }
7918 
7919 static bool getTargetShuffleInputs(SDValue Op, SmallVectorImpl<SDValue> &Inputs,
7920                                    SmallVectorImpl<int> &Mask,
7921                                    const SelectionDAG &DAG, unsigned Depth = 0,
7922                                    bool ResolveKnownElts = true) {
7923   EVT VT = Op.getValueType();
7924   if (!VT.isSimple() || !VT.isVector())
7925     return false;
7926 
7927   APInt KnownUndef, KnownZero;
7928   unsigned NumElts = Op.getValueType().getVectorNumElements();
7929   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
7930   return getTargetShuffleInputs(Op, DemandedElts, Inputs, Mask, KnownUndef,
7931                                 KnownZero, DAG, Depth, ResolveKnownElts);
7932 }
7933 
7934 /// Returns the scalar element that will make up the i'th
7935 /// element of the result of the vector shuffle.
7936 static SDValue getShuffleScalarElt(SDValue Op, unsigned Index,
7937                                    SelectionDAG &DAG, unsigned Depth) {
7938   if (Depth >= SelectionDAG::MaxRecursionDepth)
7939     return SDValue(); // Limit search depth.
7940 
7941   EVT VT = Op.getValueType();
7942   unsigned Opcode = Op.getOpcode();
7943   unsigned NumElems = VT.getVectorNumElements();
7944 
7945   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
7946   if (auto *SV = dyn_cast<ShuffleVectorSDNode>(Op)) {
7947     int Elt = SV->getMaskElt(Index);
7948 
7949     if (Elt < 0)
7950       return DAG.getUNDEF(VT.getVectorElementType());
7951 
7952     SDValue Src = (Elt < (int)NumElems) ? SV->getOperand(0) : SV->getOperand(1);
7953     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7954   }
7955 
7956   // Recurse into target specific vector shuffles to find scalars.
7957   if (isTargetShuffle(Opcode)) {
7958     MVT ShufVT = VT.getSimpleVT();
7959     MVT ShufSVT = ShufVT.getVectorElementType();
7960     int NumElems = (int)ShufVT.getVectorNumElements();
7961     SmallVector<int, 16> ShuffleMask;
7962     SmallVector<SDValue, 16> ShuffleOps;
7963     bool IsUnary;
7964 
7965     if (!getTargetShuffleMask(Op.getNode(), ShufVT, true, ShuffleOps,
7966                               ShuffleMask, IsUnary))
7967       return SDValue();
7968 
7969     int Elt = ShuffleMask[Index];
7970     if (Elt == SM_SentinelZero)
7971       return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(Op), ShufSVT)
7972                                  : DAG.getConstantFP(+0.0, SDLoc(Op), ShufSVT);
7973     if (Elt == SM_SentinelUndef)
7974       return DAG.getUNDEF(ShufSVT);
7975 
7976     assert(0 <= Elt && Elt < (2 * NumElems) && "Shuffle index out of range");
7977     SDValue Src = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
7978     return getShuffleScalarElt(Src, Elt % NumElems, DAG, Depth + 1);
7979   }
7980 
7981   // Recurse into insert_subvector base/sub vector to find scalars.
7982   if (Opcode == ISD::INSERT_SUBVECTOR) {
7983     SDValue Vec = Op.getOperand(0);
7984     SDValue Sub = Op.getOperand(1);
7985     uint64_t SubIdx = Op.getConstantOperandVal(2);
7986     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
7987 
7988     if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
7989       return getShuffleScalarElt(Sub, Index - SubIdx, DAG, Depth + 1);
7990     return getShuffleScalarElt(Vec, Index, DAG, Depth + 1);
7991   }
7992 
7993   // Recurse into concat_vectors sub vector to find scalars.
7994   if (Opcode == ISD::CONCAT_VECTORS) {
7995     EVT SubVT = Op.getOperand(0).getValueType();
7996     unsigned NumSubElts = SubVT.getVectorNumElements();
7997     uint64_t SubIdx = Index / NumSubElts;
7998     uint64_t SubElt = Index % NumSubElts;
7999     return getShuffleScalarElt(Op.getOperand(SubIdx), SubElt, DAG, Depth + 1);
8000   }
8001 
8002   // Recurse into extract_subvector src vector to find scalars.
8003   if (Opcode == ISD::EXTRACT_SUBVECTOR) {
8004     SDValue Src = Op.getOperand(0);
8005     uint64_t SrcIdx = Op.getConstantOperandVal(1);
8006     return getShuffleScalarElt(Src, Index + SrcIdx, DAG, Depth + 1);
8007   }
8008 
8009   // We only peek through bitcasts of the same vector width.
8010   if (Opcode == ISD::BITCAST) {
8011     SDValue Src = Op.getOperand(0);
8012     EVT SrcVT = Src.getValueType();
8013     if (SrcVT.isVector() && SrcVT.getVectorNumElements() == NumElems)
8014       return getShuffleScalarElt(Src, Index, DAG, Depth + 1);
8015     return SDValue();
8016   }
8017 
8018   // Actual nodes that may contain scalar elements
8019 
8020   // For insert_vector_elt - either return the index matching scalar or recurse
8021   // into the base vector.
8022   if (Opcode == ISD::INSERT_VECTOR_ELT &&
8023       isa<ConstantSDNode>(Op.getOperand(2))) {
8024     if (Op.getConstantOperandAPInt(2) == Index)
8025       return Op.getOperand(1);
8026     return getShuffleScalarElt(Op.getOperand(0), Index, DAG, Depth + 1);
8027   }
8028 
8029   if (Opcode == ISD::SCALAR_TO_VECTOR)
8030     return (Index == 0) ? Op.getOperand(0)
8031                         : DAG.getUNDEF(VT.getVectorElementType());
8032 
8033   if (Opcode == ISD::BUILD_VECTOR)
8034     return Op.getOperand(Index);
8035 
8036   return SDValue();
8037 }
8038 
8039 // Use PINSRB/PINSRW/PINSRD to create a build vector.
8040 static SDValue LowerBuildVectorAsInsert(SDValue Op, const APInt &NonZeroMask,
8041                                         unsigned NumNonZero, unsigned NumZero,
8042                                         SelectionDAG &DAG,
8043                                         const X86Subtarget &Subtarget) {
8044   MVT VT = Op.getSimpleValueType();
8045   unsigned NumElts = VT.getVectorNumElements();
8046   assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||
8047           ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&
8048          "Illegal vector insertion");
8049 
8050   SDLoc dl(Op);
8051   SDValue V;
8052   bool First = true;
8053 
8054   for (unsigned i = 0; i < NumElts; ++i) {
8055     bool IsNonZero = NonZeroMask[i];
8056     if (!IsNonZero)
8057       continue;
8058 
8059     // If the build vector contains zeros or our first insertion is not the
8060     // first index then insert into zero vector to break any register
8061     // dependency else use SCALAR_TO_VECTOR.
8062     if (First) {
8063       First = false;
8064       if (NumZero || 0 != i)
8065         V = getZeroVector(VT, Subtarget, DAG, dl);
8066       else {
8067         assert(0 == i && "Expected insertion into zero-index");
8068         V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8069         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
8070         V = DAG.getBitcast(VT, V);
8071         continue;
8072       }
8073     }
8074     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
8075                     DAG.getIntPtrConstant(i, dl));
8076   }
8077 
8078   return V;
8079 }
8080 
8081 /// Custom lower build_vector of v16i8.
8082 static SDValue LowerBuildVectorv16i8(SDValue Op, const APInt &NonZeroMask,
8083                                      unsigned NumNonZero, unsigned NumZero,
8084                                      SelectionDAG &DAG,
8085                                      const X86Subtarget &Subtarget) {
8086   if (NumNonZero > 8 && !Subtarget.hasSSE41())
8087     return SDValue();
8088 
8089   // SSE4.1 - use PINSRB to insert each byte directly.
8090   if (Subtarget.hasSSE41())
8091     return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8092                                     Subtarget);
8093 
8094   SDLoc dl(Op);
8095   SDValue V;
8096 
8097   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
8098   for (unsigned i = 0; i < 16; i += 2) {
8099     bool ThisIsNonZero = NonZeroMask[i];
8100     bool NextIsNonZero = NonZeroMask[i + 1];
8101     if (!ThisIsNonZero && !NextIsNonZero)
8102       continue;
8103 
8104     // FIXME: Investigate combining the first 4 bytes as a i32 instead.
8105     SDValue Elt;
8106     if (ThisIsNonZero) {
8107       if (NumZero || NextIsNonZero)
8108         Elt = DAG.getZExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8109       else
8110         Elt = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
8111     }
8112 
8113     if (NextIsNonZero) {
8114       SDValue NextElt = Op.getOperand(i + 1);
8115       if (i == 0 && NumZero)
8116         NextElt = DAG.getZExtOrTrunc(NextElt, dl, MVT::i32);
8117       else
8118         NextElt = DAG.getAnyExtOrTrunc(NextElt, dl, MVT::i32);
8119       NextElt = DAG.getNode(ISD::SHL, dl, MVT::i32, NextElt,
8120                             DAG.getConstant(8, dl, MVT::i8));
8121       if (ThisIsNonZero)
8122         Elt = DAG.getNode(ISD::OR, dl, MVT::i32, NextElt, Elt);
8123       else
8124         Elt = NextElt;
8125     }
8126 
8127     // If our first insertion is not the first index or zeros are needed, then
8128     // insert into zero vector. Otherwise, use SCALAR_TO_VECTOR (leaves high
8129     // elements undefined).
8130     if (!V) {
8131       if (i != 0 || NumZero)
8132         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
8133       else {
8134         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Elt);
8135         V = DAG.getBitcast(MVT::v8i16, V);
8136         continue;
8137       }
8138     }
8139     Elt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Elt);
8140     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, Elt,
8141                     DAG.getIntPtrConstant(i / 2, dl));
8142   }
8143 
8144   return DAG.getBitcast(MVT::v16i8, V);
8145 }
8146 
8147 /// Custom lower build_vector of v8i16.
8148 static SDValue LowerBuildVectorv8i16(SDValue Op, const APInt &NonZeroMask,
8149                                      unsigned NumNonZero, unsigned NumZero,
8150                                      SelectionDAG &DAG,
8151                                      const X86Subtarget &Subtarget) {
8152   if (NumNonZero > 4 && !Subtarget.hasSSE41())
8153     return SDValue();
8154 
8155   // Use PINSRW to insert each byte directly.
8156   return LowerBuildVectorAsInsert(Op, NonZeroMask, NumNonZero, NumZero, DAG,
8157                                   Subtarget);
8158 }
8159 
8160 /// Custom lower build_vector of v4i32 or v4f32.
8161 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
8162                                      const X86Subtarget &Subtarget) {
8163   // If this is a splat of a pair of elements, use MOVDDUP (unless the target
8164   // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
8165   // Because we're creating a less complicated build vector here, we may enable
8166   // further folding of the MOVDDUP via shuffle transforms.
8167   if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
8168       Op.getOperand(0) == Op.getOperand(2) &&
8169       Op.getOperand(1) == Op.getOperand(3) &&
8170       Op.getOperand(0) != Op.getOperand(1)) {
8171     SDLoc DL(Op);
8172     MVT VT = Op.getSimpleValueType();
8173     MVT EltVT = VT.getVectorElementType();
8174     // Create a new build vector with the first 2 elements followed by undef
8175     // padding, bitcast to v2f64, duplicate, and bitcast back.
8176     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
8177                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
8178     SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
8179     SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
8180     return DAG.getBitcast(VT, Dup);
8181   }
8182 
8183   // Find all zeroable elements.
8184   std::bitset<4> Zeroable, Undefs;
8185   for (int i = 0; i < 4; ++i) {
8186     SDValue Elt = Op.getOperand(i);
8187     Undefs[i] = Elt.isUndef();
8188     Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
8189   }
8190   assert(Zeroable.size() - Zeroable.count() > 1 &&
8191          "We expect at least two non-zero elements!");
8192 
8193   // We only know how to deal with build_vector nodes where elements are either
8194   // zeroable or extract_vector_elt with constant index.
8195   SDValue FirstNonZero;
8196   unsigned FirstNonZeroIdx;
8197   for (unsigned i = 0; i < 4; ++i) {
8198     if (Zeroable[i])
8199       continue;
8200     SDValue Elt = Op.getOperand(i);
8201     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8202         !isa<ConstantSDNode>(Elt.getOperand(1)))
8203       return SDValue();
8204     // Make sure that this node is extracting from a 128-bit vector.
8205     MVT VT = Elt.getOperand(0).getSimpleValueType();
8206     if (!VT.is128BitVector())
8207       return SDValue();
8208     if (!FirstNonZero.getNode()) {
8209       FirstNonZero = Elt;
8210       FirstNonZeroIdx = i;
8211     }
8212   }
8213 
8214   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
8215   SDValue V1 = FirstNonZero.getOperand(0);
8216   MVT VT = V1.getSimpleValueType();
8217 
8218   // See if this build_vector can be lowered as a blend with zero.
8219   SDValue Elt;
8220   unsigned EltMaskIdx, EltIdx;
8221   int Mask[4];
8222   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
8223     if (Zeroable[EltIdx]) {
8224       // The zero vector will be on the right hand side.
8225       Mask[EltIdx] = EltIdx+4;
8226       continue;
8227     }
8228 
8229     Elt = Op->getOperand(EltIdx);
8230     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
8231     EltMaskIdx = Elt.getConstantOperandVal(1);
8232     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
8233       break;
8234     Mask[EltIdx] = EltIdx;
8235   }
8236 
8237   if (EltIdx == 4) {
8238     // Let the shuffle legalizer deal with blend operations.
8239     SDValue VZeroOrUndef = (Zeroable == Undefs)
8240                                ? DAG.getUNDEF(VT)
8241                                : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
8242     if (V1.getSimpleValueType() != VT)
8243       V1 = DAG.getBitcast(VT, V1);
8244     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
8245   }
8246 
8247   // See if we can lower this build_vector to a INSERTPS.
8248   if (!Subtarget.hasSSE41())
8249     return SDValue();
8250 
8251   SDValue V2 = Elt.getOperand(0);
8252   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
8253     V1 = SDValue();
8254 
8255   bool CanFold = true;
8256   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
8257     if (Zeroable[i])
8258       continue;
8259 
8260     SDValue Current = Op->getOperand(i);
8261     SDValue SrcVector = Current->getOperand(0);
8262     if (!V1.getNode())
8263       V1 = SrcVector;
8264     CanFold = (SrcVector == V1) && (Current.getConstantOperandAPInt(1) == i);
8265   }
8266 
8267   if (!CanFold)
8268     return SDValue();
8269 
8270   assert(V1.getNode() && "Expected at least two non-zero elements!");
8271   if (V1.getSimpleValueType() != MVT::v4f32)
8272     V1 = DAG.getBitcast(MVT::v4f32, V1);
8273   if (V2.getSimpleValueType() != MVT::v4f32)
8274     V2 = DAG.getBitcast(MVT::v4f32, V2);
8275 
8276   // Ok, we can emit an INSERTPS instruction.
8277   unsigned ZMask = Zeroable.to_ulong();
8278 
8279   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
8280   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8281   SDLoc DL(Op);
8282   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8283                                DAG.getIntPtrConstant(InsertPSMask, DL, true));
8284   return DAG.getBitcast(VT, Result);
8285 }
8286 
8287 /// Return a vector logical shift node.
8288 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
8289                          SelectionDAG &DAG, const TargetLowering &TLI,
8290                          const SDLoc &dl) {
8291   assert(VT.is128BitVector() && "Unknown type for VShift");
8292   MVT ShVT = MVT::v16i8;
8293   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
8294   SrcOp = DAG.getBitcast(ShVT, SrcOp);
8295   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
8296   SDValue ShiftVal = DAG.getTargetConstant(NumBits / 8, dl, MVT::i8);
8297   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
8298 }
8299 
8300 static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
8301                                       SelectionDAG &DAG) {
8302 
8303   // Check if the scalar load can be widened into a vector load. And if
8304   // the address is "base + cst" see if the cst can be "absorbed" into
8305   // the shuffle mask.
8306   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
8307     SDValue Ptr = LD->getBasePtr();
8308     if (!ISD::isNormalLoad(LD) || !LD->isSimple())
8309       return SDValue();
8310     EVT PVT = LD->getValueType(0);
8311     if (PVT != MVT::i32 && PVT != MVT::f32)
8312       return SDValue();
8313 
8314     int FI = -1;
8315     int64_t Offset = 0;
8316     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
8317       FI = FINode->getIndex();
8318       Offset = 0;
8319     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
8320                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
8321       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8322       Offset = Ptr.getConstantOperandVal(1);
8323       Ptr = Ptr.getOperand(0);
8324     } else {
8325       return SDValue();
8326     }
8327 
8328     // FIXME: 256-bit vector instructions don't require a strict alignment,
8329     // improve this code to support it better.
8330     Align RequiredAlign(VT.getSizeInBits() / 8);
8331     SDValue Chain = LD->getChain();
8332     // Make sure the stack object alignment is at least 16 or 32.
8333     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8334     MaybeAlign InferredAlign = DAG.InferPtrAlign(Ptr);
8335     if (!InferredAlign || *InferredAlign < RequiredAlign) {
8336       if (MFI.isFixedObjectIndex(FI)) {
8337         // Can't change the alignment. FIXME: It's possible to compute
8338         // the exact stack offset and reference FI + adjust offset instead.
8339         // If someone *really* cares about this. That's the way to implement it.
8340         return SDValue();
8341       } else {
8342         MFI.setObjectAlignment(FI, RequiredAlign);
8343       }
8344     }
8345 
8346     // (Offset % 16 or 32) must be multiple of 4. Then address is then
8347     // Ptr + (Offset & ~15).
8348     if (Offset < 0)
8349       return SDValue();
8350     if ((Offset % RequiredAlign.value()) & 3)
8351       return SDValue();
8352     int64_t StartOffset = Offset & ~int64_t(RequiredAlign.value() - 1);
8353     if (StartOffset) {
8354       SDLoc DL(Ptr);
8355       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
8356                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
8357     }
8358 
8359     int EltNo = (Offset - StartOffset) >> 2;
8360     unsigned NumElems = VT.getVectorNumElements();
8361 
8362     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
8363     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
8364                              LD->getPointerInfo().getWithOffset(StartOffset));
8365 
8366     SmallVector<int, 8> Mask(NumElems, EltNo);
8367 
8368     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
8369   }
8370 
8371   return SDValue();
8372 }
8373 
8374 // Recurse to find a LoadSDNode source and the accumulated ByteOffest.
8375 static bool findEltLoadSrc(SDValue Elt, LoadSDNode *&Ld, int64_t &ByteOffset) {
8376   if (ISD::isNON_EXTLoad(Elt.getNode())) {
8377     auto *BaseLd = cast<LoadSDNode>(Elt);
8378     if (!BaseLd->isSimple())
8379       return false;
8380     Ld = BaseLd;
8381     ByteOffset = 0;
8382     return true;
8383   }
8384 
8385   switch (Elt.getOpcode()) {
8386   case ISD::BITCAST:
8387   case ISD::TRUNCATE:
8388   case ISD::SCALAR_TO_VECTOR:
8389     return findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset);
8390   case ISD::SRL:
8391     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8392       uint64_t Idx = IdxC->getZExtValue();
8393       if ((Idx % 8) == 0 && findEltLoadSrc(Elt.getOperand(0), Ld, ByteOffset)) {
8394         ByteOffset += Idx / 8;
8395         return true;
8396       }
8397     }
8398     break;
8399   case ISD::EXTRACT_VECTOR_ELT:
8400     if (auto *IdxC = dyn_cast<ConstantSDNode>(Elt.getOperand(1))) {
8401       SDValue Src = Elt.getOperand(0);
8402       unsigned SrcSizeInBits = Src.getScalarValueSizeInBits();
8403       unsigned DstSizeInBits = Elt.getScalarValueSizeInBits();
8404       if (DstSizeInBits == SrcSizeInBits && (SrcSizeInBits % 8) == 0 &&
8405           findEltLoadSrc(Src, Ld, ByteOffset)) {
8406         uint64_t Idx = IdxC->getZExtValue();
8407         ByteOffset += Idx * (SrcSizeInBits / 8);
8408         return true;
8409       }
8410     }
8411     break;
8412   }
8413 
8414   return false;
8415 }
8416 
8417 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
8418 /// elements can be replaced by a single large load which has the same value as
8419 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
8420 ///
8421 /// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
8422 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
8423                                         const SDLoc &DL, SelectionDAG &DAG,
8424                                         const X86Subtarget &Subtarget,
8425                                         bool isAfterLegalize) {
8426   if ((VT.getScalarSizeInBits() % 8) != 0)
8427     return SDValue();
8428 
8429   unsigned NumElems = Elts.size();
8430 
8431   int LastLoadedElt = -1;
8432   APInt LoadMask = APInt::getNullValue(NumElems);
8433   APInt ZeroMask = APInt::getNullValue(NumElems);
8434   APInt UndefMask = APInt::getNullValue(NumElems);
8435 
8436   SmallVector<LoadSDNode*, 8> Loads(NumElems, nullptr);
8437   SmallVector<int64_t, 8> ByteOffsets(NumElems, 0);
8438 
8439   // For each element in the initializer, see if we've found a load, zero or an
8440   // undef.
8441   for (unsigned i = 0; i < NumElems; ++i) {
8442     SDValue Elt = peekThroughBitcasts(Elts[i]);
8443     if (!Elt.getNode())
8444       return SDValue();
8445     if (Elt.isUndef()) {
8446       UndefMask.setBit(i);
8447       continue;
8448     }
8449     if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode())) {
8450       ZeroMask.setBit(i);
8451       continue;
8452     }
8453 
8454     // Each loaded element must be the correct fractional portion of the
8455     // requested vector load.
8456     unsigned EltSizeInBits = Elt.getValueSizeInBits();
8457     if ((NumElems * EltSizeInBits) != VT.getSizeInBits())
8458       return SDValue();
8459 
8460     if (!findEltLoadSrc(Elt, Loads[i], ByteOffsets[i]) || ByteOffsets[i] < 0)
8461       return SDValue();
8462     unsigned LoadSizeInBits = Loads[i]->getValueSizeInBits(0);
8463     if (((ByteOffsets[i] * 8) + EltSizeInBits) > LoadSizeInBits)
8464       return SDValue();
8465 
8466     LoadMask.setBit(i);
8467     LastLoadedElt = i;
8468   }
8469   assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +
8470           LoadMask.countPopulation()) == NumElems &&
8471          "Incomplete element masks");
8472 
8473   // Handle Special Cases - all undef or undef/zero.
8474   if (UndefMask.countPopulation() == NumElems)
8475     return DAG.getUNDEF(VT);
8476   if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
8477     return VT.isInteger() ? DAG.getConstant(0, DL, VT)
8478                           : DAG.getConstantFP(0.0, DL, VT);
8479 
8480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8481   int FirstLoadedElt = LoadMask.countTrailingZeros();
8482   SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
8483   EVT EltBaseVT = EltBase.getValueType();
8484   assert(EltBaseVT.getSizeInBits() == EltBaseVT.getStoreSizeInBits() &&
8485          "Register/Memory size mismatch");
8486   LoadSDNode *LDBase = Loads[FirstLoadedElt];
8487   assert(LDBase && "Did not find base load for merging consecutive loads");
8488   unsigned BaseSizeInBits = EltBaseVT.getStoreSizeInBits();
8489   unsigned BaseSizeInBytes = BaseSizeInBits / 8;
8490   int NumLoadedElts = (1 + LastLoadedElt - FirstLoadedElt);
8491   int LoadSizeInBits = NumLoadedElts * BaseSizeInBits;
8492   assert((BaseSizeInBits % 8) == 0 && "Sub-byte element loads detected");
8493 
8494   // TODO: Support offsetting the base load.
8495   if (ByteOffsets[FirstLoadedElt] != 0)
8496     return SDValue();
8497 
8498   // Check to see if the element's load is consecutive to the base load
8499   // or offset from a previous (already checked) load.
8500   auto CheckConsecutiveLoad = [&](LoadSDNode *Base, int EltIdx) {
8501     LoadSDNode *Ld = Loads[EltIdx];
8502     int64_t ByteOffset = ByteOffsets[EltIdx];
8503     if (ByteOffset && (ByteOffset % BaseSizeInBytes) == 0) {
8504       int64_t BaseIdx = EltIdx - (ByteOffset / BaseSizeInBytes);
8505       return (0 <= BaseIdx && BaseIdx < (int)NumElems && LoadMask[BaseIdx] &&
8506               Loads[BaseIdx] == Ld && ByteOffsets[BaseIdx] == 0);
8507     }
8508     return DAG.areNonVolatileConsecutiveLoads(Ld, Base, BaseSizeInBytes,
8509                                               EltIdx - FirstLoadedElt);
8510   };
8511 
8512   // Consecutive loads can contain UNDEFS but not ZERO elements.
8513   // Consecutive loads with UNDEFs and ZEROs elements require a
8514   // an additional shuffle stage to clear the ZERO elements.
8515   bool IsConsecutiveLoad = true;
8516   bool IsConsecutiveLoadWithZeros = true;
8517   for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
8518     if (LoadMask[i]) {
8519       if (!CheckConsecutiveLoad(LDBase, i)) {
8520         IsConsecutiveLoad = false;
8521         IsConsecutiveLoadWithZeros = false;
8522         break;
8523       }
8524     } else if (ZeroMask[i]) {
8525       IsConsecutiveLoad = false;
8526     }
8527   }
8528 
8529   auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
8530     auto MMOFlags = LDBase->getMemOperand()->getFlags();
8531     assert(LDBase->isSimple() &&
8532            "Cannot merge volatile or atomic loads.");
8533     SDValue NewLd =
8534         DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
8535                     LDBase->getPointerInfo(), LDBase->getOriginalAlign(),
8536                     MMOFlags);
8537     for (auto *LD : Loads)
8538       if (LD)
8539         DAG.makeEquivalentMemoryOrdering(LD, NewLd);
8540     return NewLd;
8541   };
8542 
8543   // Check if the base load is entirely dereferenceable.
8544   bool IsDereferenceable = LDBase->getPointerInfo().isDereferenceable(
8545       VT.getSizeInBits() / 8, *DAG.getContext(), DAG.getDataLayout());
8546 
8547   // LOAD - all consecutive load/undefs (must start/end with a load or be
8548   // entirely dereferenceable). If we have found an entire vector of loads and
8549   // undefs, then return a large load of the entire vector width starting at the
8550   // base pointer. If the vector contains zeros, then attempt to shuffle those
8551   // elements.
8552   if (FirstLoadedElt == 0 &&
8553       (NumLoadedElts == (int)NumElems || IsDereferenceable) &&
8554       (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
8555     if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
8556       return SDValue();
8557 
8558     // Don't create 256-bit non-temporal aligned loads without AVX2 as these
8559     // will lower to regular temporal loads and use the cache.
8560     if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
8561         VT.is256BitVector() && !Subtarget.hasInt256())
8562       return SDValue();
8563 
8564     if (NumElems == 1)
8565       return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
8566 
8567     if (!ZeroMask)
8568       return CreateLoad(VT, LDBase);
8569 
8570     // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
8571     // vector and a zero vector to clear out the zero elements.
8572     if (!isAfterLegalize && VT.isVector()) {
8573       unsigned NumMaskElts = VT.getVectorNumElements();
8574       if ((NumMaskElts % NumElems) == 0) {
8575         unsigned Scale = NumMaskElts / NumElems;
8576         SmallVector<int, 4> ClearMask(NumMaskElts, -1);
8577         for (unsigned i = 0; i < NumElems; ++i) {
8578           if (UndefMask[i])
8579             continue;
8580           int Offset = ZeroMask[i] ? NumMaskElts : 0;
8581           for (unsigned j = 0; j != Scale; ++j)
8582             ClearMask[(i * Scale) + j] = (i * Scale) + j + Offset;
8583         }
8584         SDValue V = CreateLoad(VT, LDBase);
8585         SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
8586                                    : DAG.getConstantFP(0.0, DL, VT);
8587         return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
8588       }
8589     }
8590   }
8591 
8592   // If the upper half of a ymm/zmm load is undef then just load the lower half.
8593   if (VT.is256BitVector() || VT.is512BitVector()) {
8594     unsigned HalfNumElems = NumElems / 2;
8595     if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnesValue()) {
8596       EVT HalfVT =
8597           EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
8598       SDValue HalfLD =
8599           EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
8600                                    DAG, Subtarget, isAfterLegalize);
8601       if (HalfLD)
8602         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
8603                            HalfLD, DAG.getIntPtrConstant(0, DL));
8604     }
8605   }
8606 
8607   // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
8608   if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
8609       (LoadSizeInBits == 32 || LoadSizeInBits == 64) &&
8610       ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
8611     MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSizeInBits)
8612                                       : MVT::getIntegerVT(LoadSizeInBits);
8613     MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSizeInBits);
8614     // Allow v4f32 on SSE1 only targets.
8615     // FIXME: Add more isel patterns so we can just use VT directly.
8616     if (!Subtarget.hasSSE2() && VT == MVT::v4f32)
8617       VecVT = MVT::v4f32;
8618     if (TLI.isTypeLegal(VecVT)) {
8619       SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
8620       SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
8621       SDValue ResNode = DAG.getMemIntrinsicNode(
8622           X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT, LDBase->getPointerInfo(),
8623           LDBase->getOriginalAlign(), MachineMemOperand::MOLoad);
8624       for (auto *LD : Loads)
8625         if (LD)
8626           DAG.makeEquivalentMemoryOrdering(LD, ResNode);
8627       return DAG.getBitcast(VT, ResNode);
8628     }
8629   }
8630 
8631   // BROADCAST - match the smallest possible repetition pattern, load that
8632   // scalar/subvector element and then broadcast to the entire vector.
8633   if (ZeroMask.isNullValue() && isPowerOf2_32(NumElems) && Subtarget.hasAVX() &&
8634       (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
8635     for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
8636       unsigned RepeatSize = SubElems * BaseSizeInBits;
8637       unsigned ScalarSize = std::min(RepeatSize, 64u);
8638       if (!Subtarget.hasAVX2() && ScalarSize < 32)
8639         continue;
8640 
8641       // Don't attempt a 1:N subvector broadcast - it should be caught by
8642       // combineConcatVectorOps, else will cause infinite loops.
8643       if (RepeatSize > ScalarSize && SubElems == 1)
8644         continue;
8645 
8646       bool Match = true;
8647       SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(EltBaseVT));
8648       for (unsigned i = 0; i != NumElems && Match; ++i) {
8649         if (!LoadMask[i])
8650           continue;
8651         SDValue Elt = peekThroughBitcasts(Elts[i]);
8652         if (RepeatedLoads[i % SubElems].isUndef())
8653           RepeatedLoads[i % SubElems] = Elt;
8654         else
8655           Match &= (RepeatedLoads[i % SubElems] == Elt);
8656       }
8657 
8658       // We must have loads at both ends of the repetition.
8659       Match &= !RepeatedLoads.front().isUndef();
8660       Match &= !RepeatedLoads.back().isUndef();
8661       if (!Match)
8662         continue;
8663 
8664       EVT RepeatVT =
8665           VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
8666               ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
8667               : EVT::getFloatingPointVT(ScalarSize);
8668       if (RepeatSize > ScalarSize)
8669         RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
8670                                     RepeatSize / ScalarSize);
8671       EVT BroadcastVT =
8672           EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
8673                            VT.getSizeInBits() / ScalarSize);
8674       if (TLI.isTypeLegal(BroadcastVT)) {
8675         if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
8676                 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, isAfterLegalize)) {
8677           SDValue Broadcast = RepeatLoad;
8678           if (RepeatSize > ScalarSize) {
8679             while (Broadcast.getValueSizeInBits() < VT.getSizeInBits())
8680               Broadcast = concatSubVectors(Broadcast, Broadcast, DAG, DL);
8681           } else {
8682             Broadcast =
8683                 DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, RepeatLoad);
8684           }
8685           return DAG.getBitcast(VT, Broadcast);
8686         }
8687       }
8688     }
8689   }
8690 
8691   return SDValue();
8692 }
8693 
8694 // Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
8695 // load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
8696 // are consecutive, non-overlapping, and in the right order.
8697 static SDValue combineToConsecutiveLoads(EVT VT, SDValue Op, const SDLoc &DL,
8698                                          SelectionDAG &DAG,
8699                                          const X86Subtarget &Subtarget,
8700                                          bool isAfterLegalize) {
8701   SmallVector<SDValue, 64> Elts;
8702   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8703     if (SDValue Elt = getShuffleScalarElt(Op, i, DAG, 0)) {
8704       Elts.push_back(Elt);
8705       continue;
8706     }
8707     return SDValue();
8708   }
8709   assert(Elts.size() == VT.getVectorNumElements());
8710   return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
8711                                   isAfterLegalize);
8712 }
8713 
8714 static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
8715                                    unsigned SplatBitSize, LLVMContext &C) {
8716   unsigned ScalarSize = VT.getScalarSizeInBits();
8717   unsigned NumElm = SplatBitSize / ScalarSize;
8718 
8719   SmallVector<Constant *, 32> ConstantVec;
8720   for (unsigned i = 0; i < NumElm; i++) {
8721     APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
8722     Constant *Const;
8723     if (VT.isFloatingPoint()) {
8724       if (ScalarSize == 32) {
8725         Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
8726       } else {
8727         assert(ScalarSize == 64 && "Unsupported floating point scalar size");
8728         Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
8729       }
8730     } else
8731       Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
8732     ConstantVec.push_back(Const);
8733   }
8734   return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
8735 }
8736 
8737 static bool isFoldableUseOfShuffle(SDNode *N) {
8738   for (auto *U : N->uses()) {
8739     unsigned Opc = U->getOpcode();
8740     // VPERMV/VPERMV3 shuffles can never fold their index operands.
8741     if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
8742       return false;
8743     if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
8744       return false;
8745     if (isTargetShuffle(Opc))
8746       return true;
8747     if (Opc == ISD::BITCAST) // Ignore bitcasts
8748       return isFoldableUseOfShuffle(U);
8749     if (N->hasOneUse())
8750       return true;
8751   }
8752   return false;
8753 }
8754 
8755 /// Attempt to use the vbroadcast instruction to generate a splat value
8756 /// from a splat BUILD_VECTOR which uses:
8757 ///  a. A single scalar load, or a constant.
8758 ///  b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
8759 ///
8760 /// The VBROADCAST node is returned when a pattern is found,
8761 /// or SDValue() otherwise.
8762 static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
8763                                            const X86Subtarget &Subtarget,
8764                                            SelectionDAG &DAG) {
8765   // VBROADCAST requires AVX.
8766   // TODO: Splats could be generated for non-AVX CPUs using SSE
8767   // instructions, but there's less potential gain for only 128-bit vectors.
8768   if (!Subtarget.hasAVX())
8769     return SDValue();
8770 
8771   MVT VT = BVOp->getSimpleValueType(0);
8772   unsigned NumElts = VT.getVectorNumElements();
8773   SDLoc dl(BVOp);
8774 
8775   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
8776          "Unsupported vector type for broadcast.");
8777 
8778   // See if the build vector is a repeating sequence of scalars (inc. splat).
8779   SDValue Ld;
8780   BitVector UndefElements;
8781   SmallVector<SDValue, 16> Sequence;
8782   if (BVOp->getRepeatedSequence(Sequence, &UndefElements)) {
8783     assert((NumElts % Sequence.size()) == 0 && "Sequence doesn't fit.");
8784     if (Sequence.size() == 1)
8785       Ld = Sequence[0];
8786   }
8787 
8788   // Attempt to use VBROADCASTM
8789   // From this pattern:
8790   // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
8791   // b. t1 = (build_vector t0 t0)
8792   //
8793   // Create (VBROADCASTM v2i1 X)
8794   if (!Sequence.empty() && Subtarget.hasCDI()) {
8795     // If not a splat, are the upper sequence values zeroable?
8796     unsigned SeqLen = Sequence.size();
8797     bool UpperZeroOrUndef =
8798         SeqLen == 1 ||
8799         llvm::all_of(makeArrayRef(Sequence).drop_front(), [](SDValue V) {
8800           return !V || V.isUndef() || isNullConstant(V);
8801         });
8802     SDValue Op0 = Sequence[0];
8803     if (UpperZeroOrUndef && ((Op0.getOpcode() == ISD::BITCAST) ||
8804                              (Op0.getOpcode() == ISD::ZERO_EXTEND &&
8805                               Op0.getOperand(0).getOpcode() == ISD::BITCAST))) {
8806       SDValue BOperand = Op0.getOpcode() == ISD::BITCAST
8807                              ? Op0.getOperand(0)
8808                              : Op0.getOperand(0).getOperand(0);
8809       MVT MaskVT = BOperand.getSimpleValueType();
8810       MVT EltType = MVT::getIntegerVT(VT.getScalarSizeInBits() * SeqLen);
8811       if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) ||  // for broadcastmb2q
8812           (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
8813         MVT BcstVT = MVT::getVectorVT(EltType, NumElts / SeqLen);
8814         if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
8815           unsigned Scale = 512 / VT.getSizeInBits();
8816           BcstVT = MVT::getVectorVT(EltType, Scale * (NumElts / SeqLen));
8817         }
8818         SDValue Bcst = DAG.getNode(X86ISD::VBROADCASTM, dl, BcstVT, BOperand);
8819         if (BcstVT.getSizeInBits() != VT.getSizeInBits())
8820           Bcst = extractSubVector(Bcst, 0, DAG, dl, VT.getSizeInBits());
8821         return DAG.getBitcast(VT, Bcst);
8822       }
8823     }
8824   }
8825 
8826   unsigned NumUndefElts = UndefElements.count();
8827   if (!Ld || (NumElts - NumUndefElts) <= 1) {
8828     APInt SplatValue, Undef;
8829     unsigned SplatBitSize;
8830     bool HasUndef;
8831     // Check if this is a repeated constant pattern suitable for broadcasting.
8832     if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
8833         SplatBitSize > VT.getScalarSizeInBits() &&
8834         SplatBitSize < VT.getSizeInBits()) {
8835       // Avoid replacing with broadcast when it's a use of a shuffle
8836       // instruction to preserve the present custom lowering of shuffles.
8837       if (isFoldableUseOfShuffle(BVOp))
8838         return SDValue();
8839       // replace BUILD_VECTOR with broadcast of the repeated constants.
8840       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8841       LLVMContext *Ctx = DAG.getContext();
8842       MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
8843       if (Subtarget.hasAVX()) {
8844         if (SplatBitSize == 32 || SplatBitSize == 64 ||
8845             (SplatBitSize < 32 && Subtarget.hasAVX2())) {
8846           // Splatted value can fit in one INTEGER constant in constant pool.
8847           // Load the constant and broadcast it.
8848           MVT CVT = MVT::getIntegerVT(SplatBitSize);
8849           Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
8850           Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
8851           SDValue CP = DAG.getConstantPool(C, PVT);
8852           unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
8853 
8854           Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8855           SDVTList Tys =
8856               DAG.getVTList(MVT::getVectorVT(CVT, Repeat), MVT::Other);
8857           SDValue Ops[] = {DAG.getEntryNode(), CP};
8858           MachinePointerInfo MPI =
8859               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8860           SDValue Brdcst = DAG.getMemIntrinsicNode(
8861               X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT, MPI, Alignment,
8862               MachineMemOperand::MOLoad);
8863           return DAG.getBitcast(VT, Brdcst);
8864         }
8865         if (SplatBitSize > 64) {
8866           // Load the vector of constants and broadcast it.
8867           Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
8868                                              *Ctx);
8869           SDValue VCP = DAG.getConstantPool(VecC, PVT);
8870           unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
8871           MVT VVT = MVT::getVectorVT(VT.getScalarType(), NumElm);
8872           Align Alignment = cast<ConstantPoolSDNode>(VCP)->getAlign();
8873           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8874           SDValue Ops[] = {DAG.getEntryNode(), VCP};
8875           MachinePointerInfo MPI =
8876               MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8877           return DAG.getMemIntrinsicNode(
8878               X86ISD::SUBV_BROADCAST_LOAD, dl, Tys, Ops, VVT, MPI, Alignment,
8879               MachineMemOperand::MOLoad);
8880         }
8881       }
8882     }
8883 
8884     // If we are moving a scalar into a vector (Ld must be set and all elements
8885     // but 1 are undef) and that operation is not obviously supported by
8886     // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
8887     // That's better than general shuffling and may eliminate a load to GPR and
8888     // move from scalar to vector register.
8889     if (!Ld || NumElts - NumUndefElts != 1)
8890       return SDValue();
8891     unsigned ScalarSize = Ld.getValueSizeInBits();
8892     if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
8893       return SDValue();
8894   }
8895 
8896   bool ConstSplatVal =
8897       (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
8898   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
8899 
8900   // TODO: Handle broadcasts of non-constant sequences.
8901 
8902   // Make sure that all of the users of a non-constant load are from the
8903   // BUILD_VECTOR node.
8904   // FIXME: Is the use count needed for non-constant, non-load case?
8905   if (!ConstSplatVal && !IsLoad && !BVOp->isOnlyUserOf(Ld.getNode()))
8906     return SDValue();
8907 
8908   unsigned ScalarSize = Ld.getValueSizeInBits();
8909   bool IsGE256 = (VT.getSizeInBits() >= 256);
8910 
8911   // When optimizing for size, generate up to 5 extra bytes for a broadcast
8912   // instruction to save 8 or more bytes of constant pool data.
8913   // TODO: If multiple splats are generated to load the same constant,
8914   // it may be detrimental to overall size. There needs to be a way to detect
8915   // that condition to know if this is truly a size win.
8916   bool OptForSize = DAG.shouldOptForSize();
8917 
8918   // Handle broadcasting a single constant scalar from the constant pool
8919   // into a vector.
8920   // On Sandybridge (no AVX2), it is still better to load a constant vector
8921   // from the constant pool and not to broadcast it from a scalar.
8922   // But override that restriction when optimizing for size.
8923   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
8924   if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
8925     EVT CVT = Ld.getValueType();
8926     assert(!CVT.isVector() && "Must not broadcast a vector type");
8927 
8928     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
8929     // For size optimization, also splat v2f64 and v2i64, and for size opt
8930     // with AVX2, also splat i8 and i16.
8931     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
8932     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8933         (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
8934       const Constant *C = nullptr;
8935       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
8936         C = CI->getConstantIntValue();
8937       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
8938         C = CF->getConstantFPValue();
8939 
8940       assert(C && "Invalid constant type");
8941 
8942       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8943       SDValue CP =
8944           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
8945       Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
8946 
8947       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8948       SDValue Ops[] = {DAG.getEntryNode(), CP};
8949       MachinePointerInfo MPI =
8950           MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8951       return DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops, CVT,
8952                                      MPI, Alignment, MachineMemOperand::MOLoad);
8953     }
8954   }
8955 
8956   // Handle AVX2 in-register broadcasts.
8957   if (!IsLoad && Subtarget.hasInt256() &&
8958       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
8959     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
8960 
8961   // The scalar source must be a normal load.
8962   if (!IsLoad)
8963     return SDValue();
8964 
8965   // Make sure the non-chain result is only used by this build vector.
8966   if (!Ld->hasNUsesOfValue(NumElts - NumUndefElts, 0))
8967     return SDValue();
8968 
8969   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
8970       (Subtarget.hasVLX() && ScalarSize == 64)) {
8971     auto *LN = cast<LoadSDNode>(Ld);
8972     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8973     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8974     SDValue BCast =
8975         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8976                                 LN->getMemoryVT(), LN->getMemOperand());
8977     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8978     return BCast;
8979   }
8980 
8981   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
8982   // double since there is no vbroadcastsd xmm
8983   if (Subtarget.hasInt256() && Ld.getValueType().isInteger() &&
8984       (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)) {
8985     auto *LN = cast<LoadSDNode>(Ld);
8986     SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8987     SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
8988     SDValue BCast =
8989         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
8990                                 LN->getMemoryVT(), LN->getMemOperand());
8991     DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BCast.getValue(1));
8992     return BCast;
8993   }
8994 
8995   // Unsupported broadcast.
8996   return SDValue();
8997 }
8998 
8999 /// For an EXTRACT_VECTOR_ELT with a constant index return the real
9000 /// underlying vector and index.
9001 ///
9002 /// Modifies \p ExtractedFromVec to the real vector and returns the real
9003 /// index.
9004 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
9005                                          SDValue ExtIdx) {
9006   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
9007   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
9008     return Idx;
9009 
9010   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
9011   // lowered this:
9012   //   (extract_vector_elt (v8f32 %1), Constant<6>)
9013   // to:
9014   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
9015   //                           (extract_subvector (v8f32 %0), Constant<4>),
9016   //                           undef)
9017   //                       Constant<0>)
9018   // In this case the vector is the extract_subvector expression and the index
9019   // is 2, as specified by the shuffle.
9020   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
9021   SDValue ShuffleVec = SVOp->getOperand(0);
9022   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
9023   assert(ShuffleVecVT.getVectorElementType() ==
9024          ExtractedFromVec.getSimpleValueType().getVectorElementType());
9025 
9026   int ShuffleIdx = SVOp->getMaskElt(Idx);
9027   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
9028     ExtractedFromVec = ShuffleVec;
9029     return ShuffleIdx;
9030   }
9031   return Idx;
9032 }
9033 
9034 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
9035   MVT VT = Op.getSimpleValueType();
9036 
9037   // Skip if insert_vec_elt is not supported.
9038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9039   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
9040     return SDValue();
9041 
9042   SDLoc DL(Op);
9043   unsigned NumElems = Op.getNumOperands();
9044 
9045   SDValue VecIn1;
9046   SDValue VecIn2;
9047   SmallVector<unsigned, 4> InsertIndices;
9048   SmallVector<int, 8> Mask(NumElems, -1);
9049 
9050   for (unsigned i = 0; i != NumElems; ++i) {
9051     unsigned Opc = Op.getOperand(i).getOpcode();
9052 
9053     if (Opc == ISD::UNDEF)
9054       continue;
9055 
9056     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
9057       // Quit if more than 1 elements need inserting.
9058       if (InsertIndices.size() > 1)
9059         return SDValue();
9060 
9061       InsertIndices.push_back(i);
9062       continue;
9063     }
9064 
9065     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
9066     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
9067 
9068     // Quit if non-constant index.
9069     if (!isa<ConstantSDNode>(ExtIdx))
9070       return SDValue();
9071     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
9072 
9073     // Quit if extracted from vector of different type.
9074     if (ExtractedFromVec.getValueType() != VT)
9075       return SDValue();
9076 
9077     if (!VecIn1.getNode())
9078       VecIn1 = ExtractedFromVec;
9079     else if (VecIn1 != ExtractedFromVec) {
9080       if (!VecIn2.getNode())
9081         VecIn2 = ExtractedFromVec;
9082       else if (VecIn2 != ExtractedFromVec)
9083         // Quit if more than 2 vectors to shuffle
9084         return SDValue();
9085     }
9086 
9087     if (ExtractedFromVec == VecIn1)
9088       Mask[i] = Idx;
9089     else if (ExtractedFromVec == VecIn2)
9090       Mask[i] = Idx + NumElems;
9091   }
9092 
9093   if (!VecIn1.getNode())
9094     return SDValue();
9095 
9096   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9097   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
9098 
9099   for (unsigned Idx : InsertIndices)
9100     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
9101                      DAG.getIntPtrConstant(Idx, DL));
9102 
9103   return NV;
9104 }
9105 
9106 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
9107 static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
9108                                      const X86Subtarget &Subtarget) {
9109 
9110   MVT VT = Op.getSimpleValueType();
9111   assert((VT.getVectorElementType() == MVT::i1) &&
9112          "Unexpected type in LowerBUILD_VECTORvXi1!");
9113 
9114   SDLoc dl(Op);
9115   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
9116       ISD::isBuildVectorAllOnes(Op.getNode()))
9117     return Op;
9118 
9119   uint64_t Immediate = 0;
9120   SmallVector<unsigned, 16> NonConstIdx;
9121   bool IsSplat = true;
9122   bool HasConstElts = false;
9123   int SplatIdx = -1;
9124   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
9125     SDValue In = Op.getOperand(idx);
9126     if (In.isUndef())
9127       continue;
9128     if (auto *InC = dyn_cast<ConstantSDNode>(In)) {
9129       Immediate |= (InC->getZExtValue() & 0x1) << idx;
9130       HasConstElts = true;
9131     } else {
9132       NonConstIdx.push_back(idx);
9133     }
9134     if (SplatIdx < 0)
9135       SplatIdx = idx;
9136     else if (In != Op.getOperand(SplatIdx))
9137       IsSplat = false;
9138   }
9139 
9140   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
9141   if (IsSplat) {
9142     // The build_vector allows the scalar element to be larger than the vector
9143     // element type. We need to mask it to use as a condition unless we know
9144     // the upper bits are zero.
9145     // FIXME: Use computeKnownBits instead of checking specific opcode?
9146     SDValue Cond = Op.getOperand(SplatIdx);
9147     assert(Cond.getValueType() == MVT::i8 && "Unexpected VT!");
9148     if (Cond.getOpcode() != ISD::SETCC)
9149       Cond = DAG.getNode(ISD::AND, dl, MVT::i8, Cond,
9150                          DAG.getConstant(1, dl, MVT::i8));
9151 
9152     // Perform the select in the scalar domain so we can use cmov.
9153     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9154       SDValue Select = DAG.getSelect(dl, MVT::i32, Cond,
9155                                      DAG.getAllOnesConstant(dl, MVT::i32),
9156                                      DAG.getConstant(0, dl, MVT::i32));
9157       Select = DAG.getBitcast(MVT::v32i1, Select);
9158       return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Select, Select);
9159     } else {
9160       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9161       SDValue Select = DAG.getSelect(dl, ImmVT, Cond,
9162                                      DAG.getAllOnesConstant(dl, ImmVT),
9163                                      DAG.getConstant(0, dl, ImmVT));
9164       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9165       Select = DAG.getBitcast(VecVT, Select);
9166       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Select,
9167                          DAG.getIntPtrConstant(0, dl));
9168     }
9169   }
9170 
9171   // insert elements one by one
9172   SDValue DstVec;
9173   if (HasConstElts) {
9174     if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
9175       SDValue ImmL = DAG.getConstant(Lo_32(Immediate), dl, MVT::i32);
9176       SDValue ImmH = DAG.getConstant(Hi_32(Immediate), dl, MVT::i32);
9177       ImmL = DAG.getBitcast(MVT::v32i1, ImmL);
9178       ImmH = DAG.getBitcast(MVT::v32i1, ImmH);
9179       DstVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, ImmL, ImmH);
9180     } else {
9181       MVT ImmVT = MVT::getIntegerVT(std::max((unsigned)VT.getSizeInBits(), 8U));
9182       SDValue Imm = DAG.getConstant(Immediate, dl, ImmVT);
9183       MVT VecVT = VT.getSizeInBits() >= 8 ? VT : MVT::v8i1;
9184       DstVec = DAG.getBitcast(VecVT, Imm);
9185       DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, DstVec,
9186                            DAG.getIntPtrConstant(0, dl));
9187     }
9188   } else
9189     DstVec = DAG.getUNDEF(VT);
9190 
9191   for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
9192     unsigned InsertIdx = NonConstIdx[i];
9193     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
9194                          Op.getOperand(InsertIdx),
9195                          DAG.getIntPtrConstant(InsertIdx, dl));
9196   }
9197   return DstVec;
9198 }
9199 
9200 /// This is a helper function of LowerToHorizontalOp().
9201 /// This function checks that the build_vector \p N in input implements a
9202 /// 128-bit partial horizontal operation on a 256-bit vector, but that operation
9203 /// may not match the layout of an x86 256-bit horizontal instruction.
9204 /// In other words, if this returns true, then some extraction/insertion will
9205 /// be required to produce a valid horizontal instruction.
9206 ///
9207 /// Parameter \p Opcode defines the kind of horizontal operation to match.
9208 /// For example, if \p Opcode is equal to ISD::ADD, then this function
9209 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
9210 /// is equal to ISD::SUB, then this function checks if this is a horizontal
9211 /// arithmetic sub.
9212 ///
9213 /// This function only analyzes elements of \p N whose indices are
9214 /// in range [BaseIdx, LastIdx).
9215 ///
9216 /// TODO: This function was originally used to match both real and fake partial
9217 /// horizontal operations, but the index-matching logic is incorrect for that.
9218 /// See the corrected implementation in isHopBuildVector(). Can we reduce this
9219 /// code because it is only used for partial h-op matching now?
9220 static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
9221                                   SelectionDAG &DAG,
9222                                   unsigned BaseIdx, unsigned LastIdx,
9223                                   SDValue &V0, SDValue &V1) {
9224   EVT VT = N->getValueType(0);
9225   assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops");
9226   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
9227   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
9228          "Invalid Vector in input!");
9229 
9230   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
9231   bool CanFold = true;
9232   unsigned ExpectedVExtractIdx = BaseIdx;
9233   unsigned NumElts = LastIdx - BaseIdx;
9234   V0 = DAG.getUNDEF(VT);
9235   V1 = DAG.getUNDEF(VT);
9236 
9237   // Check if N implements a horizontal binop.
9238   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
9239     SDValue Op = N->getOperand(i + BaseIdx);
9240 
9241     // Skip UNDEFs.
9242     if (Op->isUndef()) {
9243       // Update the expected vector extract index.
9244       if (i * 2 == NumElts)
9245         ExpectedVExtractIdx = BaseIdx;
9246       ExpectedVExtractIdx += 2;
9247       continue;
9248     }
9249 
9250     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
9251 
9252     if (!CanFold)
9253       break;
9254 
9255     SDValue Op0 = Op.getOperand(0);
9256     SDValue Op1 = Op.getOperand(1);
9257 
9258     // Try to match the following pattern:
9259     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
9260     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9261         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9262         Op0.getOperand(0) == Op1.getOperand(0) &&
9263         isa<ConstantSDNode>(Op0.getOperand(1)) &&
9264         isa<ConstantSDNode>(Op1.getOperand(1)));
9265     if (!CanFold)
9266       break;
9267 
9268     unsigned I0 = Op0.getConstantOperandVal(1);
9269     unsigned I1 = Op1.getConstantOperandVal(1);
9270 
9271     if (i * 2 < NumElts) {
9272       if (V0.isUndef()) {
9273         V0 = Op0.getOperand(0);
9274         if (V0.getValueType() != VT)
9275           return false;
9276       }
9277     } else {
9278       if (V1.isUndef()) {
9279         V1 = Op0.getOperand(0);
9280         if (V1.getValueType() != VT)
9281           return false;
9282       }
9283       if (i * 2 == NumElts)
9284         ExpectedVExtractIdx = BaseIdx;
9285     }
9286 
9287     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
9288     if (I0 == ExpectedVExtractIdx)
9289       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
9290     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
9291       // Try to match the following dag sequence:
9292       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
9293       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
9294     } else
9295       CanFold = false;
9296 
9297     ExpectedVExtractIdx += 2;
9298   }
9299 
9300   return CanFold;
9301 }
9302 
9303 /// Emit a sequence of two 128-bit horizontal add/sub followed by
9304 /// a concat_vector.
9305 ///
9306 /// This is a helper function of LowerToHorizontalOp().
9307 /// This function expects two 256-bit vectors called V0 and V1.
9308 /// At first, each vector is split into two separate 128-bit vectors.
9309 /// Then, the resulting 128-bit vectors are used to implement two
9310 /// horizontal binary operations.
9311 ///
9312 /// The kind of horizontal binary operation is defined by \p X86Opcode.
9313 ///
9314 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
9315 /// the two new horizontal binop.
9316 /// When Mode is set, the first horizontal binop dag node would take as input
9317 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
9318 /// horizontal binop dag node would take as input the lower 128-bit of V1
9319 /// and the upper 128-bit of V1.
9320 ///   Example:
9321 ///     HADD V0_LO, V0_HI
9322 ///     HADD V1_LO, V1_HI
9323 ///
9324 /// Otherwise, the first horizontal binop dag node takes as input the lower
9325 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
9326 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
9327 ///   Example:
9328 ///     HADD V0_LO, V1_LO
9329 ///     HADD V0_HI, V1_HI
9330 ///
9331 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
9332 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
9333 /// the upper 128-bits of the result.
9334 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
9335                                      const SDLoc &DL, SelectionDAG &DAG,
9336                                      unsigned X86Opcode, bool Mode,
9337                                      bool isUndefLO, bool isUndefHI) {
9338   MVT VT = V0.getSimpleValueType();
9339   assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&
9340          "Invalid nodes in input!");
9341 
9342   unsigned NumElts = VT.getVectorNumElements();
9343   SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
9344   SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
9345   SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
9346   SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
9347   MVT NewVT = V0_LO.getSimpleValueType();
9348 
9349   SDValue LO = DAG.getUNDEF(NewVT);
9350   SDValue HI = DAG.getUNDEF(NewVT);
9351 
9352   if (Mode) {
9353     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9354     if (!isUndefLO && !V0->isUndef())
9355       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
9356     if (!isUndefHI && !V1->isUndef())
9357       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
9358   } else {
9359     // Don't emit a horizontal binop if the result is expected to be UNDEF.
9360     if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
9361       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
9362 
9363     if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
9364       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
9365   }
9366 
9367   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
9368 }
9369 
9370 /// Returns true iff \p BV builds a vector with the result equivalent to
9371 /// the result of ADDSUB/SUBADD operation.
9372 /// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
9373 /// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
9374 /// \p Opnd0 and \p Opnd1.
9375 static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
9376                              const X86Subtarget &Subtarget, SelectionDAG &DAG,
9377                              SDValue &Opnd0, SDValue &Opnd1,
9378                              unsigned &NumExtracts,
9379                              bool &IsSubAdd) {
9380 
9381   MVT VT = BV->getSimpleValueType(0);
9382   if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
9383     return false;
9384 
9385   unsigned NumElts = VT.getVectorNumElements();
9386   SDValue InVec0 = DAG.getUNDEF(VT);
9387   SDValue InVec1 = DAG.getUNDEF(VT);
9388 
9389   NumExtracts = 0;
9390 
9391   // Odd-numbered elements in the input build vector are obtained from
9392   // adding/subtracting two integer/float elements.
9393   // Even-numbered elements in the input build vector are obtained from
9394   // subtracting/adding two integer/float elements.
9395   unsigned Opc[2] = {0, 0};
9396   for (unsigned i = 0, e = NumElts; i != e; ++i) {
9397     SDValue Op = BV->getOperand(i);
9398 
9399     // Skip 'undef' values.
9400     unsigned Opcode = Op.getOpcode();
9401     if (Opcode == ISD::UNDEF)
9402       continue;
9403 
9404     // Early exit if we found an unexpected opcode.
9405     if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
9406       return false;
9407 
9408     SDValue Op0 = Op.getOperand(0);
9409     SDValue Op1 = Op.getOperand(1);
9410 
9411     // Try to match the following pattern:
9412     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
9413     // Early exit if we cannot match that sequence.
9414     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9415         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9416         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9417         Op0.getOperand(1) != Op1.getOperand(1))
9418       return false;
9419 
9420     unsigned I0 = Op0.getConstantOperandVal(1);
9421     if (I0 != i)
9422       return false;
9423 
9424     // We found a valid add/sub node, make sure its the same opcode as previous
9425     // elements for this parity.
9426     if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
9427       return false;
9428     Opc[i % 2] = Opcode;
9429 
9430     // Update InVec0 and InVec1.
9431     if (InVec0.isUndef()) {
9432       InVec0 = Op0.getOperand(0);
9433       if (InVec0.getSimpleValueType() != VT)
9434         return false;
9435     }
9436     if (InVec1.isUndef()) {
9437       InVec1 = Op1.getOperand(0);
9438       if (InVec1.getSimpleValueType() != VT)
9439         return false;
9440     }
9441 
9442     // Make sure that operands in input to each add/sub node always
9443     // come from a same pair of vectors.
9444     if (InVec0 != Op0.getOperand(0)) {
9445       if (Opcode == ISD::FSUB)
9446         return false;
9447 
9448       // FADD is commutable. Try to commute the operands
9449       // and then test again.
9450       std::swap(Op0, Op1);
9451       if (InVec0 != Op0.getOperand(0))
9452         return false;
9453     }
9454 
9455     if (InVec1 != Op1.getOperand(0))
9456       return false;
9457 
9458     // Increment the number of extractions done.
9459     ++NumExtracts;
9460   }
9461 
9462   // Ensure we have found an opcode for both parities and that they are
9463   // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
9464   // inputs are undef.
9465   if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
9466       InVec0.isUndef() || InVec1.isUndef())
9467     return false;
9468 
9469   IsSubAdd = Opc[0] == ISD::FADD;
9470 
9471   Opnd0 = InVec0;
9472   Opnd1 = InVec1;
9473   return true;
9474 }
9475 
9476 /// Returns true if is possible to fold MUL and an idiom that has already been
9477 /// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
9478 /// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
9479 /// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
9480 ///
9481 /// Prior to calling this function it should be known that there is some
9482 /// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
9483 /// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
9484 /// before replacement of such SDNode with ADDSUB operation. Thus the number
9485 /// of \p Opnd0 uses is expected to be equal to 2.
9486 /// For example, this function may be called for the following IR:
9487 ///    %AB = fmul fast <2 x double> %A, %B
9488 ///    %Sub = fsub fast <2 x double> %AB, %C
9489 ///    %Add = fadd fast <2 x double> %AB, %C
9490 ///    %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
9491 ///                            <2 x i32> <i32 0, i32 3>
9492 /// There is a def for %Addsub here, which potentially can be replaced by
9493 /// X86ISD::ADDSUB operation:
9494 ///    %Addsub = X86ISD::ADDSUB %AB, %C
9495 /// and such ADDSUB can further be replaced with FMADDSUB:
9496 ///    %Addsub = FMADDSUB %A, %B, %C.
9497 ///
9498 /// The main reason why this method is called before the replacement of the
9499 /// recognized ADDSUB idiom with ADDSUB operation is that such replacement
9500 /// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
9501 /// FMADDSUB is.
9502 static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
9503                                  SelectionDAG &DAG,
9504                                  SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
9505                                  unsigned ExpectedUses) {
9506   if (Opnd0.getOpcode() != ISD::FMUL ||
9507       !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
9508     return false;
9509 
9510   // FIXME: These checks must match the similar ones in
9511   // DAGCombiner::visitFADDForFMACombine. It would be good to have one
9512   // function that would answer if it is Ok to fuse MUL + ADD to FMADD
9513   // or MUL + ADDSUB to FMADDSUB.
9514   const TargetOptions &Options = DAG.getTarget().Options;
9515   bool AllowFusion =
9516       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
9517   if (!AllowFusion)
9518     return false;
9519 
9520   Opnd2 = Opnd1;
9521   Opnd1 = Opnd0.getOperand(1);
9522   Opnd0 = Opnd0.getOperand(0);
9523 
9524   return true;
9525 }
9526 
9527 /// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
9528 /// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
9529 /// X86ISD::FMSUBADD node.
9530 static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
9531                                        const X86Subtarget &Subtarget,
9532                                        SelectionDAG &DAG) {
9533   SDValue Opnd0, Opnd1;
9534   unsigned NumExtracts;
9535   bool IsSubAdd;
9536   if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
9537                         IsSubAdd))
9538     return SDValue();
9539 
9540   MVT VT = BV->getSimpleValueType(0);
9541   SDLoc DL(BV);
9542 
9543   // Try to generate X86ISD::FMADDSUB node here.
9544   SDValue Opnd2;
9545   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
9546     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
9547     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
9548   }
9549 
9550   // We only support ADDSUB.
9551   if (IsSubAdd)
9552     return SDValue();
9553 
9554   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
9555   // the ADDSUB idiom has been successfully recognized. There are no known
9556   // X86 targets with 512-bit ADDSUB instructions!
9557   // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
9558   // recognition.
9559   if (VT.is512BitVector())
9560     return SDValue();
9561 
9562   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
9563 }
9564 
9565 static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
9566                              unsigned &HOpcode, SDValue &V0, SDValue &V1) {
9567   // Initialize outputs to known values.
9568   MVT VT = BV->getSimpleValueType(0);
9569   HOpcode = ISD::DELETED_NODE;
9570   V0 = DAG.getUNDEF(VT);
9571   V1 = DAG.getUNDEF(VT);
9572 
9573   // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
9574   // half of the result is calculated independently from the 128-bit halves of
9575   // the inputs, so that makes the index-checking logic below more complicated.
9576   unsigned NumElts = VT.getVectorNumElements();
9577   unsigned GenericOpcode = ISD::DELETED_NODE;
9578   unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
9579   unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
9580   unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
9581   for (unsigned i = 0; i != Num128BitChunks; ++i) {
9582     for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
9583       // Ignore undef elements.
9584       SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
9585       if (Op.isUndef())
9586         continue;
9587 
9588       // If there's an opcode mismatch, we're done.
9589       if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
9590         return false;
9591 
9592       // Initialize horizontal opcode.
9593       if (HOpcode == ISD::DELETED_NODE) {
9594         GenericOpcode = Op.getOpcode();
9595         switch (GenericOpcode) {
9596         case ISD::ADD: HOpcode = X86ISD::HADD; break;
9597         case ISD::SUB: HOpcode = X86ISD::HSUB; break;
9598         case ISD::FADD: HOpcode = X86ISD::FHADD; break;
9599         case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
9600         default: return false;
9601         }
9602       }
9603 
9604       SDValue Op0 = Op.getOperand(0);
9605       SDValue Op1 = Op.getOperand(1);
9606       if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9607           Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9608           Op0.getOperand(0) != Op1.getOperand(0) ||
9609           !isa<ConstantSDNode>(Op0.getOperand(1)) ||
9610           !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
9611         return false;
9612 
9613       // The source vector is chosen based on which 64-bit half of the
9614       // destination vector is being calculated.
9615       if (j < NumEltsIn64Bits) {
9616         if (V0.isUndef())
9617           V0 = Op0.getOperand(0);
9618       } else {
9619         if (V1.isUndef())
9620           V1 = Op0.getOperand(0);
9621       }
9622 
9623       SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
9624       if (SourceVec != Op0.getOperand(0))
9625         return false;
9626 
9627       // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
9628       unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
9629       unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
9630       unsigned ExpectedIndex = i * NumEltsIn128Bits +
9631                                (j % NumEltsIn64Bits) * 2;
9632       if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
9633         continue;
9634 
9635       // If this is not a commutative op, this does not match.
9636       if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
9637         return false;
9638 
9639       // Addition is commutative, so try swapping the extract indexes.
9640       // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
9641       if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
9642         continue;
9643 
9644       // Extract indexes do not match horizontal requirement.
9645       return false;
9646     }
9647   }
9648   // We matched. Opcode and operands are returned by reference as arguments.
9649   return true;
9650 }
9651 
9652 static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
9653                                     SelectionDAG &DAG, unsigned HOpcode,
9654                                     SDValue V0, SDValue V1) {
9655   // If either input vector is not the same size as the build vector,
9656   // extract/insert the low bits to the correct size.
9657   // This is free (examples: zmm --> xmm, xmm --> ymm).
9658   MVT VT = BV->getSimpleValueType(0);
9659   unsigned Width = VT.getSizeInBits();
9660   if (V0.getValueSizeInBits() > Width)
9661     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
9662   else if (V0.getValueSizeInBits() < Width)
9663     V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
9664 
9665   if (V1.getValueSizeInBits() > Width)
9666     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
9667   else if (V1.getValueSizeInBits() < Width)
9668     V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
9669 
9670   unsigned NumElts = VT.getVectorNumElements();
9671   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
9672   for (unsigned i = 0; i != NumElts; ++i)
9673     if (BV->getOperand(i).isUndef())
9674       DemandedElts.clearBit(i);
9675 
9676   // If we don't need the upper xmm, then perform as a xmm hop.
9677   unsigned HalfNumElts = NumElts / 2;
9678   if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
9679     MVT HalfVT = VT.getHalfNumVectorElementsVT();
9680     V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
9681     V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
9682     SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
9683     return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
9684   }
9685 
9686   return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
9687 }
9688 
9689 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
9690 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
9691                                    const X86Subtarget &Subtarget,
9692                                    SelectionDAG &DAG) {
9693   // We need at least 2 non-undef elements to make this worthwhile by default.
9694   unsigned NumNonUndefs =
9695       count_if(BV->op_values(), [](SDValue V) { return !V.isUndef(); });
9696   if (NumNonUndefs < 2)
9697     return SDValue();
9698 
9699   // There are 4 sets of horizontal math operations distinguished by type:
9700   // int/FP at 128-bit/256-bit. Each type was introduced with a different
9701   // subtarget feature. Try to match those "native" patterns first.
9702   MVT VT = BV->getSimpleValueType(0);
9703   if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
9704       ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
9705       ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
9706       ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
9707     unsigned HOpcode;
9708     SDValue V0, V1;
9709     if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
9710       return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
9711   }
9712 
9713   // Try harder to match 256-bit ops by using extract/concat.
9714   if (!Subtarget.hasAVX() || !VT.is256BitVector())
9715     return SDValue();
9716 
9717   // Count the number of UNDEF operands in the build_vector in input.
9718   unsigned NumElts = VT.getVectorNumElements();
9719   unsigned Half = NumElts / 2;
9720   unsigned NumUndefsLO = 0;
9721   unsigned NumUndefsHI = 0;
9722   for (unsigned i = 0, e = Half; i != e; ++i)
9723     if (BV->getOperand(i)->isUndef())
9724       NumUndefsLO++;
9725 
9726   for (unsigned i = Half, e = NumElts; i != e; ++i)
9727     if (BV->getOperand(i)->isUndef())
9728       NumUndefsHI++;
9729 
9730   SDLoc DL(BV);
9731   SDValue InVec0, InVec1;
9732   if (VT == MVT::v8i32 || VT == MVT::v16i16) {
9733     SDValue InVec2, InVec3;
9734     unsigned X86Opcode;
9735     bool CanFold = true;
9736 
9737     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
9738         isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
9739                               InVec3) &&
9740         ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9741         ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9742       X86Opcode = X86ISD::HADD;
9743     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
9744                                    InVec1) &&
9745              isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
9746                                    InVec3) &&
9747              ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
9748              ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
9749       X86Opcode = X86ISD::HSUB;
9750     else
9751       CanFold = false;
9752 
9753     if (CanFold) {
9754       // Do not try to expand this build_vector into a pair of horizontal
9755       // add/sub if we can emit a pair of scalar add/sub.
9756       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9757         return SDValue();
9758 
9759       // Convert this build_vector into a pair of horizontal binops followed by
9760       // a concat vector. We must adjust the outputs from the partial horizontal
9761       // matching calls above to account for undefined vector halves.
9762       SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
9763       SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
9764       assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?");
9765       bool isUndefLO = NumUndefsLO == Half;
9766       bool isUndefHI = NumUndefsHI == Half;
9767       return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
9768                                    isUndefHI);
9769     }
9770   }
9771 
9772   if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
9773       VT == MVT::v16i16) {
9774     unsigned X86Opcode;
9775     if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
9776       X86Opcode = X86ISD::HADD;
9777     else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
9778                                    InVec1))
9779       X86Opcode = X86ISD::HSUB;
9780     else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
9781                                    InVec1))
9782       X86Opcode = X86ISD::FHADD;
9783     else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
9784                                    InVec1))
9785       X86Opcode = X86ISD::FHSUB;
9786     else
9787       return SDValue();
9788 
9789     // Don't try to expand this build_vector into a pair of horizontal add/sub
9790     // if we can simply emit a pair of scalar add/sub.
9791     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
9792       return SDValue();
9793 
9794     // Convert this build_vector into two horizontal add/sub followed by
9795     // a concat vector.
9796     bool isUndefLO = NumUndefsLO == Half;
9797     bool isUndefHI = NumUndefsHI == Half;
9798     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
9799                                  isUndefLO, isUndefHI);
9800   }
9801 
9802   return SDValue();
9803 }
9804 
9805 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
9806                           SelectionDAG &DAG);
9807 
9808 /// If a BUILD_VECTOR's source elements all apply the same bit operation and
9809 /// one of their operands is constant, lower to a pair of BUILD_VECTOR and
9810 /// just apply the bit to the vectors.
9811 /// NOTE: Its not in our interest to start make a general purpose vectorizer
9812 /// from this, but enough scalar bit operations are created from the later
9813 /// legalization + scalarization stages to need basic support.
9814 static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
9815                                        const X86Subtarget &Subtarget,
9816                                        SelectionDAG &DAG) {
9817   SDLoc DL(Op);
9818   MVT VT = Op->getSimpleValueType(0);
9819   unsigned NumElems = VT.getVectorNumElements();
9820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9821 
9822   // Check that all elements have the same opcode.
9823   // TODO: Should we allow UNDEFS and if so how many?
9824   unsigned Opcode = Op->getOperand(0).getOpcode();
9825   for (unsigned i = 1; i < NumElems; ++i)
9826     if (Opcode != Op->getOperand(i).getOpcode())
9827       return SDValue();
9828 
9829   // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
9830   bool IsShift = false;
9831   switch (Opcode) {
9832   default:
9833     return SDValue();
9834   case ISD::SHL:
9835   case ISD::SRL:
9836   case ISD::SRA:
9837     IsShift = true;
9838     break;
9839   case ISD::AND:
9840   case ISD::XOR:
9841   case ISD::OR:
9842     // Don't do this if the buildvector is a splat - we'd replace one
9843     // constant with an entire vector.
9844     if (Op->getSplatValue())
9845       return SDValue();
9846     if (!TLI.isOperationLegalOrPromote(Opcode, VT))
9847       return SDValue();
9848     break;
9849   }
9850 
9851   SmallVector<SDValue, 4> LHSElts, RHSElts;
9852   for (SDValue Elt : Op->ops()) {
9853     SDValue LHS = Elt.getOperand(0);
9854     SDValue RHS = Elt.getOperand(1);
9855 
9856     // We expect the canonicalized RHS operand to be the constant.
9857     if (!isa<ConstantSDNode>(RHS))
9858       return SDValue();
9859 
9860     // Extend shift amounts.
9861     if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
9862       if (!IsShift)
9863         return SDValue();
9864       RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
9865     }
9866 
9867     LHSElts.push_back(LHS);
9868     RHSElts.push_back(RHS);
9869   }
9870 
9871   // Limit to shifts by uniform immediates.
9872   // TODO: Only accept vXi8/vXi64 special cases?
9873   // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
9874   if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
9875     return SDValue();
9876 
9877   SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
9878   SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
9879   SDValue Res = DAG.getNode(Opcode, DL, VT, LHS, RHS);
9880 
9881   if (!IsShift)
9882     return Res;
9883 
9884   // Immediately lower the shift to ensure the constant build vector doesn't
9885   // get converted to a constant pool before the shift is lowered.
9886   return LowerShift(Res, Subtarget, DAG);
9887 }
9888 
9889 /// Create a vector constant without a load. SSE/AVX provide the bare minimum
9890 /// functionality to do this, so it's all zeros, all ones, or some derivation
9891 /// that is cheap to calculate.
9892 static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
9893                                          const X86Subtarget &Subtarget) {
9894   SDLoc DL(Op);
9895   MVT VT = Op.getSimpleValueType();
9896 
9897   // Vectors containing all zeros can be matched by pxor and xorps.
9898   if (ISD::isBuildVectorAllZeros(Op.getNode()))
9899     return Op;
9900 
9901   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
9902   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
9903   // vpcmpeqd on 256-bit vectors.
9904   if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
9905     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
9906       return Op;
9907 
9908     return getOnesVector(VT, DAG, DL);
9909   }
9910 
9911   return SDValue();
9912 }
9913 
9914 /// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
9915 /// from a vector of source values and a vector of extraction indices.
9916 /// The vectors might be manipulated to match the type of the permute op.
9917 static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
9918                                      SDLoc &DL, SelectionDAG &DAG,
9919                                      const X86Subtarget &Subtarget) {
9920   MVT ShuffleVT = VT;
9921   EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9922   unsigned NumElts = VT.getVectorNumElements();
9923   unsigned SizeInBits = VT.getSizeInBits();
9924 
9925   // Adjust IndicesVec to match VT size.
9926   assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&
9927          "Illegal variable permute mask size");
9928   if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
9929     IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
9930                                   NumElts * VT.getScalarSizeInBits());
9931   IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
9932 
9933   // Handle SrcVec that don't match VT type.
9934   if (SrcVec.getValueSizeInBits() != SizeInBits) {
9935     if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
9936       // Handle larger SrcVec by treating it as a larger permute.
9937       unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
9938       VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
9939       IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
9940       IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
9941                                   Subtarget, DAG, SDLoc(IndicesVec));
9942       SDValue NewSrcVec =
9943           createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9944       if (NewSrcVec)
9945         return extractSubVector(NewSrcVec, 0, DAG, DL, SizeInBits);
9946       return SDValue();
9947     } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
9948       // Widen smaller SrcVec to match VT.
9949       SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
9950     } else
9951       return SDValue();
9952   }
9953 
9954   auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
9955     assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale");
9956     EVT SrcVT = Idx.getValueType();
9957     unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
9958     uint64_t IndexScale = 0;
9959     uint64_t IndexOffset = 0;
9960 
9961     // If we're scaling a smaller permute op, then we need to repeat the
9962     // indices, scaling and offsetting them as well.
9963     // e.g. v4i32 -> v16i8 (Scale = 4)
9964     // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
9965     // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
9966     for (uint64_t i = 0; i != Scale; ++i) {
9967       IndexScale |= Scale << (i * NumDstBits);
9968       IndexOffset |= i << (i * NumDstBits);
9969     }
9970 
9971     Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
9972                       DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
9973     Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
9974                       DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
9975     return Idx;
9976   };
9977 
9978   unsigned Opcode = 0;
9979   switch (VT.SimpleTy) {
9980   default:
9981     break;
9982   case MVT::v16i8:
9983     if (Subtarget.hasSSSE3())
9984       Opcode = X86ISD::PSHUFB;
9985     break;
9986   case MVT::v8i16:
9987     if (Subtarget.hasVLX() && Subtarget.hasBWI())
9988       Opcode = X86ISD::VPERMV;
9989     else if (Subtarget.hasSSSE3()) {
9990       Opcode = X86ISD::PSHUFB;
9991       ShuffleVT = MVT::v16i8;
9992     }
9993     break;
9994   case MVT::v4f32:
9995   case MVT::v4i32:
9996     if (Subtarget.hasAVX()) {
9997       Opcode = X86ISD::VPERMILPV;
9998       ShuffleVT = MVT::v4f32;
9999     } else if (Subtarget.hasSSSE3()) {
10000       Opcode = X86ISD::PSHUFB;
10001       ShuffleVT = MVT::v16i8;
10002     }
10003     break;
10004   case MVT::v2f64:
10005   case MVT::v2i64:
10006     if (Subtarget.hasAVX()) {
10007       // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
10008       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10009       Opcode = X86ISD::VPERMILPV;
10010       ShuffleVT = MVT::v2f64;
10011     } else if (Subtarget.hasSSE41()) {
10012       // SSE41 can compare v2i64 - select between indices 0 and 1.
10013       return DAG.getSelectCC(
10014           DL, IndicesVec,
10015           getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
10016           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
10017           DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
10018           ISD::CondCode::SETEQ);
10019     }
10020     break;
10021   case MVT::v32i8:
10022     if (Subtarget.hasVLX() && Subtarget.hasVBMI())
10023       Opcode = X86ISD::VPERMV;
10024     else if (Subtarget.hasXOP()) {
10025       SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
10026       SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
10027       SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
10028       SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
10029       return DAG.getNode(
10030           ISD::CONCAT_VECTORS, DL, VT,
10031           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
10032           DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
10033     } else if (Subtarget.hasAVX()) {
10034       SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
10035       SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
10036       SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
10037       SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
10038       auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
10039                               ArrayRef<SDValue> Ops) {
10040         // Permute Lo and Hi and then select based on index range.
10041         // This works as SHUFB uses bits[3:0] to permute elements and we don't
10042         // care about the bit[7] as its just an index vector.
10043         SDValue Idx = Ops[2];
10044         EVT VT = Idx.getValueType();
10045         return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
10046                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
10047                                DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
10048                                ISD::CondCode::SETGT);
10049       };
10050       SDValue Ops[] = {LoLo, HiHi, IndicesVec};
10051       return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
10052                               PSHUFBBuilder);
10053     }
10054     break;
10055   case MVT::v16i16:
10056     if (Subtarget.hasVLX() && Subtarget.hasBWI())
10057       Opcode = X86ISD::VPERMV;
10058     else if (Subtarget.hasAVX()) {
10059       // Scale to v32i8 and perform as v32i8.
10060       IndicesVec = ScaleIndices(IndicesVec, 2);
10061       return DAG.getBitcast(
10062           VT, createVariablePermute(
10063                   MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
10064                   DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
10065     }
10066     break;
10067   case MVT::v8f32:
10068   case MVT::v8i32:
10069     if (Subtarget.hasAVX2())
10070       Opcode = X86ISD::VPERMV;
10071     else if (Subtarget.hasAVX()) {
10072       SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
10073       SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10074                                           {0, 1, 2, 3, 0, 1, 2, 3});
10075       SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
10076                                           {4, 5, 6, 7, 4, 5, 6, 7});
10077       if (Subtarget.hasXOP())
10078         return DAG.getBitcast(
10079             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32, LoLo, HiHi,
10080                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10081       // Permute Lo and Hi and then select based on index range.
10082       // This works as VPERMILPS only uses index bits[0:1] to permute elements.
10083       SDValue Res = DAG.getSelectCC(
10084           DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
10085           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
10086           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
10087           ISD::CondCode::SETGT);
10088       return DAG.getBitcast(VT, Res);
10089     }
10090     break;
10091   case MVT::v4i64:
10092   case MVT::v4f64:
10093     if (Subtarget.hasAVX512()) {
10094       if (!Subtarget.hasVLX()) {
10095         MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
10096         SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
10097                                 SDLoc(SrcVec));
10098         IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
10099                                     DAG, SDLoc(IndicesVec));
10100         SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
10101                                             DAG, Subtarget);
10102         return extract256BitVector(Res, 0, DAG, DL);
10103       }
10104       Opcode = X86ISD::VPERMV;
10105     } else if (Subtarget.hasAVX()) {
10106       SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
10107       SDValue LoLo =
10108           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
10109       SDValue HiHi =
10110           DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
10111       // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
10112       IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
10113       if (Subtarget.hasXOP())
10114         return DAG.getBitcast(
10115             VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64, LoLo, HiHi,
10116                             IndicesVec, DAG.getTargetConstant(0, DL, MVT::i8)));
10117       // Permute Lo and Hi and then select based on index range.
10118       // This works as VPERMILPD only uses index bit[1] to permute elements.
10119       SDValue Res = DAG.getSelectCC(
10120           DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
10121           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
10122           DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
10123           ISD::CondCode::SETGT);
10124       return DAG.getBitcast(VT, Res);
10125     }
10126     break;
10127   case MVT::v64i8:
10128     if (Subtarget.hasVBMI())
10129       Opcode = X86ISD::VPERMV;
10130     break;
10131   case MVT::v32i16:
10132     if (Subtarget.hasBWI())
10133       Opcode = X86ISD::VPERMV;
10134     break;
10135   case MVT::v16f32:
10136   case MVT::v16i32:
10137   case MVT::v8f64:
10138   case MVT::v8i64:
10139     if (Subtarget.hasAVX512())
10140       Opcode = X86ISD::VPERMV;
10141     break;
10142   }
10143   if (!Opcode)
10144     return SDValue();
10145 
10146   assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
10147          (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&
10148          "Illegal variable permute shuffle type");
10149 
10150   uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
10151   if (Scale > 1)
10152     IndicesVec = ScaleIndices(IndicesVec, Scale);
10153 
10154   EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
10155   IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
10156 
10157   SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
10158   SDValue Res = Opcode == X86ISD::VPERMV
10159                     ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
10160                     : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
10161   return DAG.getBitcast(VT, Res);
10162 }
10163 
10164 // Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
10165 // reasoned to be a permutation of a vector by indices in a non-constant vector.
10166 // (build_vector (extract_elt V, (extract_elt I, 0)),
10167 //               (extract_elt V, (extract_elt I, 1)),
10168 //                    ...
10169 // ->
10170 // (vpermv I, V)
10171 //
10172 // TODO: Handle undefs
10173 // TODO: Utilize pshufb and zero mask blending to support more efficient
10174 // construction of vectors with constant-0 elements.
10175 static SDValue
10176 LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
10177                                    const X86Subtarget &Subtarget) {
10178   SDValue SrcVec, IndicesVec;
10179   // Check for a match of the permute source vector and permute index elements.
10180   // This is done by checking that the i-th build_vector operand is of the form:
10181   // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
10182   for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
10183     SDValue Op = V.getOperand(Idx);
10184     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10185       return SDValue();
10186 
10187     // If this is the first extract encountered in V, set the source vector,
10188     // otherwise verify the extract is from the previously defined source
10189     // vector.
10190     if (!SrcVec)
10191       SrcVec = Op.getOperand(0);
10192     else if (SrcVec != Op.getOperand(0))
10193       return SDValue();
10194     SDValue ExtractedIndex = Op->getOperand(1);
10195     // Peek through extends.
10196     if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
10197         ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
10198       ExtractedIndex = ExtractedIndex.getOperand(0);
10199     if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10200       return SDValue();
10201 
10202     // If this is the first extract from the index vector candidate, set the
10203     // indices vector, otherwise verify the extract is from the previously
10204     // defined indices vector.
10205     if (!IndicesVec)
10206       IndicesVec = ExtractedIndex.getOperand(0);
10207     else if (IndicesVec != ExtractedIndex.getOperand(0))
10208       return SDValue();
10209 
10210     auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
10211     if (!PermIdx || PermIdx->getAPIntValue() != Idx)
10212       return SDValue();
10213   }
10214 
10215   SDLoc DL(V);
10216   MVT VT = V.getSimpleValueType();
10217   return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
10218 }
10219 
10220 SDValue
10221 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
10222   SDLoc dl(Op);
10223 
10224   MVT VT = Op.getSimpleValueType();
10225   MVT EltVT = VT.getVectorElementType();
10226   unsigned NumElems = Op.getNumOperands();
10227 
10228   // Generate vectors for predicate vectors.
10229   if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
10230     return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
10231 
10232   if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
10233     return VectorConstant;
10234 
10235   unsigned EVTBits = EltVT.getSizeInBits();
10236   APInt UndefMask = APInt::getNullValue(NumElems);
10237   APInt ZeroMask = APInt::getNullValue(NumElems);
10238   APInt NonZeroMask = APInt::getNullValue(NumElems);
10239   bool IsAllConstants = true;
10240   SmallSet<SDValue, 8> Values;
10241   unsigned NumConstants = NumElems;
10242   for (unsigned i = 0; i < NumElems; ++i) {
10243     SDValue Elt = Op.getOperand(i);
10244     if (Elt.isUndef()) {
10245       UndefMask.setBit(i);
10246       continue;
10247     }
10248     Values.insert(Elt);
10249     if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
10250       IsAllConstants = false;
10251       NumConstants--;
10252     }
10253     if (X86::isZeroNode(Elt)) {
10254       ZeroMask.setBit(i);
10255     } else {
10256       NonZeroMask.setBit(i);
10257     }
10258   }
10259 
10260   // All undef vector. Return an UNDEF. All zero vectors were handled above.
10261   if (NonZeroMask == 0) {
10262     assert(UndefMask.isAllOnesValue() && "Fully undef mask expected");
10263     return DAG.getUNDEF(VT);
10264   }
10265 
10266   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
10267 
10268   // If the upper elts of a ymm/zmm are undef/zero then we might be better off
10269   // lowering to a smaller build vector and padding with undef/zero.
10270   if ((VT.is256BitVector() || VT.is512BitVector()) &&
10271       !isFoldableUseOfShuffle(BV)) {
10272     unsigned UpperElems = NumElems / 2;
10273     APInt UndefOrZeroMask = UndefMask | ZeroMask;
10274     unsigned NumUpperUndefsOrZeros = UndefOrZeroMask.countLeadingOnes();
10275     if (NumUpperUndefsOrZeros >= UpperElems) {
10276       if (VT.is512BitVector() &&
10277           NumUpperUndefsOrZeros >= (NumElems - (NumElems / 4)))
10278         UpperElems = NumElems - (NumElems / 4);
10279       bool UndefUpper = UndefMask.countLeadingOnes() >= UpperElems;
10280       MVT LowerVT = MVT::getVectorVT(EltVT, NumElems - UpperElems);
10281       SDValue NewBV =
10282           DAG.getBuildVector(LowerVT, dl, Op->ops().drop_back(UpperElems));
10283       return widenSubVector(VT, NewBV, !UndefUpper, Subtarget, DAG, dl);
10284     }
10285   }
10286 
10287   if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
10288     return AddSub;
10289   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
10290     return HorizontalOp;
10291   if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
10292     return Broadcast;
10293   if (SDValue BitOp = lowerBuildVectorToBitOp(BV, Subtarget, DAG))
10294     return BitOp;
10295 
10296   unsigned NumZero = ZeroMask.countPopulation();
10297   unsigned NumNonZero = NonZeroMask.countPopulation();
10298 
10299   // If we are inserting one variable into a vector of non-zero constants, try
10300   // to avoid loading each constant element as a scalar. Load the constants as a
10301   // vector and then insert the variable scalar element. If insertion is not
10302   // supported, fall back to a shuffle to get the scalar blended with the
10303   // constants. Insertion into a zero vector is handled as a special-case
10304   // somewhere below here.
10305   if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
10306       (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
10307        isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
10308     // Create an all-constant vector. The variable element in the old
10309     // build vector is replaced by undef in the constant vector. Save the
10310     // variable scalar element and its index for use in the insertelement.
10311     LLVMContext &Context = *DAG.getContext();
10312     Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
10313     SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
10314     SDValue VarElt;
10315     SDValue InsIndex;
10316     for (unsigned i = 0; i != NumElems; ++i) {
10317       SDValue Elt = Op.getOperand(i);
10318       if (auto *C = dyn_cast<ConstantSDNode>(Elt))
10319         ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
10320       else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
10321         ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
10322       else if (!Elt.isUndef()) {
10323         assert(!VarElt.getNode() && !InsIndex.getNode() &&
10324                "Expected one variable element in this vector");
10325         VarElt = Elt;
10326         InsIndex = DAG.getVectorIdxConstant(i, dl);
10327       }
10328     }
10329     Constant *CV = ConstantVector::get(ConstVecOps);
10330     SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
10331 
10332     // The constants we just created may not be legal (eg, floating point). We
10333     // must lower the vector right here because we can not guarantee that we'll
10334     // legalize it before loading it. This is also why we could not just create
10335     // a new build vector here. If the build vector contains illegal constants,
10336     // it could get split back up into a series of insert elements.
10337     // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
10338     SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
10339     MachineFunction &MF = DAG.getMachineFunction();
10340     MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
10341     SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
10342     unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
10343     unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
10344     if (InsertC < NumEltsInLow128Bits)
10345       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
10346 
10347     // There's no good way to insert into the high elements of a >128-bit
10348     // vector, so use shuffles to avoid an extract/insert sequence.
10349     assert(VT.getSizeInBits() > 128 && "Invalid insertion index?");
10350     assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector");
10351     SmallVector<int, 8> ShuffleMask;
10352     unsigned NumElts = VT.getVectorNumElements();
10353     for (unsigned i = 0; i != NumElts; ++i)
10354       ShuffleMask.push_back(i == InsertC ? NumElts : i);
10355     SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
10356     return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
10357   }
10358 
10359   // Special case for single non-zero, non-undef, element.
10360   if (NumNonZero == 1) {
10361     unsigned Idx = NonZeroMask.countTrailingZeros();
10362     SDValue Item = Op.getOperand(Idx);
10363 
10364     // If we have a constant or non-constant insertion into the low element of
10365     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
10366     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
10367     // depending on what the source datatype is.
10368     if (Idx == 0) {
10369       if (NumZero == 0)
10370         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10371 
10372       if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
10373           (EltVT == MVT::i64 && Subtarget.is64Bit())) {
10374         assert((VT.is128BitVector() || VT.is256BitVector() ||
10375                 VT.is512BitVector()) &&
10376                "Expected an SSE value type!");
10377         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10378         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
10379         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10380       }
10381 
10382       // We can't directly insert an i8 or i16 into a vector, so zero extend
10383       // it to i32 first.
10384       if (EltVT == MVT::i16 || EltVT == MVT::i8) {
10385         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
10386         MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
10387         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
10388         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
10389         return DAG.getBitcast(VT, Item);
10390       }
10391     }
10392 
10393     // Is it a vector logical left shift?
10394     if (NumElems == 2 && Idx == 1 &&
10395         X86::isZeroNode(Op.getOperand(0)) &&
10396         !X86::isZeroNode(Op.getOperand(1))) {
10397       unsigned NumBits = VT.getSizeInBits();
10398       return getVShift(true, VT,
10399                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10400                                    VT, Op.getOperand(1)),
10401                        NumBits/2, DAG, *this, dl);
10402     }
10403 
10404     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
10405       return SDValue();
10406 
10407     // Otherwise, if this is a vector with i32 or f32 elements, and the element
10408     // is a non-constant being inserted into an element other than the low one,
10409     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
10410     // movd/movss) to move this into the low element, then shuffle it into
10411     // place.
10412     if (EVTBits == 32) {
10413       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
10414       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
10415     }
10416   }
10417 
10418   // Splat is obviously ok. Let legalizer expand it to a shuffle.
10419   if (Values.size() == 1) {
10420     if (EVTBits == 32) {
10421       // Instead of a shuffle like this:
10422       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
10423       // Check if it's possible to issue this instead.
10424       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
10425       unsigned Idx = NonZeroMask.countTrailingZeros();
10426       SDValue Item = Op.getOperand(Idx);
10427       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
10428         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
10429     }
10430     return SDValue();
10431   }
10432 
10433   // A vector full of immediates; various special cases are already
10434   // handled, so this is best done with a single constant-pool load.
10435   if (IsAllConstants)
10436     return SDValue();
10437 
10438   if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
10439       return V;
10440 
10441   // See if we can use a vector load to get all of the elements.
10442   {
10443     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
10444     if (SDValue LD =
10445             EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
10446       return LD;
10447   }
10448 
10449   // If this is a splat of pairs of 32-bit elements, we can use a narrower
10450   // build_vector and broadcast it.
10451   // TODO: We could probably generalize this more.
10452   if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
10453     SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
10454                        DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
10455     auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
10456       // Make sure all the even/odd operands match.
10457       for (unsigned i = 2; i != NumElems; ++i)
10458         if (Ops[i % 2] != Op.getOperand(i))
10459           return false;
10460       return true;
10461     };
10462     if (CanSplat(Op, NumElems, Ops)) {
10463       MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
10464       MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
10465       // Create a new build vector and cast to v2i64/v2f64.
10466       SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
10467                                      DAG.getBuildVector(NarrowVT, dl, Ops));
10468       // Broadcast from v2i64/v2f64 and cast to final VT.
10469       MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems/2);
10470       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
10471                                             NewBV));
10472     }
10473   }
10474 
10475   // For AVX-length vectors, build the individual 128-bit pieces and use
10476   // shuffles to put them in place.
10477   if (VT.getSizeInBits() > 128) {
10478     MVT HVT = MVT::getVectorVT(EltVT, NumElems/2);
10479 
10480     // Build both the lower and upper subvector.
10481     SDValue Lower =
10482         DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
10483     SDValue Upper = DAG.getBuildVector(
10484         HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
10485 
10486     // Recreate the wider vector with the lower and upper part.
10487     return concatSubVectors(Lower, Upper, DAG, dl);
10488   }
10489 
10490   // Let legalizer expand 2-wide build_vectors.
10491   if (EVTBits == 64) {
10492     if (NumNonZero == 1) {
10493       // One half is zero or undef.
10494       unsigned Idx = NonZeroMask.countTrailingZeros();
10495       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
10496                                Op.getOperand(Idx));
10497       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
10498     }
10499     return SDValue();
10500   }
10501 
10502   // If element VT is < 32 bits, convert it to inserts into a zero vector.
10503   if (EVTBits == 8 && NumElems == 16)
10504     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeroMask, NumNonZero, NumZero,
10505                                           DAG, Subtarget))
10506       return V;
10507 
10508   if (EVTBits == 16 && NumElems == 8)
10509     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeroMask, NumNonZero, NumZero,
10510                                           DAG, Subtarget))
10511       return V;
10512 
10513   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
10514   if (EVTBits == 32 && NumElems == 4)
10515     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
10516       return V;
10517 
10518   // If element VT is == 32 bits, turn it into a number of shuffles.
10519   if (NumElems == 4 && NumZero > 0) {
10520     SmallVector<SDValue, 8> Ops(NumElems);
10521     for (unsigned i = 0; i < 4; ++i) {
10522       bool isZero = !NonZeroMask[i];
10523       if (isZero)
10524         Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
10525       else
10526         Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10527     }
10528 
10529     for (unsigned i = 0; i < 2; ++i) {
10530       switch (NonZeroMask.extractBitsAsZExtValue(2, i * 2)) {
10531         default: llvm_unreachable("Unexpected NonZero count");
10532         case 0:
10533           Ops[i] = Ops[i*2];  // Must be a zero vector.
10534           break;
10535         case 1:
10536           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
10537           break;
10538         case 2:
10539           Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10540           break;
10541         case 3:
10542           Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
10543           break;
10544       }
10545     }
10546 
10547     bool Reverse1 = NonZeroMask.extractBitsAsZExtValue(2, 0) == 2;
10548     bool Reverse2 = NonZeroMask.extractBitsAsZExtValue(2, 2) == 2;
10549     int MaskVec[] = {
10550       Reverse1 ? 1 : 0,
10551       Reverse1 ? 0 : 1,
10552       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
10553       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
10554     };
10555     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
10556   }
10557 
10558   assert(Values.size() > 1 && "Expected non-undef and non-splat vector");
10559 
10560   // Check for a build vector from mostly shuffle plus few inserting.
10561   if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
10562     return Sh;
10563 
10564   // For SSE 4.1, use insertps to put the high elements into the low element.
10565   if (Subtarget.hasSSE41()) {
10566     SDValue Result;
10567     if (!Op.getOperand(0).isUndef())
10568       Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
10569     else
10570       Result = DAG.getUNDEF(VT);
10571 
10572     for (unsigned i = 1; i < NumElems; ++i) {
10573       if (Op.getOperand(i).isUndef()) continue;
10574       Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
10575                            Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
10576     }
10577     return Result;
10578   }
10579 
10580   // Otherwise, expand into a number of unpckl*, start by extending each of
10581   // our (non-undef) elements to the full vector width with the element in the
10582   // bottom slot of the vector (which generates no code for SSE).
10583   SmallVector<SDValue, 8> Ops(NumElems);
10584   for (unsigned i = 0; i < NumElems; ++i) {
10585     if (!Op.getOperand(i).isUndef())
10586       Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
10587     else
10588       Ops[i] = DAG.getUNDEF(VT);
10589   }
10590 
10591   // Next, we iteratively mix elements, e.g. for v4f32:
10592   //   Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
10593   //         : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
10594   //   Step 2: unpcklpd X, Y ==>    <3, 2, 1, 0>
10595   for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
10596     // Generate scaled UNPCKL shuffle mask.
10597     SmallVector<int, 16> Mask;
10598     for(unsigned i = 0; i != Scale; ++i)
10599       Mask.push_back(i);
10600     for (unsigned i = 0; i != Scale; ++i)
10601       Mask.push_back(NumElems+i);
10602     Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
10603 
10604     for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
10605       Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
10606   }
10607   return Ops[0];
10608 }
10609 
10610 // 256-bit AVX can use the vinsertf128 instruction
10611 // to create 256-bit vectors from two other 128-bit ones.
10612 // TODO: Detect subvector broadcast here instead of DAG combine?
10613 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
10614                                       const X86Subtarget &Subtarget) {
10615   SDLoc dl(Op);
10616   MVT ResVT = Op.getSimpleValueType();
10617 
10618   assert((ResVT.is256BitVector() ||
10619           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
10620 
10621   unsigned NumOperands = Op.getNumOperands();
10622   unsigned NumZero = 0;
10623   unsigned NumNonZero = 0;
10624   unsigned NonZeros = 0;
10625   for (unsigned i = 0; i != NumOperands; ++i) {
10626     SDValue SubVec = Op.getOperand(i);
10627     if (SubVec.isUndef())
10628       continue;
10629     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10630       ++NumZero;
10631     else {
10632       assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10633       NonZeros |= 1 << i;
10634       ++NumNonZero;
10635     }
10636   }
10637 
10638   // If we have more than 2 non-zeros, build each half separately.
10639   if (NumNonZero > 2) {
10640     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10641     ArrayRef<SDUse> Ops = Op->ops();
10642     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10643                              Ops.slice(0, NumOperands/2));
10644     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10645                              Ops.slice(NumOperands/2));
10646     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10647   }
10648 
10649   // Otherwise, build it up through insert_subvectors.
10650   SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
10651                         : DAG.getUNDEF(ResVT);
10652 
10653   MVT SubVT = Op.getOperand(0).getSimpleValueType();
10654   unsigned NumSubElems = SubVT.getVectorNumElements();
10655   for (unsigned i = 0; i != NumOperands; ++i) {
10656     if ((NonZeros & (1 << i)) == 0)
10657       continue;
10658 
10659     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
10660                       Op.getOperand(i),
10661                       DAG.getIntPtrConstant(i * NumSubElems, dl));
10662   }
10663 
10664   return Vec;
10665 }
10666 
10667 // Returns true if the given node is a type promotion (by concatenating i1
10668 // zeros) of the result of a node that already zeros all upper bits of
10669 // k-register.
10670 // TODO: Merge this with LowerAVXCONCAT_VECTORS?
10671 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
10672                                        const X86Subtarget &Subtarget,
10673                                        SelectionDAG & DAG) {
10674   SDLoc dl(Op);
10675   MVT ResVT = Op.getSimpleValueType();
10676   unsigned NumOperands = Op.getNumOperands();
10677 
10678   assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
10679          "Unexpected number of operands in CONCAT_VECTORS");
10680 
10681   uint64_t Zeros = 0;
10682   uint64_t NonZeros = 0;
10683   for (unsigned i = 0; i != NumOperands; ++i) {
10684     SDValue SubVec = Op.getOperand(i);
10685     if (SubVec.isUndef())
10686       continue;
10687     assert(i < sizeof(NonZeros) * CHAR_BIT); // Ensure the shift is in range.
10688     if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
10689       Zeros |= (uint64_t)1 << i;
10690     else
10691       NonZeros |= (uint64_t)1 << i;
10692   }
10693 
10694   unsigned NumElems = ResVT.getVectorNumElements();
10695 
10696   // If we are inserting non-zero vector and there are zeros in LSBs and undef
10697   // in the MSBs we need to emit a KSHIFTL. The generic lowering to
10698   // insert_subvector will give us two kshifts.
10699   if (isPowerOf2_64(NonZeros) && Zeros != 0 && NonZeros > Zeros &&
10700       Log2_64(NonZeros) != NumOperands - 1) {
10701     MVT ShiftVT = ResVT;
10702     if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
10703       ShiftVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
10704     unsigned Idx = Log2_64(NonZeros);
10705     SDValue SubVec = Op.getOperand(Idx);
10706     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10707     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ShiftVT,
10708                          DAG.getUNDEF(ShiftVT), SubVec,
10709                          DAG.getIntPtrConstant(0, dl));
10710     Op = DAG.getNode(X86ISD::KSHIFTL, dl, ShiftVT, SubVec,
10711                      DAG.getTargetConstant(Idx * SubVecNumElts, dl, MVT::i8));
10712     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, Op,
10713                        DAG.getIntPtrConstant(0, dl));
10714   }
10715 
10716   // If there are zero or one non-zeros we can handle this very simply.
10717   if (NonZeros == 0 || isPowerOf2_64(NonZeros)) {
10718     SDValue Vec = Zeros ? DAG.getConstant(0, dl, ResVT) : DAG.getUNDEF(ResVT);
10719     if (!NonZeros)
10720       return Vec;
10721     unsigned Idx = Log2_64(NonZeros);
10722     SDValue SubVec = Op.getOperand(Idx);
10723     unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
10724     return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
10725                        DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
10726   }
10727 
10728   if (NumOperands > 2) {
10729     MVT HalfVT = ResVT.getHalfNumVectorElementsVT();
10730     ArrayRef<SDUse> Ops = Op->ops();
10731     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10732                              Ops.slice(0, NumOperands/2));
10733     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
10734                              Ops.slice(NumOperands/2));
10735     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
10736   }
10737 
10738   assert(countPopulation(NonZeros) == 2 && "Simple cases not handled?");
10739 
10740   if (ResVT.getVectorNumElements() >= 16)
10741     return Op; // The operation is legal with KUNPCK
10742 
10743   SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
10744                             DAG.getUNDEF(ResVT), Op.getOperand(0),
10745                             DAG.getIntPtrConstant(0, dl));
10746   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
10747                      DAG.getIntPtrConstant(NumElems/2, dl));
10748 }
10749 
10750 static SDValue LowerCONCAT_VECTORS(SDValue Op,
10751                                    const X86Subtarget &Subtarget,
10752                                    SelectionDAG &DAG) {
10753   MVT VT = Op.getSimpleValueType();
10754   if (VT.getVectorElementType() == MVT::i1)
10755     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
10756 
10757   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
10758          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
10759           Op.getNumOperands() == 4)));
10760 
10761   // AVX can use the vinsertf128 instruction to create 256-bit vectors
10762   // from two other 128-bit ones.
10763 
10764   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
10765   return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
10766 }
10767 
10768 //===----------------------------------------------------------------------===//
10769 // Vector shuffle lowering
10770 //
10771 // This is an experimental code path for lowering vector shuffles on x86. It is
10772 // designed to handle arbitrary vector shuffles and blends, gracefully
10773 // degrading performance as necessary. It works hard to recognize idiomatic
10774 // shuffles and lower them to optimal instruction patterns without leaving
10775 // a framework that allows reasonably efficient handling of all vector shuffle
10776 // patterns.
10777 //===----------------------------------------------------------------------===//
10778 
10779 /// Tiny helper function to identify a no-op mask.
10780 ///
10781 /// This is a somewhat boring predicate function. It checks whether the mask
10782 /// array input, which is assumed to be a single-input shuffle mask of the kind
10783 /// used by the X86 shuffle instructions (not a fully general
10784 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
10785 /// in-place shuffle are 'no-op's.
10786 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
10787   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10788     assert(Mask[i] >= -1 && "Out of bound mask element!");
10789     if (Mask[i] >= 0 && Mask[i] != i)
10790       return false;
10791   }
10792   return true;
10793 }
10794 
10795 /// Test whether there are elements crossing LaneSizeInBits lanes in this
10796 /// shuffle mask.
10797 ///
10798 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
10799 /// and we routinely test for these.
10800 static bool isLaneCrossingShuffleMask(unsigned LaneSizeInBits,
10801                                       unsigned ScalarSizeInBits,
10802                                       ArrayRef<int> Mask) {
10803   assert(LaneSizeInBits && ScalarSizeInBits &&
10804          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10805          "Illegal shuffle lane size");
10806   int LaneSize = LaneSizeInBits / ScalarSizeInBits;
10807   int Size = Mask.size();
10808   for (int i = 0; i < Size; ++i)
10809     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10810       return true;
10811   return false;
10812 }
10813 
10814 /// Test whether there are elements crossing 128-bit lanes in this
10815 /// shuffle mask.
10816 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
10817   return isLaneCrossingShuffleMask(128, VT.getScalarSizeInBits(), Mask);
10818 }
10819 
10820 /// Test whether elements in each LaneSizeInBits lane in this shuffle mask come
10821 /// from multiple lanes - this is different to isLaneCrossingShuffleMask to
10822 /// better support 'repeated mask + lane permute' style shuffles.
10823 static bool isMultiLaneShuffleMask(unsigned LaneSizeInBits,
10824                                    unsigned ScalarSizeInBits,
10825                                    ArrayRef<int> Mask) {
10826   assert(LaneSizeInBits && ScalarSizeInBits &&
10827          (LaneSizeInBits % ScalarSizeInBits) == 0 &&
10828          "Illegal shuffle lane size");
10829   int NumElts = Mask.size();
10830   int NumEltsPerLane = LaneSizeInBits / ScalarSizeInBits;
10831   int NumLanes = NumElts / NumEltsPerLane;
10832   if (NumLanes > 1) {
10833     for (int i = 0; i != NumLanes; ++i) {
10834       int SrcLane = -1;
10835       for (int j = 0; j != NumEltsPerLane; ++j) {
10836         int M = Mask[(i * NumEltsPerLane) + j];
10837         if (M < 0)
10838           continue;
10839         int Lane = (M % NumElts) / NumEltsPerLane;
10840         if (SrcLane >= 0 && SrcLane != Lane)
10841           return true;
10842         SrcLane = Lane;
10843       }
10844     }
10845   }
10846   return false;
10847 }
10848 
10849 /// Test whether a shuffle mask is equivalent within each sub-lane.
10850 ///
10851 /// This checks a shuffle mask to see if it is performing the same
10852 /// lane-relative shuffle in each sub-lane. This trivially implies
10853 /// that it is also not lane-crossing. It may however involve a blend from the
10854 /// same lane of a second vector.
10855 ///
10856 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
10857 /// non-trivial to compute in the face of undef lanes. The representation is
10858 /// suitable for use with existing 128-bit shuffles as entries from the second
10859 /// vector have been remapped to [LaneSize, 2*LaneSize).
10860 static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
10861                                   ArrayRef<int> Mask,
10862                                   SmallVectorImpl<int> &RepeatedMask) {
10863   auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
10864   RepeatedMask.assign(LaneSize, -1);
10865   int Size = Mask.size();
10866   for (int i = 0; i < Size; ++i) {
10867     assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0);
10868     if (Mask[i] < 0)
10869       continue;
10870     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10871       // This entry crosses lanes, so there is no way to model this shuffle.
10872       return false;
10873 
10874     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10875     // Adjust second vector indices to start at LaneSize instead of Size.
10876     int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
10877                                 : Mask[i] % LaneSize + LaneSize;
10878     if (RepeatedMask[i % LaneSize] < 0)
10879       // This is the first non-undef entry in this slot of a 128-bit lane.
10880       RepeatedMask[i % LaneSize] = LocalM;
10881     else if (RepeatedMask[i % LaneSize] != LocalM)
10882       // Found a mismatch with the repeated mask.
10883       return false;
10884   }
10885   return true;
10886 }
10887 
10888 /// Test whether a shuffle mask is equivalent within each 128-bit lane.
10889 static bool
10890 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10891                                 SmallVectorImpl<int> &RepeatedMask) {
10892   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10893 }
10894 
10895 static bool
10896 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
10897   SmallVector<int, 32> RepeatedMask;
10898   return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
10899 }
10900 
10901 /// Test whether a shuffle mask is equivalent within each 256-bit lane.
10902 static bool
10903 is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
10904                                 SmallVectorImpl<int> &RepeatedMask) {
10905   return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
10906 }
10907 
10908 /// Test whether a target shuffle mask is equivalent within each sub-lane.
10909 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10910 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits,
10911                                         unsigned EltSizeInBits,
10912                                         ArrayRef<int> Mask,
10913                                         SmallVectorImpl<int> &RepeatedMask) {
10914   int LaneSize = LaneSizeInBits / EltSizeInBits;
10915   RepeatedMask.assign(LaneSize, SM_SentinelUndef);
10916   int Size = Mask.size();
10917   for (int i = 0; i < Size; ++i) {
10918     assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0));
10919     if (Mask[i] == SM_SentinelUndef)
10920       continue;
10921     if (Mask[i] == SM_SentinelZero) {
10922       if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
10923         return false;
10924       RepeatedMask[i % LaneSize] = SM_SentinelZero;
10925       continue;
10926     }
10927     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
10928       // This entry crosses lanes, so there is no way to model this shuffle.
10929       return false;
10930 
10931     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
10932     // Adjust second vector indices to start at LaneSize instead of Size.
10933     int LocalM =
10934         Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
10935     if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
10936       // This is the first non-undef entry in this slot of a 128-bit lane.
10937       RepeatedMask[i % LaneSize] = LocalM;
10938     else if (RepeatedMask[i % LaneSize] != LocalM)
10939       // Found a mismatch with the repeated mask.
10940       return false;
10941   }
10942   return true;
10943 }
10944 
10945 /// Test whether a target shuffle mask is equivalent within each sub-lane.
10946 /// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
10947 static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
10948                                         ArrayRef<int> Mask,
10949                                         SmallVectorImpl<int> &RepeatedMask) {
10950   return isRepeatedTargetShuffleMask(LaneSizeInBits, VT.getScalarSizeInBits(),
10951                                      Mask, RepeatedMask);
10952 }
10953 
10954 /// Checks whether the vector elements referenced by two shuffle masks are
10955 /// equivalent.
10956 static bool IsElementEquivalent(int MaskSize, SDValue Op, SDValue ExpectedOp,
10957                                 int Idx, int ExpectedIdx) {
10958   assert(0 <= Idx && Idx < MaskSize && 0 <= ExpectedIdx &&
10959          ExpectedIdx < MaskSize && "Out of range element index");
10960   if (!Op || !ExpectedOp || Op.getOpcode() != ExpectedOp.getOpcode())
10961     return false;
10962 
10963   switch (Op.getOpcode()) {
10964   case ISD::BUILD_VECTOR:
10965     // If the values are build vectors, we can look through them to find
10966     // equivalent inputs that make the shuffles equivalent.
10967     // TODO: Handle MaskSize != Op.getNumOperands()?
10968     if (MaskSize == (int)Op.getNumOperands() &&
10969         MaskSize == (int)ExpectedOp.getNumOperands())
10970       return Op.getOperand(Idx) == ExpectedOp.getOperand(ExpectedIdx);
10971     break;
10972   case X86ISD::VBROADCAST:
10973   case X86ISD::VBROADCAST_LOAD:
10974     // TODO: Handle MaskSize != Op.getValueType().getVectorNumElements()?
10975     return (Op == ExpectedOp &&
10976             (int)Op.getValueType().getVectorNumElements() == MaskSize);
10977   case X86ISD::HADD:
10978   case X86ISD::HSUB:
10979   case X86ISD::FHADD:
10980   case X86ISD::FHSUB:
10981   case X86ISD::PACKSS:
10982   case X86ISD::PACKUS:
10983     // HOP(X,X) can refer to the elt from the lower/upper half of a lane.
10984     // TODO: Handle MaskSize != NumElts?
10985     // TODO: Handle HOP(X,Y) vs HOP(Y,X) equivalence cases.
10986     if (Op == ExpectedOp && Op.getOperand(0) == Op.getOperand(1)) {
10987       MVT VT = Op.getSimpleValueType();
10988       int NumElts = VT.getVectorNumElements();
10989       if (MaskSize == NumElts) {
10990         int NumLanes = VT.getSizeInBits() / 128;
10991         int NumEltsPerLane = NumElts / NumLanes;
10992         int NumHalfEltsPerLane = NumEltsPerLane / 2;
10993         bool SameLane =
10994             (Idx / NumEltsPerLane) == (ExpectedIdx / NumEltsPerLane);
10995         bool SameElt =
10996             (Idx % NumHalfEltsPerLane) == (ExpectedIdx % NumHalfEltsPerLane);
10997         return SameLane && SameElt;
10998       }
10999     }
11000     break;
11001   }
11002 
11003   return false;
11004 }
11005 
11006 /// Checks whether a shuffle mask is equivalent to an explicit list of
11007 /// arguments.
11008 ///
11009 /// This is a fast way to test a shuffle mask against a fixed pattern:
11010 ///
11011 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
11012 ///
11013 /// It returns true if the mask is exactly as wide as the argument list, and
11014 /// each element of the mask is either -1 (signifying undef) or the value given
11015 /// in the argument.
11016 static bool isShuffleEquivalent(ArrayRef<int> Mask, ArrayRef<int> ExpectedMask,
11017                                 SDValue V1 = SDValue(),
11018                                 SDValue V2 = SDValue()) {
11019   int Size = Mask.size();
11020   if (Size != (int)ExpectedMask.size())
11021     return false;
11022 
11023   for (int i = 0; i < Size; ++i) {
11024     assert(Mask[i] >= -1 && "Out of bound mask element!");
11025     int MaskIdx = Mask[i];
11026     int ExpectedIdx = ExpectedMask[i];
11027     if (0 <= MaskIdx && MaskIdx != ExpectedIdx) {
11028       SDValue MaskV = MaskIdx < Size ? V1 : V2;
11029       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11030       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11031       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11032       if (!IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11033         return false;
11034     }
11035   }
11036   return true;
11037 }
11038 
11039 /// Checks whether a target shuffle mask is equivalent to an explicit pattern.
11040 ///
11041 /// The masks must be exactly the same width.
11042 ///
11043 /// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
11044 /// value in ExpectedMask is always accepted. Otherwise the indices must match.
11045 ///
11046 /// SM_SentinelZero is accepted as a valid negative index but must match in
11047 /// both.
11048 static bool isTargetShuffleEquivalent(MVT VT, ArrayRef<int> Mask,
11049                                       ArrayRef<int> ExpectedMask,
11050                                       SDValue V1 = SDValue(),
11051                                       SDValue V2 = SDValue()) {
11052   int Size = Mask.size();
11053   if (Size != (int)ExpectedMask.size())
11054     return false;
11055   assert(isUndefOrZeroOrInRange(ExpectedMask, 0, 2 * Size) &&
11056          "Illegal target shuffle mask");
11057 
11058   // Check for out-of-range target shuffle mask indices.
11059   if (!isUndefOrZeroOrInRange(Mask, 0, 2 * Size))
11060     return false;
11061 
11062   // Don't use V1/V2 if they're not the same size as the shuffle mask type.
11063   if (V1 && V1.getValueSizeInBits() != VT.getSizeInBits())
11064     V1 = SDValue();
11065   if (V2 && V2.getValueSizeInBits() != VT.getSizeInBits())
11066     V2 = SDValue();
11067 
11068   for (int i = 0; i < Size; ++i) {
11069     int MaskIdx = Mask[i];
11070     int ExpectedIdx = ExpectedMask[i];
11071     if (MaskIdx == SM_SentinelUndef || MaskIdx == ExpectedIdx)
11072       continue;
11073     if (0 <= MaskIdx && 0 <= ExpectedIdx) {
11074       SDValue MaskV = MaskIdx < Size ? V1 : V2;
11075       SDValue ExpectedV = ExpectedIdx < Size ? V1 : V2;
11076       MaskIdx = MaskIdx < Size ? MaskIdx : (MaskIdx - Size);
11077       ExpectedIdx = ExpectedIdx < Size ? ExpectedIdx : (ExpectedIdx - Size);
11078       if (IsElementEquivalent(Size, MaskV, ExpectedV, MaskIdx, ExpectedIdx))
11079         continue;
11080     }
11081     // TODO - handle SM_Sentinel equivalences.
11082     return false;
11083   }
11084   return true;
11085 }
11086 
11087 // Attempt to create a shuffle mask from a VSELECT condition mask.
11088 static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
11089                                          SDValue Cond) {
11090   EVT CondVT = Cond.getValueType();
11091   unsigned EltSizeInBits = CondVT.getScalarSizeInBits();
11092   unsigned NumElts = CondVT.getVectorNumElements();
11093 
11094   APInt UndefElts;
11095   SmallVector<APInt, 32> EltBits;
11096   if (!getTargetConstantBitsFromNode(Cond, EltSizeInBits, UndefElts, EltBits,
11097                                      true, false))
11098     return false;
11099 
11100   Mask.resize(NumElts, SM_SentinelUndef);
11101 
11102   for (int i = 0; i != (int)NumElts; ++i) {
11103     Mask[i] = i;
11104     // Arbitrarily choose from the 2nd operand if the select condition element
11105     // is undef.
11106     // TODO: Can we do better by matching patterns such as even/odd?
11107     if (UndefElts[i] || EltBits[i].isNullValue())
11108       Mask[i] += NumElts;
11109   }
11110 
11111   return true;
11112 }
11113 
11114 // Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
11115 // instructions.
11116 static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
11117   if (VT != MVT::v8i32 && VT != MVT::v8f32)
11118     return false;
11119 
11120   SmallVector<int, 8> Unpcklwd;
11121   createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
11122                           /* Unary = */ false);
11123   SmallVector<int, 8> Unpckhwd;
11124   createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
11125                           /* Unary = */ false);
11126   bool IsUnpackwdMask = (isTargetShuffleEquivalent(VT, Mask, Unpcklwd) ||
11127                          isTargetShuffleEquivalent(VT, Mask, Unpckhwd));
11128   return IsUnpackwdMask;
11129 }
11130 
11131 static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask) {
11132   // Create 128-bit vector type based on mask size.
11133   MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
11134   MVT VT = MVT::getVectorVT(EltVT, Mask.size());
11135 
11136   // We can't assume a canonical shuffle mask, so try the commuted version too.
11137   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
11138   ShuffleVectorSDNode::commuteMask(CommutedMask);
11139 
11140   // Match any of unary/binary or low/high.
11141   for (unsigned i = 0; i != 4; ++i) {
11142     SmallVector<int, 16> UnpackMask;
11143     createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
11144     if (isTargetShuffleEquivalent(VT, Mask, UnpackMask) ||
11145         isTargetShuffleEquivalent(VT, CommutedMask, UnpackMask))
11146       return true;
11147   }
11148   return false;
11149 }
11150 
11151 /// Return true if a shuffle mask chooses elements identically in its top and
11152 /// bottom halves. For example, any splat mask has the same top and bottom
11153 /// halves. If an element is undefined in only one half of the mask, the halves
11154 /// are not considered identical.
11155 static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
11156   assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask");
11157   unsigned HalfSize = Mask.size() / 2;
11158   for (unsigned i = 0; i != HalfSize; ++i) {
11159     if (Mask[i] != Mask[i + HalfSize])
11160       return false;
11161   }
11162   return true;
11163 }
11164 
11165 /// Get a 4-lane 8-bit shuffle immediate for a mask.
11166 ///
11167 /// This helper function produces an 8-bit shuffle immediate corresponding to
11168 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
11169 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
11170 /// example.
11171 ///
11172 /// NB: We rely heavily on "undef" masks preserving the input lane.
11173 static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
11174   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
11175   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
11176   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
11177   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
11178   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
11179 
11180   // If the mask only uses one non-undef element, then fully 'splat' it to
11181   // improve later broadcast matching.
11182   int FirstIndex = find_if(Mask, [](int M) { return M >= 0; }) - Mask.begin();
11183   assert(0 <= FirstIndex && FirstIndex < 4 && "All undef shuffle mask");
11184 
11185   int FirstElt = Mask[FirstIndex];
11186   if (all_of(Mask, [FirstElt](int M) { return M < 0 || M == FirstElt; }))
11187     return (FirstElt << 6) | (FirstElt << 4) | (FirstElt << 2) | FirstElt;
11188 
11189   unsigned Imm = 0;
11190   Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
11191   Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
11192   Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
11193   Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
11194   return Imm;
11195 }
11196 
11197 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
11198                                           SelectionDAG &DAG) {
11199   return DAG.getTargetConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
11200 }
11201 
11202 // The Shuffle result is as follow:
11203 // 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
11204 // Each Zeroable's element correspond to a particular Mask's element.
11205 // As described in computeZeroableShuffleElements function.
11206 //
11207 // The function looks for a sub-mask that the nonzero elements are in
11208 // increasing order. If such sub-mask exist. The function returns true.
11209 static bool isNonZeroElementsInOrder(const APInt &Zeroable,
11210                                      ArrayRef<int> Mask, const EVT &VectorType,
11211                                      bool &IsZeroSideLeft) {
11212   int NextElement = -1;
11213   // Check if the Mask's nonzero elements are in increasing order.
11214   for (int i = 0, e = Mask.size(); i < e; i++) {
11215     // Checks if the mask's zeros elements are built from only zeros.
11216     assert(Mask[i] >= -1 && "Out of bound mask element!");
11217     if (Mask[i] < 0)
11218       return false;
11219     if (Zeroable[i])
11220       continue;
11221     // Find the lowest non zero element
11222     if (NextElement < 0) {
11223       NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
11224       IsZeroSideLeft = NextElement != 0;
11225     }
11226     // Exit if the mask's non zero elements are not in increasing order.
11227     if (NextElement != Mask[i])
11228       return false;
11229     NextElement++;
11230   }
11231   return true;
11232 }
11233 
11234 /// Try to lower a shuffle with a single PSHUFB of V1 or V2.
11235 static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
11236                                       ArrayRef<int> Mask, SDValue V1,
11237                                       SDValue V2, const APInt &Zeroable,
11238                                       const X86Subtarget &Subtarget,
11239                                       SelectionDAG &DAG) {
11240   int Size = Mask.size();
11241   int LaneSize = 128 / VT.getScalarSizeInBits();
11242   const int NumBytes = VT.getSizeInBits() / 8;
11243   const int NumEltBytes = VT.getScalarSizeInBits() / 8;
11244 
11245   assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||
11246          (Subtarget.hasAVX2() && VT.is256BitVector()) ||
11247          (Subtarget.hasBWI() && VT.is512BitVector()));
11248 
11249   SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
11250   // Sign bit set in i8 mask means zero element.
11251   SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
11252 
11253   SDValue V;
11254   for (int i = 0; i < NumBytes; ++i) {
11255     int M = Mask[i / NumEltBytes];
11256     if (M < 0) {
11257       PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
11258       continue;
11259     }
11260     if (Zeroable[i / NumEltBytes]) {
11261       PSHUFBMask[i] = ZeroMask;
11262       continue;
11263     }
11264 
11265     // We can only use a single input of V1 or V2.
11266     SDValue SrcV = (M >= Size ? V2 : V1);
11267     if (V && V != SrcV)
11268       return SDValue();
11269     V = SrcV;
11270     M %= Size;
11271 
11272     // PSHUFB can't cross lanes, ensure this doesn't happen.
11273     if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
11274       return SDValue();
11275 
11276     M = M % LaneSize;
11277     M = M * NumEltBytes + (i % NumEltBytes);
11278     PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
11279   }
11280   assert(V && "Failed to find a source input");
11281 
11282   MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
11283   return DAG.getBitcast(
11284       VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
11285                       DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
11286 }
11287 
11288 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
11289                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
11290                            const SDLoc &dl);
11291 
11292 // X86 has dedicated shuffle that can be lowered to VEXPAND
11293 static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
11294                                     const APInt &Zeroable,
11295                                     ArrayRef<int> Mask, SDValue &V1,
11296                                     SDValue &V2, SelectionDAG &DAG,
11297                                     const X86Subtarget &Subtarget) {
11298   bool IsLeftZeroSide = true;
11299   if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
11300                                 IsLeftZeroSide))
11301     return SDValue();
11302   unsigned VEXPANDMask = (~Zeroable).getZExtValue();
11303   MVT IntegerType =
11304       MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
11305   SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
11306   unsigned NumElts = VT.getVectorNumElements();
11307   assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&
11308          "Unexpected number of vector elements");
11309   SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
11310                               Subtarget, DAG, DL);
11311   SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
11312   SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
11313   return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
11314 }
11315 
11316 static bool matchShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
11317                                   unsigned &UnpackOpcode, bool IsUnary,
11318                                   ArrayRef<int> TargetMask, const SDLoc &DL,
11319                                   SelectionDAG &DAG,
11320                                   const X86Subtarget &Subtarget) {
11321   int NumElts = VT.getVectorNumElements();
11322 
11323   bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
11324   for (int i = 0; i != NumElts; i += 2) {
11325     int M1 = TargetMask[i + 0];
11326     int M2 = TargetMask[i + 1];
11327     Undef1 &= (SM_SentinelUndef == M1);
11328     Undef2 &= (SM_SentinelUndef == M2);
11329     Zero1 &= isUndefOrZero(M1);
11330     Zero2 &= isUndefOrZero(M2);
11331   }
11332   assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
11333          "Zeroable shuffle detected");
11334 
11335   // Attempt to match the target mask against the unpack lo/hi mask patterns.
11336   SmallVector<int, 64> Unpckl, Unpckh;
11337   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
11338   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl, V1,
11339                                 (IsUnary ? V1 : V2))) {
11340     UnpackOpcode = X86ISD::UNPCKL;
11341     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11342     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11343     return true;
11344   }
11345 
11346   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
11347   if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh, V1,
11348                                 (IsUnary ? V1 : V2))) {
11349     UnpackOpcode = X86ISD::UNPCKH;
11350     V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
11351     V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
11352     return true;
11353   }
11354 
11355   // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
11356   if (IsUnary && (Zero1 || Zero2)) {
11357     // Don't bother if we can blend instead.
11358     if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
11359         isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
11360       return false;
11361 
11362     bool MatchLo = true, MatchHi = true;
11363     for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
11364       int M = TargetMask[i];
11365 
11366       // Ignore if the input is known to be zero or the index is undef.
11367       if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
11368           (M == SM_SentinelUndef))
11369         continue;
11370 
11371       MatchLo &= (M == Unpckl[i]);
11372       MatchHi &= (M == Unpckh[i]);
11373     }
11374 
11375     if (MatchLo || MatchHi) {
11376       UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
11377       V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11378       V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
11379       return true;
11380     }
11381   }
11382 
11383   // If a binary shuffle, commute and try again.
11384   if (!IsUnary) {
11385     ShuffleVectorSDNode::commuteMask(Unpckl);
11386     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckl)) {
11387       UnpackOpcode = X86ISD::UNPCKL;
11388       std::swap(V1, V2);
11389       return true;
11390     }
11391 
11392     ShuffleVectorSDNode::commuteMask(Unpckh);
11393     if (isTargetShuffleEquivalent(VT, TargetMask, Unpckh)) {
11394       UnpackOpcode = X86ISD::UNPCKH;
11395       std::swap(V1, V2);
11396       return true;
11397     }
11398   }
11399 
11400   return false;
11401 }
11402 
11403 // X86 has dedicated unpack instructions that can handle specific blend
11404 // operations: UNPCKH and UNPCKL.
11405 static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
11406                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
11407                                      SelectionDAG &DAG) {
11408   SmallVector<int, 8> Unpckl;
11409   createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
11410   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11411     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
11412 
11413   SmallVector<int, 8> Unpckh;
11414   createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
11415   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11416     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
11417 
11418   // Commute and try again.
11419   ShuffleVectorSDNode::commuteMask(Unpckl);
11420   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11421     return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
11422 
11423   ShuffleVectorSDNode::commuteMask(Unpckh);
11424   if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11425     return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
11426 
11427   return SDValue();
11428 }
11429 
11430 /// Check if the mask can be mapped to a preliminary shuffle (vperm 64-bit)
11431 /// followed by unpack 256-bit.
11432 static SDValue lowerShuffleWithUNPCK256(const SDLoc &DL, MVT VT,
11433                                         ArrayRef<int> Mask, SDValue V1,
11434                                         SDValue V2, SelectionDAG &DAG) {
11435   SmallVector<int, 32> Unpckl, Unpckh;
11436   createSplat2ShuffleMask(VT, Unpckl, /* Lo */ true);
11437   createSplat2ShuffleMask(VT, Unpckh, /* Lo */ false);
11438 
11439   unsigned UnpackOpcode;
11440   if (isShuffleEquivalent(Mask, Unpckl, V1, V2))
11441     UnpackOpcode = X86ISD::UNPCKL;
11442   else if (isShuffleEquivalent(Mask, Unpckh, V1, V2))
11443     UnpackOpcode = X86ISD::UNPCKH;
11444   else
11445     return SDValue();
11446 
11447   // This is a "natural" unpack operation (rather than the 128-bit sectored
11448   // operation implemented by AVX). We need to rearrange 64-bit chunks of the
11449   // input in order to use the x86 instruction.
11450   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, DAG.getBitcast(MVT::v4f64, V1),
11451                             DAG.getUNDEF(MVT::v4f64), {0, 2, 1, 3});
11452   V1 = DAG.getBitcast(VT, V1);
11453   return DAG.getNode(UnpackOpcode, DL, VT, V1, V1);
11454 }
11455 
11456 // Check if the mask can be mapped to a TRUNCATE or VTRUNC, truncating the
11457 // source into the lower elements and zeroing the upper elements.
11458 static bool matchShuffleAsVTRUNC(MVT &SrcVT, MVT &DstVT, MVT VT,
11459                                  ArrayRef<int> Mask, const APInt &Zeroable,
11460                                  const X86Subtarget &Subtarget) {
11461   if (!VT.is512BitVector() && !Subtarget.hasVLX())
11462     return false;
11463 
11464   unsigned NumElts = Mask.size();
11465   unsigned EltSizeInBits = VT.getScalarSizeInBits();
11466   unsigned MaxScale = 64 / EltSizeInBits;
11467 
11468   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11469     unsigned SrcEltBits = EltSizeInBits * Scale;
11470     if (SrcEltBits < 32 && !Subtarget.hasBWI())
11471       continue;
11472     unsigned NumSrcElts = NumElts / Scale;
11473     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale))
11474       continue;
11475     unsigned UpperElts = NumElts - NumSrcElts;
11476     if (!Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11477       continue;
11478     SrcVT = MVT::getIntegerVT(EltSizeInBits * Scale);
11479     SrcVT = MVT::getVectorVT(SrcVT, NumSrcElts);
11480     DstVT = MVT::getIntegerVT(EltSizeInBits);
11481     if ((NumSrcElts * EltSizeInBits) >= 128) {
11482       // ISD::TRUNCATE
11483       DstVT = MVT::getVectorVT(DstVT, NumSrcElts);
11484     } else {
11485       // X86ISD::VTRUNC
11486       DstVT = MVT::getVectorVT(DstVT, 128 / EltSizeInBits);
11487     }
11488     return true;
11489   }
11490 
11491   return false;
11492 }
11493 
11494 // Helper to create TRUNCATE/VTRUNC nodes, optionally with zero/undef upper
11495 // element padding to the final DstVT.
11496 static SDValue getAVX512TruncNode(const SDLoc &DL, MVT DstVT, SDValue Src,
11497                                   const X86Subtarget &Subtarget,
11498                                   SelectionDAG &DAG, bool ZeroUppers) {
11499   MVT SrcVT = Src.getSimpleValueType();
11500   MVT DstSVT = DstVT.getScalarType();
11501   unsigned NumDstElts = DstVT.getVectorNumElements();
11502   unsigned NumSrcElts = SrcVT.getVectorNumElements();
11503   unsigned DstEltSizeInBits = DstVT.getScalarSizeInBits();
11504 
11505   if (!DAG.getTargetLoweringInfo().isTypeLegal(SrcVT))
11506     return SDValue();
11507 
11508   // Perform a direct ISD::TRUNCATE if possible.
11509   if (NumSrcElts == NumDstElts)
11510     return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
11511 
11512   if (NumSrcElts > NumDstElts) {
11513     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
11514     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
11515     return extractSubVector(Trunc, 0, DAG, DL, DstVT.getSizeInBits());
11516   }
11517 
11518   if ((NumSrcElts * DstEltSizeInBits) >= 128) {
11519     MVT TruncVT = MVT::getVectorVT(DstSVT, NumSrcElts);
11520     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Src);
11521     return widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
11522                           DstVT.getSizeInBits());
11523   }
11524 
11525   // Non-VLX targets must truncate from a 512-bit type, so we need to
11526   // widen, truncate and then possibly extract the original subvector.
11527   if (!Subtarget.hasVLX() && !SrcVT.is512BitVector()) {
11528     SDValue NewSrc = widenSubVector(Src, ZeroUppers, Subtarget, DAG, DL, 512);
11529     return getAVX512TruncNode(DL, DstVT, NewSrc, Subtarget, DAG, ZeroUppers);
11530   }
11531 
11532   // Fallback to a X86ISD::VTRUNC, padding if necessary.
11533   MVT TruncVT = MVT::getVectorVT(DstSVT, 128 / DstEltSizeInBits);
11534   SDValue Trunc = DAG.getNode(X86ISD::VTRUNC, DL, TruncVT, Src);
11535   if (DstVT != TruncVT)
11536     Trunc = widenSubVector(Trunc, ZeroUppers, Subtarget, DAG, DL,
11537                            DstVT.getSizeInBits());
11538   return Trunc;
11539 }
11540 
11541 // Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
11542 //
11543 // An example is the following:
11544 //
11545 // t0: ch = EntryToken
11546 //           t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
11547 //         t25: v4i32 = truncate t2
11548 //       t41: v8i16 = bitcast t25
11549 //       t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
11550 //       Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
11551 //     t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
11552 //   t18: v2i64 = bitcast t51
11553 //
11554 // One can just use a single vpmovdw instruction, without avx512vl we need to
11555 // use the zmm variant and extract the lower subvector, padding with zeroes.
11556 // TODO: Merge with lowerShuffleAsVTRUNC.
11557 static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, MVT VT, SDValue V1,
11558                                      SDValue V2, ArrayRef<int> Mask,
11559                                      const APInt &Zeroable,
11560                                      const X86Subtarget &Subtarget,
11561                                      SelectionDAG &DAG) {
11562   assert((VT == MVT::v16i8 || VT == MVT::v8i16) && "Unexpected VTRUNC type");
11563   if (!Subtarget.hasAVX512())
11564     return SDValue();
11565 
11566   unsigned NumElts = VT.getVectorNumElements();
11567   unsigned EltSizeInBits = VT.getScalarSizeInBits();
11568   unsigned MaxScale = 64 / EltSizeInBits;
11569   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11570     unsigned NumSrcElts = NumElts / Scale;
11571     unsigned UpperElts = NumElts - NumSrcElts;
11572     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
11573         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11574       continue;
11575 
11576     SDValue Src = V1;
11577     if (!Src.hasOneUse())
11578       return SDValue();
11579 
11580     Src = peekThroughOneUseBitcasts(Src);
11581     if (Src.getOpcode() != ISD::TRUNCATE ||
11582         Src.getScalarValueSizeInBits() != (EltSizeInBits * Scale))
11583       return SDValue();
11584     Src = Src.getOperand(0);
11585 
11586     // VPMOVWB is only available with avx512bw.
11587     MVT SrcVT = Src.getSimpleValueType();
11588     if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
11589         !Subtarget.hasBWI())
11590       return SDValue();
11591 
11592     bool UndefUppers = isUndefInRange(Mask, NumSrcElts, UpperElts);
11593     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11594   }
11595 
11596   return SDValue();
11597 }
11598 
11599 // Attempt to match binary shuffle patterns as a truncate.
11600 static SDValue lowerShuffleAsVTRUNC(const SDLoc &DL, MVT VT, SDValue V1,
11601                                     SDValue V2, ArrayRef<int> Mask,
11602                                     const APInt &Zeroable,
11603                                     const X86Subtarget &Subtarget,
11604                                     SelectionDAG &DAG) {
11605   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11606          "Unexpected VTRUNC type");
11607   if (!Subtarget.hasAVX512())
11608     return SDValue();
11609 
11610   unsigned NumElts = VT.getVectorNumElements();
11611   unsigned EltSizeInBits = VT.getScalarSizeInBits();
11612   unsigned MaxScale = 64 / EltSizeInBits;
11613   for (unsigned Scale = 2; Scale <= MaxScale; Scale += Scale) {
11614     // TODO: Support non-BWI VPMOVWB truncations?
11615     unsigned SrcEltBits = EltSizeInBits * Scale;
11616     if (SrcEltBits < 32 && !Subtarget.hasBWI())
11617       continue;
11618 
11619     // Match shuffle <0,Scale,2*Scale,..,undef_or_zero,undef_or_zero,...>
11620     // Bail if the V2 elements are undef.
11621     unsigned NumHalfSrcElts = NumElts / Scale;
11622     unsigned NumSrcElts = 2 * NumHalfSrcElts;
11623     if (!isSequentialOrUndefInRange(Mask, 0, NumSrcElts, 0, Scale) ||
11624         isUndefInRange(Mask, NumHalfSrcElts, NumHalfSrcElts))
11625       continue;
11626 
11627     // The elements beyond the truncation must be undef/zero.
11628     unsigned UpperElts = NumElts - NumSrcElts;
11629     if (UpperElts > 0 &&
11630         !Zeroable.extractBits(UpperElts, NumSrcElts).isAllOnesValue())
11631       continue;
11632     bool UndefUppers =
11633         UpperElts > 0 && isUndefInRange(Mask, NumSrcElts, UpperElts);
11634 
11635     // As we're using both sources then we need to concat them together
11636     // and truncate from the double-sized src.
11637     MVT ConcatVT = MVT::getVectorVT(VT.getScalarType(), NumElts * 2);
11638     SDValue Src = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatVT, V1, V2);
11639 
11640     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11641     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11642     Src = DAG.getBitcast(SrcVT, Src);
11643     return getAVX512TruncNode(DL, VT, Src, Subtarget, DAG, !UndefUppers);
11644   }
11645 
11646   return SDValue();
11647 }
11648 
11649 /// Check whether a compaction lowering can be done by dropping even
11650 /// elements and compute how many times even elements must be dropped.
11651 ///
11652 /// This handles shuffles which take every Nth element where N is a power of
11653 /// two. Example shuffle masks:
11654 ///
11655 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
11656 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
11657 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
11658 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
11659 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
11660 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
11661 ///
11662 /// Any of these lanes can of course be undef.
11663 ///
11664 /// This routine only supports N <= 3.
11665 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
11666 /// for larger N.
11667 ///
11668 /// \returns N above, or the number of times even elements must be dropped if
11669 /// there is such a number. Otherwise returns zero.
11670 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
11671                                           bool IsSingleInput) {
11672   // The modulus for the shuffle vector entries is based on whether this is
11673   // a single input or not.
11674   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
11675   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
11676          "We should only be called with masks with a power-of-2 size!");
11677 
11678   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
11679 
11680   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
11681   // and 2^3 simultaneously. This is because we may have ambiguity with
11682   // partially undef inputs.
11683   bool ViableForN[3] = {true, true, true};
11684 
11685   for (int i = 0, e = Mask.size(); i < e; ++i) {
11686     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
11687     // want.
11688     if (Mask[i] < 0)
11689       continue;
11690 
11691     bool IsAnyViable = false;
11692     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
11693       if (ViableForN[j]) {
11694         uint64_t N = j + 1;
11695 
11696         // The shuffle mask must be equal to (i * 2^N) % M.
11697         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
11698           IsAnyViable = true;
11699         else
11700           ViableForN[j] = false;
11701       }
11702     // Early exit if we exhaust the possible powers of two.
11703     if (!IsAnyViable)
11704       break;
11705   }
11706 
11707   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
11708     if (ViableForN[j])
11709       return j + 1;
11710 
11711   // Return 0 as there is no viable power of two.
11712   return 0;
11713 }
11714 
11715 // X86 has dedicated pack instructions that can handle specific truncation
11716 // operations: PACKSS and PACKUS.
11717 // Checks for compaction shuffle masks if MaxStages > 1.
11718 // TODO: Add support for matching multiple PACKSS/PACKUS stages.
11719 static bool matchShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1, SDValue &V2,
11720                                  unsigned &PackOpcode, ArrayRef<int> TargetMask,
11721                                  SelectionDAG &DAG,
11722                                  const X86Subtarget &Subtarget,
11723                                  unsigned MaxStages = 1) {
11724   unsigned NumElts = VT.getVectorNumElements();
11725   unsigned BitSize = VT.getScalarSizeInBits();
11726   assert(0 < MaxStages && MaxStages <= 3 && (BitSize << MaxStages) <= 64 &&
11727          "Illegal maximum compaction");
11728 
11729   auto MatchPACK = [&](SDValue N1, SDValue N2, MVT PackVT) {
11730     unsigned NumSrcBits = PackVT.getScalarSizeInBits();
11731     unsigned NumPackedBits = NumSrcBits - BitSize;
11732     SDValue VV1 = DAG.getBitcast(PackVT, N1);
11733     SDValue VV2 = DAG.getBitcast(PackVT, N2);
11734     if (Subtarget.hasSSE41() || BitSize == 8) {
11735       APInt ZeroMask = APInt::getHighBitsSet(NumSrcBits, NumPackedBits);
11736       if ((N1.isUndef() || DAG.MaskedValueIsZero(VV1, ZeroMask)) &&
11737           (N2.isUndef() || DAG.MaskedValueIsZero(VV2, ZeroMask))) {
11738         V1 = VV1;
11739         V2 = VV2;
11740         SrcVT = PackVT;
11741         PackOpcode = X86ISD::PACKUS;
11742         return true;
11743       }
11744     }
11745     if ((N1.isUndef() || DAG.ComputeNumSignBits(VV1) > NumPackedBits) &&
11746         (N2.isUndef() || DAG.ComputeNumSignBits(VV2) > NumPackedBits)) {
11747       V1 = VV1;
11748       V2 = VV2;
11749       SrcVT = PackVT;
11750       PackOpcode = X86ISD::PACKSS;
11751       return true;
11752     }
11753     return false;
11754   };
11755 
11756   // Attempt to match against wider and wider compaction patterns.
11757   for (unsigned NumStages = 1; NumStages <= MaxStages; ++NumStages) {
11758     MVT PackSVT = MVT::getIntegerVT(BitSize << NumStages);
11759     MVT PackVT = MVT::getVectorVT(PackSVT, NumElts >> NumStages);
11760 
11761     // Try binary shuffle.
11762     SmallVector<int, 32> BinaryMask;
11763     createPackShuffleMask(VT, BinaryMask, false, NumStages);
11764     if (isTargetShuffleEquivalent(VT, TargetMask, BinaryMask, V1, V2))
11765       if (MatchPACK(V1, V2, PackVT))
11766         return true;
11767 
11768     // Try unary shuffle.
11769     SmallVector<int, 32> UnaryMask;
11770     createPackShuffleMask(VT, UnaryMask, true, NumStages);
11771     if (isTargetShuffleEquivalent(VT, TargetMask, UnaryMask, V1))
11772       if (MatchPACK(V1, V1, PackVT))
11773         return true;
11774   }
11775 
11776   return false;
11777 }
11778 
11779 static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
11780                                     SDValue V1, SDValue V2, SelectionDAG &DAG,
11781                                     const X86Subtarget &Subtarget) {
11782   MVT PackVT;
11783   unsigned PackOpcode;
11784   unsigned SizeBits = VT.getSizeInBits();
11785   unsigned EltBits = VT.getScalarSizeInBits();
11786   unsigned MaxStages = Log2_32(64 / EltBits);
11787   if (!matchShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
11788                             Subtarget, MaxStages))
11789     return SDValue();
11790 
11791   unsigned CurrentEltBits = PackVT.getScalarSizeInBits();
11792   unsigned NumStages = Log2_32(CurrentEltBits / EltBits);
11793 
11794   // Don't lower multi-stage packs on AVX512, truncation is better.
11795   if (NumStages != 1 && SizeBits == 128 && Subtarget.hasVLX())
11796     return SDValue();
11797 
11798   // Pack to the largest type possible:
11799   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
11800   unsigned MaxPackBits = 16;
11801   if (CurrentEltBits > 16 &&
11802       (PackOpcode == X86ISD::PACKSS || Subtarget.hasSSE41()))
11803     MaxPackBits = 32;
11804 
11805   // Repeatedly pack down to the target size.
11806   SDValue Res;
11807   for (unsigned i = 0; i != NumStages; ++i) {
11808     unsigned SrcEltBits = std::min(MaxPackBits, CurrentEltBits);
11809     unsigned NumSrcElts = SizeBits / SrcEltBits;
11810     MVT SrcSVT = MVT::getIntegerVT(SrcEltBits);
11811     MVT DstSVT = MVT::getIntegerVT(SrcEltBits / 2);
11812     MVT SrcVT = MVT::getVectorVT(SrcSVT, NumSrcElts);
11813     MVT DstVT = MVT::getVectorVT(DstSVT, NumSrcElts * 2);
11814     Res = DAG.getNode(PackOpcode, DL, DstVT, DAG.getBitcast(SrcVT, V1),
11815                       DAG.getBitcast(SrcVT, V2));
11816     V1 = V2 = Res;
11817     CurrentEltBits /= 2;
11818   }
11819   assert(Res && Res.getValueType() == VT &&
11820          "Failed to lower compaction shuffle");
11821   return Res;
11822 }
11823 
11824 /// Try to emit a bitmask instruction for a shuffle.
11825 ///
11826 /// This handles cases where we can model a blend exactly as a bitmask due to
11827 /// one of the inputs being zeroable.
11828 static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
11829                                      SDValue V2, ArrayRef<int> Mask,
11830                                      const APInt &Zeroable,
11831                                      const X86Subtarget &Subtarget,
11832                                      SelectionDAG &DAG) {
11833   MVT MaskVT = VT;
11834   MVT EltVT = VT.getVectorElementType();
11835   SDValue Zero, AllOnes;
11836   // Use f64 if i64 isn't legal.
11837   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
11838     EltVT = MVT::f64;
11839     MaskVT = MVT::getVectorVT(EltVT, Mask.size());
11840   }
11841 
11842   MVT LogicVT = VT;
11843   if (EltVT == MVT::f32 || EltVT == MVT::f64) {
11844     Zero = DAG.getConstantFP(0.0, DL, EltVT);
11845     APFloat AllOnesValue = APFloat::getAllOnesValue(
11846         SelectionDAG::EVTToAPFloatSemantics(EltVT), EltVT.getSizeInBits());
11847     AllOnes = DAG.getConstantFP(AllOnesValue, DL, EltVT);
11848     LogicVT =
11849         MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
11850   } else {
11851     Zero = DAG.getConstant(0, DL, EltVT);
11852     AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11853   }
11854 
11855   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
11856   SDValue V;
11857   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11858     if (Zeroable[i])
11859       continue;
11860     if (Mask[i] % Size != i)
11861       return SDValue(); // Not a blend.
11862     if (!V)
11863       V = Mask[i] < Size ? V1 : V2;
11864     else if (V != (Mask[i] < Size ? V1 : V2))
11865       return SDValue(); // Can only let one input through the mask.
11866 
11867     VMaskOps[i] = AllOnes;
11868   }
11869   if (!V)
11870     return SDValue(); // No non-zeroable elements!
11871 
11872   SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
11873   VMask = DAG.getBitcast(LogicVT, VMask);
11874   V = DAG.getBitcast(LogicVT, V);
11875   SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
11876   return DAG.getBitcast(VT, And);
11877 }
11878 
11879 /// Try to emit a blend instruction for a shuffle using bit math.
11880 ///
11881 /// This is used as a fallback approach when first class blend instructions are
11882 /// unavailable. Currently it is only suitable for integer vectors, but could
11883 /// be generalized for floating point vectors if desirable.
11884 static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
11885                                       SDValue V2, ArrayRef<int> Mask,
11886                                       SelectionDAG &DAG) {
11887   assert(VT.isInteger() && "Only supports integer vector types!");
11888   MVT EltVT = VT.getVectorElementType();
11889   SDValue Zero = DAG.getConstant(0, DL, EltVT);
11890   SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
11891   SmallVector<SDValue, 16> MaskOps;
11892   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11893     if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
11894       return SDValue(); // Shuffled input!
11895     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
11896   }
11897 
11898   SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
11899   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
11900   V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
11901   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
11902 }
11903 
11904 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
11905                                     SDValue PreservedSrc,
11906                                     const X86Subtarget &Subtarget,
11907                                     SelectionDAG &DAG);
11908 
11909 static bool matchShuffleAsBlend(SDValue V1, SDValue V2,
11910                                 MutableArrayRef<int> Mask,
11911                                 const APInt &Zeroable, bool &ForceV1Zero,
11912                                 bool &ForceV2Zero, uint64_t &BlendMask) {
11913   bool V1IsZeroOrUndef =
11914       V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
11915   bool V2IsZeroOrUndef =
11916       V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
11917 
11918   BlendMask = 0;
11919   ForceV1Zero = false, ForceV2Zero = false;
11920   assert(Mask.size() <= 64 && "Shuffle mask too big for blend mask");
11921 
11922   // Attempt to generate the binary blend mask. If an input is zero then
11923   // we can use any lane.
11924   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
11925     int M = Mask[i];
11926     if (M == SM_SentinelUndef)
11927       continue;
11928     if (M == i)
11929       continue;
11930     if (M == i + Size) {
11931       BlendMask |= 1ull << i;
11932       continue;
11933     }
11934     if (Zeroable[i]) {
11935       if (V1IsZeroOrUndef) {
11936         ForceV1Zero = true;
11937         Mask[i] = i;
11938         continue;
11939       }
11940       if (V2IsZeroOrUndef) {
11941         ForceV2Zero = true;
11942         BlendMask |= 1ull << i;
11943         Mask[i] = i + Size;
11944         continue;
11945       }
11946     }
11947     return false;
11948   }
11949   return true;
11950 }
11951 
11952 static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
11953                                             int Scale) {
11954   uint64_t ScaledMask = 0;
11955   for (int i = 0; i != Size; ++i)
11956     if (BlendMask & (1ull << i))
11957       ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
11958   return ScaledMask;
11959 }
11960 
11961 /// Try to emit a blend instruction for a shuffle.
11962 ///
11963 /// This doesn't do any checks for the availability of instructions for blending
11964 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
11965 /// be matched in the backend with the type given. What it does check for is
11966 /// that the shuffle mask is a blend, or convertible into a blend with zero.
11967 static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
11968                                    SDValue V2, ArrayRef<int> Original,
11969                                    const APInt &Zeroable,
11970                                    const X86Subtarget &Subtarget,
11971                                    SelectionDAG &DAG) {
11972   uint64_t BlendMask = 0;
11973   bool ForceV1Zero = false, ForceV2Zero = false;
11974   SmallVector<int, 64> Mask(Original.begin(), Original.end());
11975   if (!matchShuffleAsBlend(V1, V2, Mask, Zeroable, ForceV1Zero, ForceV2Zero,
11976                            BlendMask))
11977     return SDValue();
11978 
11979   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
11980   if (ForceV1Zero)
11981     V1 = getZeroVector(VT, Subtarget, DAG, DL);
11982   if (ForceV2Zero)
11983     V2 = getZeroVector(VT, Subtarget, DAG, DL);
11984 
11985   switch (VT.SimpleTy) {
11986   case MVT::v4i64:
11987   case MVT::v8i32:
11988     assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!");
11989     LLVM_FALLTHROUGH;
11990   case MVT::v4f64:
11991   case MVT::v8f32:
11992     assert(Subtarget.hasAVX() && "256-bit float blends require AVX!");
11993     LLVM_FALLTHROUGH;
11994   case MVT::v2f64:
11995   case MVT::v2i64:
11996   case MVT::v4f32:
11997   case MVT::v4i32:
11998   case MVT::v8i16:
11999     assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!");
12000     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
12001                        DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12002   case MVT::v16i16: {
12003     assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!");
12004     SmallVector<int, 8> RepeatedMask;
12005     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
12006       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
12007       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
12008       BlendMask = 0;
12009       for (int i = 0; i < 8; ++i)
12010         if (RepeatedMask[i] >= 8)
12011           BlendMask |= 1ull << i;
12012       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12013                          DAG.getTargetConstant(BlendMask, DL, MVT::i8));
12014     }
12015     // Use PBLENDW for lower/upper lanes and then blend lanes.
12016     // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
12017     // merge to VSELECT where useful.
12018     uint64_t LoMask = BlendMask & 0xFF;
12019     uint64_t HiMask = (BlendMask >> 8) & 0xFF;
12020     if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
12021       SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12022                                DAG.getTargetConstant(LoMask, DL, MVT::i8));
12023       SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
12024                                DAG.getTargetConstant(HiMask, DL, MVT::i8));
12025       return DAG.getVectorShuffle(
12026           MVT::v16i16, DL, Lo, Hi,
12027           {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
12028     }
12029     LLVM_FALLTHROUGH;
12030   }
12031   case MVT::v32i8:
12032     assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!");
12033     LLVM_FALLTHROUGH;
12034   case MVT::v16i8: {
12035     assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!");
12036 
12037     // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
12038     if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12039                                                Subtarget, DAG))
12040       return Masked;
12041 
12042     if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
12043       MVT IntegerType =
12044           MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12045       SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12046       return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12047     }
12048 
12049     // If we have VPTERNLOG, we can use that as a bit blend.
12050     if (Subtarget.hasVLX())
12051       if (SDValue BitBlend =
12052               lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
12053         return BitBlend;
12054 
12055     // Scale the blend by the number of bytes per element.
12056     int Scale = VT.getScalarSizeInBits() / 8;
12057 
12058     // This form of blend is always done on bytes. Compute the byte vector
12059     // type.
12060     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12061 
12062     // x86 allows load folding with blendvb from the 2nd source operand. But
12063     // we are still using LLVM select here (see comment below), so that's V1.
12064     // If V2 can be load-folded and V1 cannot be load-folded, then commute to
12065     // allow that load-folding possibility.
12066     if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
12067       ShuffleVectorSDNode::commuteMask(Mask);
12068       std::swap(V1, V2);
12069     }
12070 
12071     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
12072     // mix of LLVM's code generator and the x86 backend. We tell the code
12073     // generator that boolean values in the elements of an x86 vector register
12074     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
12075     // mapping a select to operand #1, and 'false' mapping to operand #2. The
12076     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
12077     // of the element (the remaining are ignored) and 0 in that high bit would
12078     // mean operand #1 while 1 in the high bit would mean operand #2. So while
12079     // the LLVM model for boolean values in vector elements gets the relevant
12080     // bit set, it is set backwards and over constrained relative to x86's
12081     // actual model.
12082     SmallVector<SDValue, 32> VSELECTMask;
12083     for (int i = 0, Size = Mask.size(); i < Size; ++i)
12084       for (int j = 0; j < Scale; ++j)
12085         VSELECTMask.push_back(
12086             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
12087                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
12088                                           MVT::i8));
12089 
12090     V1 = DAG.getBitcast(BlendVT, V1);
12091     V2 = DAG.getBitcast(BlendVT, V2);
12092     return DAG.getBitcast(
12093         VT,
12094         DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
12095                       V1, V2));
12096   }
12097   case MVT::v16f32:
12098   case MVT::v8f64:
12099   case MVT::v8i64:
12100   case MVT::v16i32:
12101   case MVT::v32i16:
12102   case MVT::v64i8: {
12103     // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
12104     bool OptForSize = DAG.shouldOptForSize();
12105     if (!OptForSize) {
12106       if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
12107                                                  Subtarget, DAG))
12108         return Masked;
12109     }
12110 
12111     // Otherwise load an immediate into a GPR, cast to k-register, and use a
12112     // masked move.
12113     MVT IntegerType =
12114         MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
12115     SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
12116     return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
12117   }
12118   default:
12119     llvm_unreachable("Not a supported integer vector type!");
12120   }
12121 }
12122 
12123 /// Try to lower as a blend of elements from two inputs followed by
12124 /// a single-input permutation.
12125 ///
12126 /// This matches the pattern where we can blend elements from two inputs and
12127 /// then reduce the shuffle to a single-input permutation.
12128 static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
12129                                              SDValue V1, SDValue V2,
12130                                              ArrayRef<int> Mask,
12131                                              SelectionDAG &DAG,
12132                                              bool ImmBlends = false) {
12133   // We build up the blend mask while checking whether a blend is a viable way
12134   // to reduce the shuffle.
12135   SmallVector<int, 32> BlendMask(Mask.size(), -1);
12136   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
12137 
12138   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
12139     if (Mask[i] < 0)
12140       continue;
12141 
12142     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
12143 
12144     if (BlendMask[Mask[i] % Size] < 0)
12145       BlendMask[Mask[i] % Size] = Mask[i];
12146     else if (BlendMask[Mask[i] % Size] != Mask[i])
12147       return SDValue(); // Can't blend in the needed input!
12148 
12149     PermuteMask[i] = Mask[i] % Size;
12150   }
12151 
12152   // If only immediate blends, then bail if the blend mask can't be widened to
12153   // i16.
12154   unsigned EltSize = VT.getScalarSizeInBits();
12155   if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
12156     return SDValue();
12157 
12158   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
12159   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
12160 }
12161 
12162 /// Try to lower as an unpack of elements from two inputs followed by
12163 /// a single-input permutation.
12164 ///
12165 /// This matches the pattern where we can unpack elements from two inputs and
12166 /// then reduce the shuffle to a single-input (wider) permutation.
12167 static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
12168                                              SDValue V1, SDValue V2,
12169                                              ArrayRef<int> Mask,
12170                                              SelectionDAG &DAG) {
12171   int NumElts = Mask.size();
12172   int NumLanes = VT.getSizeInBits() / 128;
12173   int NumLaneElts = NumElts / NumLanes;
12174   int NumHalfLaneElts = NumLaneElts / 2;
12175 
12176   bool MatchLo = true, MatchHi = true;
12177   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
12178 
12179   // Determine UNPCKL/UNPCKH type and operand order.
12180   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
12181     for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
12182       int M = Mask[Lane + Elt];
12183       if (M < 0)
12184         continue;
12185 
12186       SDValue &Op = Ops[Elt & 1];
12187       if (M < NumElts && (Op.isUndef() || Op == V1))
12188         Op = V1;
12189       else if (NumElts <= M && (Op.isUndef() || Op == V2))
12190         Op = V2;
12191       else
12192         return SDValue();
12193 
12194       int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
12195       MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
12196                  isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
12197       MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
12198                  isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
12199       if (!MatchLo && !MatchHi)
12200         return SDValue();
12201     }
12202   }
12203   assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI");
12204 
12205   // Now check that each pair of elts come from the same unpack pair
12206   // and set the permute mask based on each pair.
12207   // TODO - Investigate cases where we permute individual elements.
12208   SmallVector<int, 32> PermuteMask(NumElts, -1);
12209   for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
12210     for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
12211       int M0 = Mask[Lane + Elt + 0];
12212       int M1 = Mask[Lane + Elt + 1];
12213       if (0 <= M0 && 0 <= M1 &&
12214           (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
12215         return SDValue();
12216       if (0 <= M0)
12217         PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
12218       if (0 <= M1)
12219         PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
12220     }
12221   }
12222 
12223   unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
12224   SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
12225   return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
12226 }
12227 
12228 /// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
12229 /// permuting the elements of the result in place.
12230 static SDValue lowerShuffleAsByteRotateAndPermute(
12231     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12232     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12233   if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
12234       (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
12235       (VT.is512BitVector() && !Subtarget.hasBWI()))
12236     return SDValue();
12237 
12238   // We don't currently support lane crossing permutes.
12239   if (is128BitLaneCrossingShuffleMask(VT, Mask))
12240     return SDValue();
12241 
12242   int Scale = VT.getScalarSizeInBits() / 8;
12243   int NumLanes = VT.getSizeInBits() / 128;
12244   int NumElts = VT.getVectorNumElements();
12245   int NumEltsPerLane = NumElts / NumLanes;
12246 
12247   // Determine range of mask elts.
12248   bool Blend1 = true;
12249   bool Blend2 = true;
12250   std::pair<int, int> Range1 = std::make_pair(INT_MAX, INT_MIN);
12251   std::pair<int, int> Range2 = std::make_pair(INT_MAX, INT_MIN);
12252   for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
12253     for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
12254       int M = Mask[Lane + Elt];
12255       if (M < 0)
12256         continue;
12257       if (M < NumElts) {
12258         Blend1 &= (M == (Lane + Elt));
12259         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
12260         M = M % NumEltsPerLane;
12261         Range1.first = std::min(Range1.first, M);
12262         Range1.second = std::max(Range1.second, M);
12263       } else {
12264         M -= NumElts;
12265         Blend2 &= (M == (Lane + Elt));
12266         assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask");
12267         M = M % NumEltsPerLane;
12268         Range2.first = std::min(Range2.first, M);
12269         Range2.second = std::max(Range2.second, M);
12270       }
12271     }
12272   }
12273 
12274   // Bail if we don't need both elements.
12275   // TODO - it might be worth doing this for unary shuffles if the permute
12276   // can be widened.
12277   if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
12278       !(0 <= Range2.first && Range2.second < NumEltsPerLane))
12279     return SDValue();
12280 
12281   if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
12282     return SDValue();
12283 
12284   // Rotate the 2 ops so we can access both ranges, then permute the result.
12285   auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
12286     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12287     SDValue Rotate = DAG.getBitcast(
12288         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
12289                         DAG.getBitcast(ByteVT, Lo),
12290                         DAG.getTargetConstant(Scale * RotAmt, DL, MVT::i8)));
12291     SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
12292     for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
12293       for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
12294         int M = Mask[Lane + Elt];
12295         if (M < 0)
12296           continue;
12297         if (M < NumElts)
12298           PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
12299         else
12300           PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
12301       }
12302     }
12303     return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
12304   };
12305 
12306   // Check if the ranges are small enough to rotate from either direction.
12307   if (Range2.second < Range1.first)
12308     return RotateAndPermute(V1, V2, Range1.first, 0);
12309   if (Range1.second < Range2.first)
12310     return RotateAndPermute(V2, V1, Range2.first, NumElts);
12311   return SDValue();
12312 }
12313 
12314 /// Generic routine to decompose a shuffle and blend into independent
12315 /// blends and permutes.
12316 ///
12317 /// This matches the extremely common pattern for handling combined
12318 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
12319 /// operations. It will try to pick the best arrangement of shuffles and
12320 /// blends. For vXi8/vXi16 shuffles we may use unpack instead of blend.
12321 static SDValue lowerShuffleAsDecomposedShuffleMerge(
12322     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12323     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12324   int NumElts = Mask.size();
12325   int NumLanes = VT.getSizeInBits() / 128;
12326   int NumEltsPerLane = NumElts / NumLanes;
12327 
12328   // Shuffle the input elements into the desired positions in V1 and V2 and
12329   // unpack/blend them together.
12330   bool IsAlternating = true;
12331   SmallVector<int, 32> V1Mask(NumElts, -1);
12332   SmallVector<int, 32> V2Mask(NumElts, -1);
12333   SmallVector<int, 32> FinalMask(NumElts, -1);
12334   for (int i = 0; i < NumElts; ++i) {
12335     int M = Mask[i];
12336     if (M >= 0 && M < NumElts) {
12337       V1Mask[i] = M;
12338       FinalMask[i] = i;
12339       IsAlternating &= (i & 1) == 0;
12340     } else if (M >= NumElts) {
12341       V2Mask[i] = M - NumElts;
12342       FinalMask[i] = i + NumElts;
12343       IsAlternating &= (i & 1) == 1;
12344     }
12345   }
12346 
12347   // Try to lower with the simpler initial blend/unpack/rotate strategies unless
12348   // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
12349   // the shuffle may be able to fold with a load or other benefit. However, when
12350   // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
12351   // pre-shuffle first is a better strategy.
12352   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
12353     // Only prefer immediate blends to unpack/rotate.
12354     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12355                                                           DAG, true))
12356       return BlendPerm;
12357     if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
12358                                                            DAG))
12359       return UnpackPerm;
12360     if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
12361             DL, VT, V1, V2, Mask, Subtarget, DAG))
12362       return RotatePerm;
12363     // Unpack/rotate failed - try again with variable blends.
12364     if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
12365                                                           DAG))
12366       return BlendPerm;
12367   }
12368 
12369   // If the final mask is an alternating blend of vXi8/vXi16, convert to an
12370   // UNPCKL(SHUFFLE, SHUFFLE) pattern.
12371   // TODO: It doesn't have to be alternating - but each lane mustn't have more
12372   // than half the elements coming from each source.
12373   if (IsAlternating && VT.getScalarSizeInBits() < 32) {
12374     V1Mask.assign(NumElts, -1);
12375     V2Mask.assign(NumElts, -1);
12376     FinalMask.assign(NumElts, -1);
12377     for (int i = 0; i != NumElts; i += NumEltsPerLane)
12378       for (int j = 0; j != NumEltsPerLane; ++j) {
12379         int M = Mask[i + j];
12380         if (M >= 0 && M < NumElts) {
12381           V1Mask[i + (j / 2)] = M;
12382           FinalMask[i + j] = i + (j / 2);
12383         } else if (M >= NumElts) {
12384           V2Mask[i + (j / 2)] = M - NumElts;
12385           FinalMask[i + j] = i + (j / 2) + NumElts;
12386         }
12387       }
12388   }
12389 
12390   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12391   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12392   return DAG.getVectorShuffle(VT, DL, V1, V2, FinalMask);
12393 }
12394 
12395 /// Try to lower a vector shuffle as a bit rotation.
12396 ///
12397 /// Look for a repeated rotation pattern in each sub group.
12398 /// Returns a ISD::ROTL element rotation amount or -1 if failed.
12399 static int matchShuffleAsBitRotate(ArrayRef<int> Mask, int NumSubElts) {
12400   int NumElts = Mask.size();
12401   assert((NumElts % NumSubElts) == 0 && "Illegal shuffle mask");
12402 
12403   int RotateAmt = -1;
12404   for (int i = 0; i != NumElts; i += NumSubElts) {
12405     for (int j = 0; j != NumSubElts; ++j) {
12406       int M = Mask[i + j];
12407       if (M < 0)
12408         continue;
12409       if (!isInRange(M, i, i + NumSubElts))
12410         return -1;
12411       int Offset = (NumSubElts - (M - (i + j))) % NumSubElts;
12412       if (0 <= RotateAmt && Offset != RotateAmt)
12413         return -1;
12414       RotateAmt = Offset;
12415     }
12416   }
12417   return RotateAmt;
12418 }
12419 
12420 static int matchShuffleAsBitRotate(MVT &RotateVT, int EltSizeInBits,
12421                                    const X86Subtarget &Subtarget,
12422                                    ArrayRef<int> Mask) {
12423   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12424   assert(EltSizeInBits < 64 && "Can't rotate 64-bit integers");
12425 
12426   // AVX512 only has vXi32/vXi64 rotates, so limit the rotation sub group size.
12427   int MinSubElts = Subtarget.hasAVX512() ? std::max(32 / EltSizeInBits, 2) : 2;
12428   int MaxSubElts = 64 / EltSizeInBits;
12429   for (int NumSubElts = MinSubElts; NumSubElts <= MaxSubElts; NumSubElts *= 2) {
12430     int RotateAmt = matchShuffleAsBitRotate(Mask, NumSubElts);
12431     if (RotateAmt < 0)
12432       continue;
12433 
12434     int NumElts = Mask.size();
12435     MVT RotateSVT = MVT::getIntegerVT(EltSizeInBits * NumSubElts);
12436     RotateVT = MVT::getVectorVT(RotateSVT, NumElts / NumSubElts);
12437     return RotateAmt * EltSizeInBits;
12438   }
12439 
12440   return -1;
12441 }
12442 
12443 /// Lower shuffle using X86ISD::VROTLI rotations.
12444 static SDValue lowerShuffleAsBitRotate(const SDLoc &DL, MVT VT, SDValue V1,
12445                                        ArrayRef<int> Mask,
12446                                        const X86Subtarget &Subtarget,
12447                                        SelectionDAG &DAG) {
12448   // Only XOP + AVX512 targets have bit rotation instructions.
12449   // If we at least have SSSE3 (PSHUFB) then we shouldn't attempt to use this.
12450   bool IsLegal =
12451       (VT.is128BitVector() && Subtarget.hasXOP()) || Subtarget.hasAVX512();
12452   if (!IsLegal && Subtarget.hasSSE3())
12453     return SDValue();
12454 
12455   MVT RotateVT;
12456   int RotateAmt = matchShuffleAsBitRotate(RotateVT, VT.getScalarSizeInBits(),
12457                                           Subtarget, Mask);
12458   if (RotateAmt < 0)
12459     return SDValue();
12460 
12461   // For pre-SSSE3 targets, if we are shuffling vXi8 elts then ISD::ROTL,
12462   // expanded to OR(SRL,SHL), will be more efficient, but if they can
12463   // widen to vXi16 or more then existing lowering should will be better.
12464   if (!IsLegal) {
12465     if ((RotateAmt % 16) == 0)
12466       return SDValue();
12467     // TODO: Use getTargetVShiftByConstNode.
12468     unsigned ShlAmt = RotateAmt;
12469     unsigned SrlAmt = RotateVT.getScalarSizeInBits() - RotateAmt;
12470     V1 = DAG.getBitcast(RotateVT, V1);
12471     SDValue SHL = DAG.getNode(X86ISD::VSHLI, DL, RotateVT, V1,
12472                               DAG.getTargetConstant(ShlAmt, DL, MVT::i8));
12473     SDValue SRL = DAG.getNode(X86ISD::VSRLI, DL, RotateVT, V1,
12474                               DAG.getTargetConstant(SrlAmt, DL, MVT::i8));
12475     SDValue Rot = DAG.getNode(ISD::OR, DL, RotateVT, SHL, SRL);
12476     return DAG.getBitcast(VT, Rot);
12477   }
12478 
12479   SDValue Rot =
12480       DAG.getNode(X86ISD::VROTLI, DL, RotateVT, DAG.getBitcast(RotateVT, V1),
12481                   DAG.getTargetConstant(RotateAmt, DL, MVT::i8));
12482   return DAG.getBitcast(VT, Rot);
12483 }
12484 
12485 /// Try to match a vector shuffle as an element rotation.
12486 ///
12487 /// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
12488 static int matchShuffleAsElementRotate(SDValue &V1, SDValue &V2,
12489                                        ArrayRef<int> Mask) {
12490   int NumElts = Mask.size();
12491 
12492   // We need to detect various ways of spelling a rotation:
12493   //   [11, 12, 13, 14, 15,  0,  1,  2]
12494   //   [-1, 12, 13, 14, -1, -1,  1, -1]
12495   //   [-1, -1, -1, -1, -1, -1,  1,  2]
12496   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
12497   //   [-1,  4,  5,  6, -1, -1,  9, -1]
12498   //   [-1,  4,  5,  6, -1, -1, -1, -1]
12499   int Rotation = 0;
12500   SDValue Lo, Hi;
12501   for (int i = 0; i < NumElts; ++i) {
12502     int M = Mask[i];
12503     assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&
12504            "Unexpected mask index.");
12505     if (M < 0)
12506       continue;
12507 
12508     // Determine where a rotated vector would have started.
12509     int StartIdx = i - (M % NumElts);
12510     if (StartIdx == 0)
12511       // The identity rotation isn't interesting, stop.
12512       return -1;
12513 
12514     // If we found the tail of a vector the rotation must be the missing
12515     // front. If we found the head of a vector, it must be how much of the
12516     // head.
12517     int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
12518 
12519     if (Rotation == 0)
12520       Rotation = CandidateRotation;
12521     else if (Rotation != CandidateRotation)
12522       // The rotations don't match, so we can't match this mask.
12523       return -1;
12524 
12525     // Compute which value this mask is pointing at.
12526     SDValue MaskV = M < NumElts ? V1 : V2;
12527 
12528     // Compute which of the two target values this index should be assigned
12529     // to. This reflects whether the high elements are remaining or the low
12530     // elements are remaining.
12531     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
12532 
12533     // Either set up this value if we've not encountered it before, or check
12534     // that it remains consistent.
12535     if (!TargetV)
12536       TargetV = MaskV;
12537     else if (TargetV != MaskV)
12538       // This may be a rotation, but it pulls from the inputs in some
12539       // unsupported interleaving.
12540       return -1;
12541   }
12542 
12543   // Check that we successfully analyzed the mask, and normalize the results.
12544   assert(Rotation != 0 && "Failed to locate a viable rotation!");
12545   assert((Lo || Hi) && "Failed to find a rotated input vector!");
12546   if (!Lo)
12547     Lo = Hi;
12548   else if (!Hi)
12549     Hi = Lo;
12550 
12551   V1 = Lo;
12552   V2 = Hi;
12553 
12554   return Rotation;
12555 }
12556 
12557 /// Try to lower a vector shuffle as a byte rotation.
12558 ///
12559 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
12560 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
12561 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
12562 /// try to generically lower a vector shuffle through such an pattern. It
12563 /// does not check for the profitability of lowering either as PALIGNR or
12564 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
12565 /// This matches shuffle vectors that look like:
12566 ///
12567 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
12568 ///
12569 /// Essentially it concatenates V1 and V2, shifts right by some number of
12570 /// elements, and takes the low elements as the result. Note that while this is
12571 /// specified as a *right shift* because x86 is little-endian, it is a *left
12572 /// rotate* of the vector lanes.
12573 static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
12574                                     ArrayRef<int> Mask) {
12575   // Don't accept any shuffles with zero elements.
12576   if (isAnyZero(Mask))
12577     return -1;
12578 
12579   // PALIGNR works on 128-bit lanes.
12580   SmallVector<int, 16> RepeatedMask;
12581   if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
12582     return -1;
12583 
12584   int Rotation = matchShuffleAsElementRotate(V1, V2, RepeatedMask);
12585   if (Rotation <= 0)
12586     return -1;
12587 
12588   // PALIGNR rotates bytes, so we need to scale the
12589   // rotation based on how many bytes are in the vector lane.
12590   int NumElts = RepeatedMask.size();
12591   int Scale = 16 / NumElts;
12592   return Rotation * Scale;
12593 }
12594 
12595 static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
12596                                         SDValue V2, ArrayRef<int> Mask,
12597                                         const X86Subtarget &Subtarget,
12598                                         SelectionDAG &DAG) {
12599   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12600 
12601   SDValue Lo = V1, Hi = V2;
12602   int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
12603   if (ByteRotation <= 0)
12604     return SDValue();
12605 
12606   // Cast the inputs to i8 vector of correct length to match PALIGNR or
12607   // PSLLDQ/PSRLDQ.
12608   MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
12609   Lo = DAG.getBitcast(ByteVT, Lo);
12610   Hi = DAG.getBitcast(ByteVT, Hi);
12611 
12612   // SSSE3 targets can use the palignr instruction.
12613   if (Subtarget.hasSSSE3()) {
12614     assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&
12615            "512-bit PALIGNR requires BWI instructions");
12616     return DAG.getBitcast(
12617         VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
12618                         DAG.getTargetConstant(ByteRotation, DL, MVT::i8)));
12619   }
12620 
12621   assert(VT.is128BitVector() &&
12622          "Rotate-based lowering only supports 128-bit lowering!");
12623   assert(Mask.size() <= 16 &&
12624          "Can shuffle at most 16 bytes in a 128-bit vector!");
12625   assert(ByteVT == MVT::v16i8 &&
12626          "SSE2 rotate lowering only needed for v16i8!");
12627 
12628   // Default SSE2 implementation
12629   int LoByteShift = 16 - ByteRotation;
12630   int HiByteShift = ByteRotation;
12631 
12632   SDValue LoShift =
12633       DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
12634                   DAG.getTargetConstant(LoByteShift, DL, MVT::i8));
12635   SDValue HiShift =
12636       DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
12637                   DAG.getTargetConstant(HiByteShift, DL, MVT::i8));
12638   return DAG.getBitcast(VT,
12639                         DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
12640 }
12641 
12642 /// Try to lower a vector shuffle as a dword/qword rotation.
12643 ///
12644 /// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
12645 /// rotation of the concatenation of two vectors; This routine will
12646 /// try to generically lower a vector shuffle through such an pattern.
12647 ///
12648 /// Essentially it concatenates V1 and V2, shifts right by some number of
12649 /// elements, and takes the low elements as the result. Note that while this is
12650 /// specified as a *right shift* because x86 is little-endian, it is a *left
12651 /// rotate* of the vector lanes.
12652 static SDValue lowerShuffleAsVALIGN(const SDLoc &DL, MVT VT, SDValue V1,
12653                                     SDValue V2, ArrayRef<int> Mask,
12654                                     const X86Subtarget &Subtarget,
12655                                     SelectionDAG &DAG) {
12656   assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&
12657          "Only 32-bit and 64-bit elements are supported!");
12658 
12659   // 128/256-bit vectors are only supported with VLX.
12660   assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))
12661          && "VLX required for 128/256-bit vectors");
12662 
12663   SDValue Lo = V1, Hi = V2;
12664   int Rotation = matchShuffleAsElementRotate(Lo, Hi, Mask);
12665   if (Rotation <= 0)
12666     return SDValue();
12667 
12668   return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
12669                      DAG.getTargetConstant(Rotation, DL, MVT::i8));
12670 }
12671 
12672 /// Try to lower a vector shuffle as a byte shift sequence.
12673 static SDValue lowerShuffleAsByteShiftMask(const SDLoc &DL, MVT VT, SDValue V1,
12674                                            SDValue V2, ArrayRef<int> Mask,
12675                                            const APInt &Zeroable,
12676                                            const X86Subtarget &Subtarget,
12677                                            SelectionDAG &DAG) {
12678   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
12679   assert(VT.is128BitVector() && "Only 128-bit vectors supported");
12680 
12681   // We need a shuffle that has zeros at one/both ends and a sequential
12682   // shuffle from one source within.
12683   unsigned ZeroLo = Zeroable.countTrailingOnes();
12684   unsigned ZeroHi = Zeroable.countLeadingOnes();
12685   if (!ZeroLo && !ZeroHi)
12686     return SDValue();
12687 
12688   unsigned NumElts = Mask.size();
12689   unsigned Len = NumElts - (ZeroLo + ZeroHi);
12690   if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
12691     return SDValue();
12692 
12693   unsigned Scale = VT.getScalarSizeInBits() / 8;
12694   ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
12695   if (!isUndefOrInRange(StubMask, 0, NumElts) &&
12696       !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
12697     return SDValue();
12698 
12699   SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
12700   Res = DAG.getBitcast(MVT::v16i8, Res);
12701 
12702   // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
12703   // inner sequential set of elements, possibly offset:
12704   // 01234567 --> zzzzzz01 --> 1zzzzzzz
12705   // 01234567 --> 4567zzzz --> zzzzz456
12706   // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
12707   if (ZeroLo == 0) {
12708     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12709     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12710                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12711     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12712                       DAG.getTargetConstant(Scale * ZeroHi, DL, MVT::i8));
12713   } else if (ZeroHi == 0) {
12714     unsigned Shift = Mask[ZeroLo] % NumElts;
12715     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12716                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12717     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12718                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12719   } else if (!Subtarget.hasSSSE3()) {
12720     // If we don't have PSHUFB then its worth avoiding an AND constant mask
12721     // by performing 3 byte shifts. Shuffle combining can kick in above that.
12722     // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
12723     unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
12724     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12725                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12726     Shift += Mask[ZeroLo] % NumElts;
12727     Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
12728                       DAG.getTargetConstant(Scale * Shift, DL, MVT::i8));
12729     Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
12730                       DAG.getTargetConstant(Scale * ZeroLo, DL, MVT::i8));
12731   } else
12732     return SDValue();
12733 
12734   return DAG.getBitcast(VT, Res);
12735 }
12736 
12737 /// Try to lower a vector shuffle as a bit shift (shifts in zeros).
12738 ///
12739 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
12740 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
12741 /// matches elements from one of the input vectors shuffled to the left or
12742 /// right with zeroable elements 'shifted in'. It handles both the strictly
12743 /// bit-wise element shifts and the byte shift across an entire 128-bit double
12744 /// quad word lane.
12745 ///
12746 /// PSHL : (little-endian) left bit shift.
12747 /// [ zz, 0, zz,  2 ]
12748 /// [ -1, 4, zz, -1 ]
12749 /// PSRL : (little-endian) right bit shift.
12750 /// [  1, zz,  3, zz]
12751 /// [ -1, -1,  7, zz]
12752 /// PSLLDQ : (little-endian) left byte shift
12753 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
12754 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
12755 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
12756 /// PSRLDQ : (little-endian) right byte shift
12757 /// [  5, 6,  7, zz, zz, zz, zz, zz]
12758 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
12759 /// [  1, 2, -1, -1, -1, -1, zz, zz]
12760 static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
12761                                unsigned ScalarSizeInBits, ArrayRef<int> Mask,
12762                                int MaskOffset, const APInt &Zeroable,
12763                                const X86Subtarget &Subtarget) {
12764   int Size = Mask.size();
12765   unsigned SizeInBits = Size * ScalarSizeInBits;
12766 
12767   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
12768     for (int i = 0; i < Size; i += Scale)
12769       for (int j = 0; j < Shift; ++j)
12770         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
12771           return false;
12772 
12773     return true;
12774   };
12775 
12776   auto MatchShift = [&](int Shift, int Scale, bool Left) {
12777     for (int i = 0; i != Size; i += Scale) {
12778       unsigned Pos = Left ? i + Shift : i;
12779       unsigned Low = Left ? i : i + Shift;
12780       unsigned Len = Scale - Shift;
12781       if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
12782         return -1;
12783     }
12784 
12785     int ShiftEltBits = ScalarSizeInBits * Scale;
12786     bool ByteShift = ShiftEltBits > 64;
12787     Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
12788                   : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
12789     int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
12790 
12791     // Normalize the scale for byte shifts to still produce an i64 element
12792     // type.
12793     Scale = ByteShift ? Scale / 2 : Scale;
12794 
12795     // We need to round trip through the appropriate type for the shift.
12796     MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
12797     ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
12798                         : MVT::getVectorVT(ShiftSVT, Size / Scale);
12799     return (int)ShiftAmt;
12800   };
12801 
12802   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
12803   // keep doubling the size of the integer elements up to that. We can
12804   // then shift the elements of the integer vector by whole multiples of
12805   // their width within the elements of the larger integer vector. Test each
12806   // multiple to see if we can find a match with the moved element indices
12807   // and that the shifted in elements are all zeroable.
12808   unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
12809   for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
12810     for (int Shift = 1; Shift != Scale; ++Shift)
12811       for (bool Left : {true, false})
12812         if (CheckZeros(Shift, Scale, Left)) {
12813           int ShiftAmt = MatchShift(Shift, Scale, Left);
12814           if (0 < ShiftAmt)
12815             return ShiftAmt;
12816         }
12817 
12818   // no match
12819   return -1;
12820 }
12821 
12822 static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
12823                                    SDValue V2, ArrayRef<int> Mask,
12824                                    const APInt &Zeroable,
12825                                    const X86Subtarget &Subtarget,
12826                                    SelectionDAG &DAG) {
12827   int Size = Mask.size();
12828   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12829 
12830   MVT ShiftVT;
12831   SDValue V = V1;
12832   unsigned Opcode;
12833 
12834   // Try to match shuffle against V1 shift.
12835   int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12836                                      Mask, 0, Zeroable, Subtarget);
12837 
12838   // If V1 failed, try to match shuffle against V2 shift.
12839   if (ShiftAmt < 0) {
12840     ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
12841                                    Mask, Size, Zeroable, Subtarget);
12842     V = V2;
12843   }
12844 
12845   if (ShiftAmt < 0)
12846     return SDValue();
12847 
12848   assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
12849          "Illegal integer vector type");
12850   V = DAG.getBitcast(ShiftVT, V);
12851   V = DAG.getNode(Opcode, DL, ShiftVT, V,
12852                   DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
12853   return DAG.getBitcast(VT, V);
12854 }
12855 
12856 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
12857 // Remainder of lower half result is zero and upper half is all undef.
12858 static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
12859                                 ArrayRef<int> Mask, uint64_t &BitLen,
12860                                 uint64_t &BitIdx, const APInt &Zeroable) {
12861   int Size = Mask.size();
12862   int HalfSize = Size / 2;
12863   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12864   assert(!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask");
12865 
12866   // Upper half must be undefined.
12867   if (!isUndefUpperHalf(Mask))
12868     return false;
12869 
12870   // Determine the extraction length from the part of the
12871   // lower half that isn't zeroable.
12872   int Len = HalfSize;
12873   for (; Len > 0; --Len)
12874     if (!Zeroable[Len - 1])
12875       break;
12876   assert(Len > 0 && "Zeroable shuffle mask");
12877 
12878   // Attempt to match first Len sequential elements from the lower half.
12879   SDValue Src;
12880   int Idx = -1;
12881   for (int i = 0; i != Len; ++i) {
12882     int M = Mask[i];
12883     if (M == SM_SentinelUndef)
12884       continue;
12885     SDValue &V = (M < Size ? V1 : V2);
12886     M = M % Size;
12887 
12888     // The extracted elements must start at a valid index and all mask
12889     // elements must be in the lower half.
12890     if (i > M || M >= HalfSize)
12891       return false;
12892 
12893     if (Idx < 0 || (Src == V && Idx == (M - i))) {
12894       Src = V;
12895       Idx = M - i;
12896       continue;
12897     }
12898     return false;
12899   }
12900 
12901   if (!Src || Idx < 0)
12902     return false;
12903 
12904   assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
12905   BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12906   BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12907   V1 = Src;
12908   return true;
12909 }
12910 
12911 // INSERTQ: Extract lowest Len elements from lower half of second source and
12912 // insert over first source, starting at Idx.
12913 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
12914 static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
12915                                   ArrayRef<int> Mask, uint64_t &BitLen,
12916                                   uint64_t &BitIdx) {
12917   int Size = Mask.size();
12918   int HalfSize = Size / 2;
12919   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
12920 
12921   // Upper half must be undefined.
12922   if (!isUndefUpperHalf(Mask))
12923     return false;
12924 
12925   for (int Idx = 0; Idx != HalfSize; ++Idx) {
12926     SDValue Base;
12927 
12928     // Attempt to match first source from mask before insertion point.
12929     if (isUndefInRange(Mask, 0, Idx)) {
12930       /* EMPTY */
12931     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
12932       Base = V1;
12933     } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
12934       Base = V2;
12935     } else {
12936       continue;
12937     }
12938 
12939     // Extend the extraction length looking to match both the insertion of
12940     // the second source and the remaining elements of the first.
12941     for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
12942       SDValue Insert;
12943       int Len = Hi - Idx;
12944 
12945       // Match insertion.
12946       if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
12947         Insert = V1;
12948       } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
12949         Insert = V2;
12950       } else {
12951         continue;
12952       }
12953 
12954       // Match the remaining elements of the lower half.
12955       if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
12956         /* EMPTY */
12957       } else if ((!Base || (Base == V1)) &&
12958                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
12959         Base = V1;
12960       } else if ((!Base || (Base == V2)) &&
12961                  isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
12962                                             Size + Hi)) {
12963         Base = V2;
12964       } else {
12965         continue;
12966       }
12967 
12968       BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
12969       BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
12970       V1 = Base;
12971       V2 = Insert;
12972       return true;
12973     }
12974   }
12975 
12976   return false;
12977 }
12978 
12979 /// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
12980 static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
12981                                      SDValue V2, ArrayRef<int> Mask,
12982                                      const APInt &Zeroable, SelectionDAG &DAG) {
12983   uint64_t BitLen, BitIdx;
12984   if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
12985     return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
12986                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
12987                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12988 
12989   if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
12990     return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
12991                        V2 ? V2 : DAG.getUNDEF(VT),
12992                        DAG.getTargetConstant(BitLen, DL, MVT::i8),
12993                        DAG.getTargetConstant(BitIdx, DL, MVT::i8));
12994 
12995   return SDValue();
12996 }
12997 
12998 /// Lower a vector shuffle as a zero or any extension.
12999 ///
13000 /// Given a specific number of elements, element bit width, and extension
13001 /// stride, produce either a zero or any extension based on the available
13002 /// features of the subtarget. The extended elements are consecutive and
13003 /// begin and can start from an offsetted element index in the input; to
13004 /// avoid excess shuffling the offset must either being in the bottom lane
13005 /// or at the start of a higher lane. All extended elements must be from
13006 /// the same lane.
13007 static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
13008     const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
13009     ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13010   assert(Scale > 1 && "Need a scale to extend.");
13011   int EltBits = VT.getScalarSizeInBits();
13012   int NumElements = VT.getVectorNumElements();
13013   int NumEltsPerLane = 128 / EltBits;
13014   int OffsetLane = Offset / NumEltsPerLane;
13015   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
13016          "Only 8, 16, and 32 bit elements can be extended.");
13017   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
13018   assert(0 <= Offset && "Extension offset must be positive.");
13019   assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
13020          "Extension offset must be in the first lane or start an upper lane.");
13021 
13022   // Check that an index is in same lane as the base offset.
13023   auto SafeOffset = [&](int Idx) {
13024     return OffsetLane == (Idx / NumEltsPerLane);
13025   };
13026 
13027   // Shift along an input so that the offset base moves to the first element.
13028   auto ShuffleOffset = [&](SDValue V) {
13029     if (!Offset)
13030       return V;
13031 
13032     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13033     for (int i = 0; i * Scale < NumElements; ++i) {
13034       int SrcIdx = i + Offset;
13035       ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
13036     }
13037     return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
13038   };
13039 
13040   // Found a valid a/zext mask! Try various lowering strategies based on the
13041   // input type and available ISA extensions.
13042   if (Subtarget.hasSSE41()) {
13043     // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
13044     // PUNPCK will catch this in a later shuffle match.
13045     if (Offset && Scale == 2 && VT.is128BitVector())
13046       return SDValue();
13047     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
13048                                  NumElements / Scale);
13049     InputV = ShuffleOffset(InputV);
13050     InputV = getEXTEND_VECTOR_INREG(AnyExt ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND,
13051                                     DL, ExtVT, InputV, DAG);
13052     return DAG.getBitcast(VT, InputV);
13053   }
13054 
13055   assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
13056 
13057   // For any extends we can cheat for larger element sizes and use shuffle
13058   // instructions that can fold with a load and/or copy.
13059   if (AnyExt && EltBits == 32) {
13060     int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
13061                          -1};
13062     return DAG.getBitcast(
13063         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13064                         DAG.getBitcast(MVT::v4i32, InputV),
13065                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13066   }
13067   if (AnyExt && EltBits == 16 && Scale > 2) {
13068     int PSHUFDMask[4] = {Offset / 2, -1,
13069                          SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
13070     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
13071                          DAG.getBitcast(MVT::v4i32, InputV),
13072                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13073     int PSHUFWMask[4] = {1, -1, -1, -1};
13074     unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
13075     return DAG.getBitcast(
13076         VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
13077                         DAG.getBitcast(MVT::v8i16, InputV),
13078                         getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
13079   }
13080 
13081   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
13082   // to 64-bits.
13083   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
13084     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
13085     assert(VT.is128BitVector() && "Unexpected vector width!");
13086 
13087     int LoIdx = Offset * EltBits;
13088     SDValue Lo = DAG.getBitcast(
13089         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13090                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13091                                 DAG.getTargetConstant(LoIdx, DL, MVT::i8)));
13092 
13093     if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
13094       return DAG.getBitcast(VT, Lo);
13095 
13096     int HiIdx = (Offset + 1) * EltBits;
13097     SDValue Hi = DAG.getBitcast(
13098         MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
13099                                 DAG.getTargetConstant(EltBits, DL, MVT::i8),
13100                                 DAG.getTargetConstant(HiIdx, DL, MVT::i8)));
13101     return DAG.getBitcast(VT,
13102                           DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
13103   }
13104 
13105   // If this would require more than 2 unpack instructions to expand, use
13106   // pshufb when available. We can only use more than 2 unpack instructions
13107   // when zero extending i8 elements which also makes it easier to use pshufb.
13108   if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
13109     assert(NumElements == 16 && "Unexpected byte vector width!");
13110     SDValue PSHUFBMask[16];
13111     for (int i = 0; i < 16; ++i) {
13112       int Idx = Offset + (i / Scale);
13113       if ((i % Scale == 0 && SafeOffset(Idx))) {
13114         PSHUFBMask[i] = DAG.getConstant(Idx, DL, MVT::i8);
13115         continue;
13116       }
13117       PSHUFBMask[i] =
13118           AnyExt ? DAG.getUNDEF(MVT::i8) : DAG.getConstant(0x80, DL, MVT::i8);
13119     }
13120     InputV = DAG.getBitcast(MVT::v16i8, InputV);
13121     return DAG.getBitcast(
13122         VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
13123                         DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
13124   }
13125 
13126   // If we are extending from an offset, ensure we start on a boundary that
13127   // we can unpack from.
13128   int AlignToUnpack = Offset % (NumElements / Scale);
13129   if (AlignToUnpack) {
13130     SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
13131     for (int i = AlignToUnpack; i < NumElements; ++i)
13132       ShMask[i - AlignToUnpack] = i;
13133     InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
13134     Offset -= AlignToUnpack;
13135   }
13136 
13137   // Otherwise emit a sequence of unpacks.
13138   do {
13139     unsigned UnpackLoHi = X86ISD::UNPCKL;
13140     if (Offset >= (NumElements / 2)) {
13141       UnpackLoHi = X86ISD::UNPCKH;
13142       Offset -= (NumElements / 2);
13143     }
13144 
13145     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
13146     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
13147                          : getZeroVector(InputVT, Subtarget, DAG, DL);
13148     InputV = DAG.getBitcast(InputVT, InputV);
13149     InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
13150     Scale /= 2;
13151     EltBits *= 2;
13152     NumElements /= 2;
13153   } while (Scale > 1);
13154   return DAG.getBitcast(VT, InputV);
13155 }
13156 
13157 /// Try to lower a vector shuffle as a zero extension on any microarch.
13158 ///
13159 /// This routine will try to do everything in its power to cleverly lower
13160 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
13161 /// check for the profitability of this lowering,  it tries to aggressively
13162 /// match this pattern. It will use all of the micro-architectural details it
13163 /// can to emit an efficient lowering. It handles both blends with all-zero
13164 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
13165 /// masking out later).
13166 ///
13167 /// The reason we have dedicated lowering for zext-style shuffles is that they
13168 /// are both incredibly common and often quite performance sensitive.
13169 static SDValue lowerShuffleAsZeroOrAnyExtend(
13170     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13171     const APInt &Zeroable, const X86Subtarget &Subtarget,
13172     SelectionDAG &DAG) {
13173   int Bits = VT.getSizeInBits();
13174   int NumLanes = Bits / 128;
13175   int NumElements = VT.getVectorNumElements();
13176   int NumEltsPerLane = NumElements / NumLanes;
13177   assert(VT.getScalarSizeInBits() <= 32 &&
13178          "Exceeds 32-bit integer zero extension limit");
13179   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
13180 
13181   // Define a helper function to check a particular ext-scale and lower to it if
13182   // valid.
13183   auto Lower = [&](int Scale) -> SDValue {
13184     SDValue InputV;
13185     bool AnyExt = true;
13186     int Offset = 0;
13187     int Matches = 0;
13188     for (int i = 0; i < NumElements; ++i) {
13189       int M = Mask[i];
13190       if (M < 0)
13191         continue; // Valid anywhere but doesn't tell us anything.
13192       if (i % Scale != 0) {
13193         // Each of the extended elements need to be zeroable.
13194         if (!Zeroable[i])
13195           return SDValue();
13196 
13197         // We no longer are in the anyext case.
13198         AnyExt = false;
13199         continue;
13200       }
13201 
13202       // Each of the base elements needs to be consecutive indices into the
13203       // same input vector.
13204       SDValue V = M < NumElements ? V1 : V2;
13205       M = M % NumElements;
13206       if (!InputV) {
13207         InputV = V;
13208         Offset = M - (i / Scale);
13209       } else if (InputV != V)
13210         return SDValue(); // Flip-flopping inputs.
13211 
13212       // Offset must start in the lowest 128-bit lane or at the start of an
13213       // upper lane.
13214       // FIXME: Is it ever worth allowing a negative base offset?
13215       if (!((0 <= Offset && Offset < NumEltsPerLane) ||
13216             (Offset % NumEltsPerLane) == 0))
13217         return SDValue();
13218 
13219       // If we are offsetting, all referenced entries must come from the same
13220       // lane.
13221       if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
13222         return SDValue();
13223 
13224       if ((M % NumElements) != (Offset + (i / Scale)))
13225         return SDValue(); // Non-consecutive strided elements.
13226       Matches++;
13227     }
13228 
13229     // If we fail to find an input, we have a zero-shuffle which should always
13230     // have already been handled.
13231     // FIXME: Maybe handle this here in case during blending we end up with one?
13232     if (!InputV)
13233       return SDValue();
13234 
13235     // If we are offsetting, don't extend if we only match a single input, we
13236     // can always do better by using a basic PSHUF or PUNPCK.
13237     if (Offset != 0 && Matches < 2)
13238       return SDValue();
13239 
13240     return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
13241                                                  InputV, Mask, Subtarget, DAG);
13242   };
13243 
13244   // The widest scale possible for extending is to a 64-bit integer.
13245   assert(Bits % 64 == 0 &&
13246          "The number of bits in a vector must be divisible by 64 on x86!");
13247   int NumExtElements = Bits / 64;
13248 
13249   // Each iteration, try extending the elements half as much, but into twice as
13250   // many elements.
13251   for (; NumExtElements < NumElements; NumExtElements *= 2) {
13252     assert(NumElements % NumExtElements == 0 &&
13253            "The input vector size must be divisible by the extended size.");
13254     if (SDValue V = Lower(NumElements / NumExtElements))
13255       return V;
13256   }
13257 
13258   // General extends failed, but 128-bit vectors may be able to use MOVQ.
13259   if (Bits != 128)
13260     return SDValue();
13261 
13262   // Returns one of the source operands if the shuffle can be reduced to a
13263   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
13264   auto CanZExtLowHalf = [&]() {
13265     for (int i = NumElements / 2; i != NumElements; ++i)
13266       if (!Zeroable[i])
13267         return SDValue();
13268     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
13269       return V1;
13270     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
13271       return V2;
13272     return SDValue();
13273   };
13274 
13275   if (SDValue V = CanZExtLowHalf()) {
13276     V = DAG.getBitcast(MVT::v2i64, V);
13277     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
13278     return DAG.getBitcast(VT, V);
13279   }
13280 
13281   // No viable ext lowering found.
13282   return SDValue();
13283 }
13284 
13285 /// Try to get a scalar value for a specific element of a vector.
13286 ///
13287 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
13288 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
13289                                               SelectionDAG &DAG) {
13290   MVT VT = V.getSimpleValueType();
13291   MVT EltVT = VT.getVectorElementType();
13292   V = peekThroughBitcasts(V);
13293 
13294   // If the bitcasts shift the element size, we can't extract an equivalent
13295   // element from it.
13296   MVT NewVT = V.getSimpleValueType();
13297   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
13298     return SDValue();
13299 
13300   if (V.getOpcode() == ISD::BUILD_VECTOR ||
13301       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
13302     // Ensure the scalar operand is the same size as the destination.
13303     // FIXME: Add support for scalar truncation where possible.
13304     SDValue S = V.getOperand(Idx);
13305     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
13306       return DAG.getBitcast(EltVT, S);
13307   }
13308 
13309   return SDValue();
13310 }
13311 
13312 /// Helper to test for a load that can be folded with x86 shuffles.
13313 ///
13314 /// This is particularly important because the set of instructions varies
13315 /// significantly based on whether the operand is a load or not.
13316 static bool isShuffleFoldableLoad(SDValue V) {
13317   V = peekThroughBitcasts(V);
13318   return ISD::isNON_EXTLoad(V.getNode());
13319 }
13320 
13321 /// Try to lower insertion of a single element into a zero vector.
13322 ///
13323 /// This is a common pattern that we have especially efficient patterns to lower
13324 /// across all subtarget feature sets.
13325 static SDValue lowerShuffleAsElementInsertion(
13326     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13327     const APInt &Zeroable, const X86Subtarget &Subtarget,
13328     SelectionDAG &DAG) {
13329   MVT ExtVT = VT;
13330   MVT EltVT = VT.getVectorElementType();
13331 
13332   int V2Index =
13333       find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
13334       Mask.begin();
13335   bool IsV1Zeroable = true;
13336   for (int i = 0, Size = Mask.size(); i < Size; ++i)
13337     if (i != V2Index && !Zeroable[i]) {
13338       IsV1Zeroable = false;
13339       break;
13340     }
13341 
13342   // Check for a single input from a SCALAR_TO_VECTOR node.
13343   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
13344   // all the smarts here sunk into that routine. However, the current
13345   // lowering of BUILD_VECTOR makes that nearly impossible until the old
13346   // vector shuffle lowering is dead.
13347   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
13348                                                DAG);
13349   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
13350     // We need to zext the scalar if it is smaller than an i32.
13351     V2S = DAG.getBitcast(EltVT, V2S);
13352     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
13353       // Using zext to expand a narrow element won't work for non-zero
13354       // insertions.
13355       if (!IsV1Zeroable)
13356         return SDValue();
13357 
13358       // Zero-extend directly to i32.
13359       ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
13360       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
13361     }
13362     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
13363   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
13364              EltVT == MVT::i16) {
13365     // Either not inserting from the low element of the input or the input
13366     // element size is too small to use VZEXT_MOVL to clear the high bits.
13367     return SDValue();
13368   }
13369 
13370   if (!IsV1Zeroable) {
13371     // If V1 can't be treated as a zero vector we have fewer options to lower
13372     // this. We can't support integer vectors or non-zero targets cheaply, and
13373     // the V1 elements can't be permuted in any way.
13374     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
13375     if (!VT.isFloatingPoint() || V2Index != 0)
13376       return SDValue();
13377     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
13378     V1Mask[V2Index] = -1;
13379     if (!isNoopShuffleMask(V1Mask))
13380       return SDValue();
13381     if (!VT.is128BitVector())
13382       return SDValue();
13383 
13384     // Otherwise, use MOVSD or MOVSS.
13385     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
13386            "Only two types of floating point element types to handle!");
13387     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
13388                        ExtVT, V1, V2);
13389   }
13390 
13391   // This lowering only works for the low element with floating point vectors.
13392   if (VT.isFloatingPoint() && V2Index != 0)
13393     return SDValue();
13394 
13395   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
13396   if (ExtVT != VT)
13397     V2 = DAG.getBitcast(VT, V2);
13398 
13399   if (V2Index != 0) {
13400     // If we have 4 or fewer lanes we can cheaply shuffle the element into
13401     // the desired position. Otherwise it is more efficient to do a vector
13402     // shift left. We know that we can do a vector shift left because all
13403     // the inputs are zero.
13404     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
13405       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
13406       V2Shuffle[V2Index] = 0;
13407       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
13408     } else {
13409       V2 = DAG.getBitcast(MVT::v16i8, V2);
13410       V2 = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
13411                        DAG.getTargetConstant(
13412                            V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
13413       V2 = DAG.getBitcast(VT, V2);
13414     }
13415   }
13416   return V2;
13417 }
13418 
13419 /// Try to lower broadcast of a single - truncated - integer element,
13420 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
13421 ///
13422 /// This assumes we have AVX2.
13423 static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
13424                                             int BroadcastIdx,
13425                                             const X86Subtarget &Subtarget,
13426                                             SelectionDAG &DAG) {
13427   assert(Subtarget.hasAVX2() &&
13428          "We can only lower integer broadcasts with AVX2!");
13429 
13430   MVT EltVT = VT.getVectorElementType();
13431   MVT V0VT = V0.getSimpleValueType();
13432 
13433   assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
13434   assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
13435 
13436   MVT V0EltVT = V0VT.getVectorElementType();
13437   if (!V0EltVT.isInteger())
13438     return SDValue();
13439 
13440   const unsigned EltSize = EltVT.getSizeInBits();
13441   const unsigned V0EltSize = V0EltVT.getSizeInBits();
13442 
13443   // This is only a truncation if the original element type is larger.
13444   if (V0EltSize <= EltSize)
13445     return SDValue();
13446 
13447   assert(((V0EltSize % EltSize) == 0) &&
13448          "Scalar type sizes must all be powers of 2 on x86!");
13449 
13450   const unsigned V0Opc = V0.getOpcode();
13451   const unsigned Scale = V0EltSize / EltSize;
13452   const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
13453 
13454   if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
13455       V0Opc != ISD::BUILD_VECTOR)
13456     return SDValue();
13457 
13458   SDValue Scalar = V0.getOperand(V0BroadcastIdx);
13459 
13460   // If we're extracting non-least-significant bits, shift so we can truncate.
13461   // Hopefully, we can fold away the trunc/srl/load into the broadcast.
13462   // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
13463   // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
13464   if (const int OffsetIdx = BroadcastIdx % Scale)
13465     Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
13466                          DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
13467 
13468   return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
13469                      DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
13470 }
13471 
13472 /// Test whether this can be lowered with a single SHUFPS instruction.
13473 ///
13474 /// This is used to disable more specialized lowerings when the shufps lowering
13475 /// will happen to be efficient.
13476 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
13477   // This routine only handles 128-bit shufps.
13478   assert(Mask.size() == 4 && "Unsupported mask size!");
13479   assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!");
13480   assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!");
13481   assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!");
13482   assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!");
13483 
13484   // To lower with a single SHUFPS we need to have the low half and high half
13485   // each requiring a single input.
13486   if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
13487     return false;
13488   if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
13489     return false;
13490 
13491   return true;
13492 }
13493 
13494 /// If we are extracting two 128-bit halves of a vector and shuffling the
13495 /// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
13496 /// multi-shuffle lowering.
13497 static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
13498                                              SDValue N1, ArrayRef<int> Mask,
13499                                              SelectionDAG &DAG) {
13500   MVT VT = N0.getSimpleValueType();
13501   assert((VT.is128BitVector() &&
13502           (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&
13503          "VPERM* family of shuffles requires 32-bit or 64-bit elements");
13504 
13505   // Check that both sources are extracts of the same source vector.
13506   if (!N0.hasOneUse() || !N1.hasOneUse() ||
13507       N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13508       N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
13509       N0.getOperand(0) != N1.getOperand(0))
13510     return SDValue();
13511 
13512   SDValue WideVec = N0.getOperand(0);
13513   MVT WideVT = WideVec.getSimpleValueType();
13514   if (!WideVT.is256BitVector())
13515     return SDValue();
13516 
13517   // Match extracts of each half of the wide source vector. Commute the shuffle
13518   // if the extract of the low half is N1.
13519   unsigned NumElts = VT.getVectorNumElements();
13520   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
13521   const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
13522   const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
13523   if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
13524     ShuffleVectorSDNode::commuteMask(NewMask);
13525   else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
13526     return SDValue();
13527 
13528   // Final bailout: if the mask is simple, we are better off using an extract
13529   // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
13530   // because that avoids a constant load from memory.
13531   if (NumElts == 4 &&
13532       (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask)))
13533     return SDValue();
13534 
13535   // Extend the shuffle mask with undef elements.
13536   NewMask.append(NumElts, -1);
13537 
13538   // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
13539   SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
13540                                       NewMask);
13541   // This is free: ymm -> xmm.
13542   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
13543                      DAG.getIntPtrConstant(0, DL));
13544 }
13545 
13546 /// Try to lower broadcast of a single element.
13547 ///
13548 /// For convenience, this code also bundles all of the subtarget feature set
13549 /// filtering. While a little annoying to re-dispatch on type here, there isn't
13550 /// a convenient way to factor it out.
13551 static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
13552                                        SDValue V2, ArrayRef<int> Mask,
13553                                        const X86Subtarget &Subtarget,
13554                                        SelectionDAG &DAG) {
13555   if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
13556         (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
13557         (Subtarget.hasAVX2() && VT.isInteger())))
13558     return SDValue();
13559 
13560   // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
13561   // we can only broadcast from a register with AVX2.
13562   unsigned NumEltBits = VT.getScalarSizeInBits();
13563   unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
13564                         ? X86ISD::MOVDDUP
13565                         : X86ISD::VBROADCAST;
13566   bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
13567 
13568   // Check that the mask is a broadcast.
13569   int BroadcastIdx = getSplatIndex(Mask);
13570   if (BroadcastIdx < 0)
13571     return SDValue();
13572   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
13573                                             "a sorted mask where the broadcast "
13574                                             "comes from V1.");
13575 
13576   // Go up the chain of (vector) values to find a scalar load that we can
13577   // combine with the broadcast.
13578   // TODO: Combine this logic with findEltLoadSrc() used by
13579   //       EltsFromConsecutiveLoads().
13580   int BitOffset = BroadcastIdx * NumEltBits;
13581   SDValue V = V1;
13582   for (;;) {
13583     switch (V.getOpcode()) {
13584     case ISD::BITCAST: {
13585       V = V.getOperand(0);
13586       continue;
13587     }
13588     case ISD::CONCAT_VECTORS: {
13589       int OpBitWidth = V.getOperand(0).getValueSizeInBits();
13590       int OpIdx = BitOffset / OpBitWidth;
13591       V = V.getOperand(OpIdx);
13592       BitOffset %= OpBitWidth;
13593       continue;
13594     }
13595     case ISD::EXTRACT_SUBVECTOR: {
13596       // The extraction index adds to the existing offset.
13597       unsigned EltBitWidth = V.getScalarValueSizeInBits();
13598       unsigned Idx = V.getConstantOperandVal(1);
13599       unsigned BeginOffset = Idx * EltBitWidth;
13600       BitOffset += BeginOffset;
13601       V = V.getOperand(0);
13602       continue;
13603     }
13604     case ISD::INSERT_SUBVECTOR: {
13605       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
13606       int EltBitWidth = VOuter.getScalarValueSizeInBits();
13607       int Idx = (int)V.getConstantOperandVal(2);
13608       int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
13609       int BeginOffset = Idx * EltBitWidth;
13610       int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
13611       if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
13612         BitOffset -= BeginOffset;
13613         V = VInner;
13614       } else {
13615         V = VOuter;
13616       }
13617       continue;
13618     }
13619     }
13620     break;
13621   }
13622   assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset");
13623   BroadcastIdx = BitOffset / NumEltBits;
13624 
13625   // Do we need to bitcast the source to retrieve the original broadcast index?
13626   bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
13627 
13628   // Check if this is a broadcast of a scalar. We special case lowering
13629   // for scalars so that we can more effectively fold with loads.
13630   // If the original value has a larger element type than the shuffle, the
13631   // broadcast element is in essence truncated. Make that explicit to ease
13632   // folding.
13633   if (BitCastSrc && VT.isInteger())
13634     if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
13635             DL, VT, V, BroadcastIdx, Subtarget, DAG))
13636       return TruncBroadcast;
13637 
13638   // Also check the simpler case, where we can directly reuse the scalar.
13639   if (!BitCastSrc &&
13640       ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
13641        (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
13642     V = V.getOperand(BroadcastIdx);
13643 
13644     // If we can't broadcast from a register, check that the input is a load.
13645     if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
13646       return SDValue();
13647   } else if (ISD::isNormalLoad(V.getNode()) &&
13648              cast<LoadSDNode>(V)->isSimple()) {
13649     // We do not check for one-use of the vector load because a broadcast load
13650     // is expected to be a win for code size, register pressure, and possibly
13651     // uops even if the original vector load is not eliminated.
13652 
13653     // Reduce the vector load and shuffle to a broadcasted scalar load.
13654     LoadSDNode *Ld = cast<LoadSDNode>(V);
13655     SDValue BaseAddr = Ld->getOperand(1);
13656     MVT SVT = VT.getScalarType();
13657     unsigned Offset = BroadcastIdx * SVT.getStoreSize();
13658     assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset");
13659     SDValue NewAddr =
13660         DAG.getMemBasePlusOffset(BaseAddr, TypeSize::Fixed(Offset), DL);
13661 
13662     // Directly form VBROADCAST_LOAD if we're using VBROADCAST opcode rather
13663     // than MOVDDUP.
13664     // FIXME: Should we add VBROADCAST_LOAD isel patterns for pre-AVX?
13665     if (Opcode == X86ISD::VBROADCAST) {
13666       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
13667       SDValue Ops[] = {Ld->getChain(), NewAddr};
13668       V = DAG.getMemIntrinsicNode(
13669           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SVT,
13670           DAG.getMachineFunction().getMachineMemOperand(
13671               Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13672       DAG.makeEquivalentMemoryOrdering(Ld, V);
13673       return DAG.getBitcast(VT, V);
13674     }
13675     assert(SVT == MVT::f64 && "Unexpected VT!");
13676     V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
13677                     DAG.getMachineFunction().getMachineMemOperand(
13678                         Ld->getMemOperand(), Offset, SVT.getStoreSize()));
13679     DAG.makeEquivalentMemoryOrdering(Ld, V);
13680   } else if (!BroadcastFromReg) {
13681     // We can't broadcast from a vector register.
13682     return SDValue();
13683   } else if (BitOffset != 0) {
13684     // We can only broadcast from the zero-element of a vector register,
13685     // but it can be advantageous to broadcast from the zero-element of a
13686     // subvector.
13687     if (!VT.is256BitVector() && !VT.is512BitVector())
13688       return SDValue();
13689 
13690     // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
13691     if (VT == MVT::v4f64 || VT == MVT::v4i64)
13692       return SDValue();
13693 
13694     // Only broadcast the zero-element of a 128-bit subvector.
13695     if ((BitOffset % 128) != 0)
13696       return SDValue();
13697 
13698     assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&
13699            "Unexpected bit-offset");
13700     assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&
13701            "Unexpected vector size");
13702     unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
13703     V = extract128BitVector(V, ExtractIdx, DAG, DL);
13704   }
13705 
13706   if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector())
13707     V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
13708                     DAG.getBitcast(MVT::f64, V));
13709 
13710   // If this is a scalar, do the broadcast on this type and bitcast.
13711   if (!V.getValueType().isVector()) {
13712     assert(V.getScalarValueSizeInBits() == NumEltBits &&
13713            "Unexpected scalar size");
13714     MVT BroadcastVT = MVT::getVectorVT(V.getSimpleValueType(),
13715                                        VT.getVectorNumElements());
13716     return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
13717   }
13718 
13719   // We only support broadcasting from 128-bit vectors to minimize the
13720   // number of patterns we need to deal with in isel. So extract down to
13721   // 128-bits, removing as many bitcasts as possible.
13722   if (V.getValueSizeInBits() > 128)
13723     V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
13724 
13725   // Otherwise cast V to a vector with the same element type as VT, but
13726   // possibly narrower than VT. Then perform the broadcast.
13727   unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
13728   MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(), NumSrcElts);
13729   return DAG.getNode(Opcode, DL, VT, DAG.getBitcast(CastVT, V));
13730 }
13731 
13732 // Check for whether we can use INSERTPS to perform the shuffle. We only use
13733 // INSERTPS when the V1 elements are already in the correct locations
13734 // because otherwise we can just always use two SHUFPS instructions which
13735 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
13736 // perform INSERTPS if a single V1 element is out of place and all V2
13737 // elements are zeroable.
13738 static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
13739                                    unsigned &InsertPSMask,
13740                                    const APInt &Zeroable,
13741                                    ArrayRef<int> Mask, SelectionDAG &DAG) {
13742   assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!");
13743   assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!");
13744   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
13745 
13746   // Attempt to match INSERTPS with one element from VA or VB being
13747   // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
13748   // are updated.
13749   auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
13750                              ArrayRef<int> CandidateMask) {
13751     unsigned ZMask = 0;
13752     int VADstIndex = -1;
13753     int VBDstIndex = -1;
13754     bool VAUsedInPlace = false;
13755 
13756     for (int i = 0; i < 4; ++i) {
13757       // Synthesize a zero mask from the zeroable elements (includes undefs).
13758       if (Zeroable[i]) {
13759         ZMask |= 1 << i;
13760         continue;
13761       }
13762 
13763       // Flag if we use any VA inputs in place.
13764       if (i == CandidateMask[i]) {
13765         VAUsedInPlace = true;
13766         continue;
13767       }
13768 
13769       // We can only insert a single non-zeroable element.
13770       if (VADstIndex >= 0 || VBDstIndex >= 0)
13771         return false;
13772 
13773       if (CandidateMask[i] < 4) {
13774         // VA input out of place for insertion.
13775         VADstIndex = i;
13776       } else {
13777         // VB input for insertion.
13778         VBDstIndex = i;
13779       }
13780     }
13781 
13782     // Don't bother if we have no (non-zeroable) element for insertion.
13783     if (VADstIndex < 0 && VBDstIndex < 0)
13784       return false;
13785 
13786     // Determine element insertion src/dst indices. The src index is from the
13787     // start of the inserted vector, not the start of the concatenated vector.
13788     unsigned VBSrcIndex = 0;
13789     if (VADstIndex >= 0) {
13790       // If we have a VA input out of place, we use VA as the V2 element
13791       // insertion and don't use the original V2 at all.
13792       VBSrcIndex = CandidateMask[VADstIndex];
13793       VBDstIndex = VADstIndex;
13794       VB = VA;
13795     } else {
13796       VBSrcIndex = CandidateMask[VBDstIndex] - 4;
13797     }
13798 
13799     // If no V1 inputs are used in place, then the result is created only from
13800     // the zero mask and the V2 insertion - so remove V1 dependency.
13801     if (!VAUsedInPlace)
13802       VA = DAG.getUNDEF(MVT::v4f32);
13803 
13804     // Update V1, V2 and InsertPSMask accordingly.
13805     V1 = VA;
13806     V2 = VB;
13807 
13808     // Insert the V2 element into the desired position.
13809     InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
13810     assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
13811     return true;
13812   };
13813 
13814   if (matchAsInsertPS(V1, V2, Mask))
13815     return true;
13816 
13817   // Commute and try again.
13818   SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
13819   ShuffleVectorSDNode::commuteMask(CommutedMask);
13820   if (matchAsInsertPS(V2, V1, CommutedMask))
13821     return true;
13822 
13823   return false;
13824 }
13825 
13826 static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
13827                                       ArrayRef<int> Mask, const APInt &Zeroable,
13828                                       SelectionDAG &DAG) {
13829   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13830   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
13831 
13832   // Attempt to match the insertps pattern.
13833   unsigned InsertPSMask = 0;
13834   if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
13835     return SDValue();
13836 
13837   // Insert the V2 element into the desired position.
13838   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
13839                      DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
13840 }
13841 
13842 /// Try to lower a shuffle as a permute of the inputs followed by an
13843 /// UNPCK instruction.
13844 ///
13845 /// This specifically targets cases where we end up with alternating between
13846 /// the two inputs, and so can permute them into something that feeds a single
13847 /// UNPCK instruction. Note that this routine only targets integer vectors
13848 /// because for floating point vectors we have a generalized SHUFPS lowering
13849 /// strategy that handles everything that doesn't *exactly* match an unpack,
13850 /// making this clever lowering unnecessary.
13851 static SDValue lowerShuffleAsPermuteAndUnpack(
13852     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13853     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
13854   assert(!VT.isFloatingPoint() &&
13855          "This routine only supports integer vectors.");
13856   assert(VT.is128BitVector() &&
13857          "This routine only works on 128-bit vectors.");
13858   assert(!V2.isUndef() &&
13859          "This routine should only be used when blending two inputs.");
13860   assert(Mask.size() >= 2 && "Single element masks are invalid.");
13861 
13862   int Size = Mask.size();
13863 
13864   int NumLoInputs =
13865       count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
13866   int NumHiInputs =
13867       count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
13868 
13869   bool UnpackLo = NumLoInputs >= NumHiInputs;
13870 
13871   auto TryUnpack = [&](int ScalarSize, int Scale) {
13872     SmallVector<int, 16> V1Mask((unsigned)Size, -1);
13873     SmallVector<int, 16> V2Mask((unsigned)Size, -1);
13874 
13875     for (int i = 0; i < Size; ++i) {
13876       if (Mask[i] < 0)
13877         continue;
13878 
13879       // Each element of the unpack contains Scale elements from this mask.
13880       int UnpackIdx = i / Scale;
13881 
13882       // We only handle the case where V1 feeds the first slots of the unpack.
13883       // We rely on canonicalization to ensure this is the case.
13884       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
13885         return SDValue();
13886 
13887       // Setup the mask for this input. The indexing is tricky as we have to
13888       // handle the unpack stride.
13889       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
13890       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
13891           Mask[i] % Size;
13892     }
13893 
13894     // If we will have to shuffle both inputs to use the unpack, check whether
13895     // we can just unpack first and shuffle the result. If so, skip this unpack.
13896     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
13897         !isNoopShuffleMask(V2Mask))
13898       return SDValue();
13899 
13900     // Shuffle the inputs into place.
13901     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
13902     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
13903 
13904     // Cast the inputs to the type we will use to unpack them.
13905     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
13906     V1 = DAG.getBitcast(UnpackVT, V1);
13907     V2 = DAG.getBitcast(UnpackVT, V2);
13908 
13909     // Unpack the inputs and cast the result back to the desired type.
13910     return DAG.getBitcast(
13911         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
13912                         UnpackVT, V1, V2));
13913   };
13914 
13915   // We try each unpack from the largest to the smallest to try and find one
13916   // that fits this mask.
13917   int OrigScalarSize = VT.getScalarSizeInBits();
13918   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
13919     if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
13920       return Unpack;
13921 
13922   // If we're shuffling with a zero vector then we're better off not doing
13923   // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
13924   if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
13925       ISD::isBuildVectorAllZeros(V2.getNode()))
13926     return SDValue();
13927 
13928   // If none of the unpack-rooted lowerings worked (or were profitable) try an
13929   // initial unpack.
13930   if (NumLoInputs == 0 || NumHiInputs == 0) {
13931     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
13932            "We have to have *some* inputs!");
13933     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
13934 
13935     // FIXME: We could consider the total complexity of the permute of each
13936     // possible unpacking. Or at the least we should consider how many
13937     // half-crossings are created.
13938     // FIXME: We could consider commuting the unpacks.
13939 
13940     SmallVector<int, 32> PermMask((unsigned)Size, -1);
13941     for (int i = 0; i < Size; ++i) {
13942       if (Mask[i] < 0)
13943         continue;
13944 
13945       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
13946 
13947       PermMask[i] =
13948           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
13949     }
13950     return DAG.getVectorShuffle(
13951         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
13952                             DL, VT, V1, V2),
13953         DAG.getUNDEF(VT), PermMask);
13954   }
13955 
13956   return SDValue();
13957 }
13958 
13959 /// Handle lowering of 2-lane 64-bit floating point shuffles.
13960 ///
13961 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
13962 /// support for floating point shuffles but not integer shuffles. These
13963 /// instructions will incur a domain crossing penalty on some chips though so
13964 /// it is better to avoid lowering through this for integer vectors where
13965 /// possible.
13966 static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13967                                  const APInt &Zeroable, SDValue V1, SDValue V2,
13968                                  const X86Subtarget &Subtarget,
13969                                  SelectionDAG &DAG) {
13970   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13971   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
13972   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
13973 
13974   if (V2.isUndef()) {
13975     // Check for being able to broadcast a single element.
13976     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
13977                                                     Mask, Subtarget, DAG))
13978       return Broadcast;
13979 
13980     // Straight shuffle of a single input vector. Simulate this by using the
13981     // single input as both of the "inputs" to this instruction..
13982     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
13983 
13984     if (Subtarget.hasAVX()) {
13985       // If we have AVX, we can use VPERMILPS which will allow folding a load
13986       // into the shuffle.
13987       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
13988                          DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13989     }
13990 
13991     return DAG.getNode(
13992         X86ISD::SHUFP, DL, MVT::v2f64,
13993         Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13994         Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
13995         DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
13996   }
13997   assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13998   assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!");
13999   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
14000   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
14001 
14002   if (Subtarget.hasAVX2())
14003     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14004       return Extract;
14005 
14006   // When loading a scalar and then shuffling it into a vector we can often do
14007   // the insertion cheaply.
14008   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14009           DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14010     return Insertion;
14011   // Try inverting the insertion since for v2 masks it is easy to do and we
14012   // can't reliably sort the mask one way or the other.
14013   int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
14014                         Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
14015   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14016           DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14017     return Insertion;
14018 
14019   // Try to use one of the special instruction patterns to handle two common
14020   // blend patterns if a zero-blend above didn't work.
14021   if (isShuffleEquivalent(Mask, {0, 3}, V1, V2) ||
14022       isShuffleEquivalent(Mask, {1, 3}, V1, V2))
14023     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
14024       // We can either use a special instruction to load over the low double or
14025       // to move just the low double.
14026       return DAG.getNode(
14027           X86ISD::MOVSD, DL, MVT::v2f64, V2,
14028           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
14029 
14030   if (Subtarget.hasSSE41())
14031     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
14032                                             Zeroable, Subtarget, DAG))
14033       return Blend;
14034 
14035   // Use dedicated unpack instructions for masks that match their pattern.
14036   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
14037     return V;
14038 
14039   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
14040   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
14041                      DAG.getTargetConstant(SHUFPDMask, DL, MVT::i8));
14042 }
14043 
14044 /// Handle lowering of 2-lane 64-bit integer shuffles.
14045 ///
14046 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
14047 /// the integer unit to minimize domain crossing penalties. However, for blends
14048 /// it falls back to the floating point shuffle operation with appropriate bit
14049 /// casting.
14050 static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14051                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14052                                  const X86Subtarget &Subtarget,
14053                                  SelectionDAG &DAG) {
14054   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
14055   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
14056   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
14057 
14058   if (V2.isUndef()) {
14059     // Check for being able to broadcast a single element.
14060     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
14061                                                     Mask, Subtarget, DAG))
14062       return Broadcast;
14063 
14064     // Straight shuffle of a single input vector. For everything from SSE2
14065     // onward this has a single fast instruction with no scary immediates.
14066     // We have to map the mask as it is actually a v4i32 shuffle instruction.
14067     V1 = DAG.getBitcast(MVT::v4i32, V1);
14068     int WidenedMask[4] = {Mask[0] < 0 ? -1 : (Mask[0] * 2),
14069                           Mask[0] < 0 ? -1 : ((Mask[0] * 2) + 1),
14070                           Mask[1] < 0 ? -1 : (Mask[1] * 2),
14071                           Mask[1] < 0 ? -1 : ((Mask[1] * 2) + 1)};
14072     return DAG.getBitcast(
14073         MVT::v2i64,
14074         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14075                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
14076   }
14077   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
14078   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
14079   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
14080   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
14081 
14082   if (Subtarget.hasAVX2())
14083     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14084       return Extract;
14085 
14086   // Try to use shift instructions.
14087   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
14088                                           Zeroable, Subtarget, DAG))
14089     return Shift;
14090 
14091   // When loading a scalar and then shuffling it into a vector we can often do
14092   // the insertion cheaply.
14093   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14094           DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
14095     return Insertion;
14096   // Try inverting the insertion since for v2 masks it is easy to do and we
14097   // can't reliably sort the mask one way or the other.
14098   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
14099   if (SDValue Insertion = lowerShuffleAsElementInsertion(
14100           DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
14101     return Insertion;
14102 
14103   // We have different paths for blend lowering, but they all must use the
14104   // *exact* same predicate.
14105   bool IsBlendSupported = Subtarget.hasSSE41();
14106   if (IsBlendSupported)
14107     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
14108                                             Zeroable, Subtarget, DAG))
14109       return Blend;
14110 
14111   // Use dedicated unpack instructions for masks that match their pattern.
14112   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
14113     return V;
14114 
14115   // Try to use byte rotation instructions.
14116   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14117   if (Subtarget.hasSSSE3()) {
14118     if (Subtarget.hasVLX())
14119       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v2i64, V1, V2, Mask,
14120                                                 Subtarget, DAG))
14121         return Rotate;
14122 
14123     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
14124                                                   Subtarget, DAG))
14125       return Rotate;
14126   }
14127 
14128   // If we have direct support for blends, we should lower by decomposing into
14129   // a permute. That will be faster than the domain cross.
14130   if (IsBlendSupported)
14131     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v2i64, V1, V2, Mask,
14132                                                 Subtarget, DAG);
14133 
14134   // We implement this with SHUFPD which is pretty lame because it will likely
14135   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
14136   // However, all the alternatives are still more cycles and newer chips don't
14137   // have this problem. It would be really nice if x86 had better shuffles here.
14138   V1 = DAG.getBitcast(MVT::v2f64, V1);
14139   V2 = DAG.getBitcast(MVT::v2f64, V2);
14140   return DAG.getBitcast(MVT::v2i64,
14141                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
14142 }
14143 
14144 /// Lower a vector shuffle using the SHUFPS instruction.
14145 ///
14146 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
14147 /// It makes no assumptions about whether this is the *best* lowering, it simply
14148 /// uses it.
14149 static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
14150                                       ArrayRef<int> Mask, SDValue V1,
14151                                       SDValue V2, SelectionDAG &DAG) {
14152   SDValue LowV = V1, HighV = V2;
14153   SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
14154   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14155 
14156   if (NumV2Elements == 1) {
14157     int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
14158 
14159     // Compute the index adjacent to V2Index and in the same half by toggling
14160     // the low bit.
14161     int V2AdjIndex = V2Index ^ 1;
14162 
14163     if (Mask[V2AdjIndex] < 0) {
14164       // Handles all the cases where we have a single V2 element and an undef.
14165       // This will only ever happen in the high lanes because we commute the
14166       // vector otherwise.
14167       if (V2Index < 2)
14168         std::swap(LowV, HighV);
14169       NewMask[V2Index] -= 4;
14170     } else {
14171       // Handle the case where the V2 element ends up adjacent to a V1 element.
14172       // To make this work, blend them together as the first step.
14173       int V1Index = V2AdjIndex;
14174       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
14175       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
14176                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
14177 
14178       // Now proceed to reconstruct the final blend as we have the necessary
14179       // high or low half formed.
14180       if (V2Index < 2) {
14181         LowV = V2;
14182         HighV = V1;
14183       } else {
14184         HighV = V2;
14185       }
14186       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
14187       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
14188     }
14189   } else if (NumV2Elements == 2) {
14190     if (Mask[0] < 4 && Mask[1] < 4) {
14191       // Handle the easy case where we have V1 in the low lanes and V2 in the
14192       // high lanes.
14193       NewMask[2] -= 4;
14194       NewMask[3] -= 4;
14195     } else if (Mask[2] < 4 && Mask[3] < 4) {
14196       // We also handle the reversed case because this utility may get called
14197       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
14198       // arrange things in the right direction.
14199       NewMask[0] -= 4;
14200       NewMask[1] -= 4;
14201       HighV = V1;
14202       LowV = V2;
14203     } else {
14204       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
14205       // trying to place elements directly, just blend them and set up the final
14206       // shuffle to place them.
14207 
14208       // The first two blend mask elements are for V1, the second two are for
14209       // V2.
14210       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
14211                           Mask[2] < 4 ? Mask[2] : Mask[3],
14212                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
14213                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
14214       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
14215                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
14216 
14217       // Now we do a normal shuffle of V1 by giving V1 as both operands to
14218       // a blend.
14219       LowV = HighV = V1;
14220       NewMask[0] = Mask[0] < 4 ? 0 : 2;
14221       NewMask[1] = Mask[0] < 4 ? 2 : 0;
14222       NewMask[2] = Mask[2] < 4 ? 1 : 3;
14223       NewMask[3] = Mask[2] < 4 ? 3 : 1;
14224     }
14225   } else if (NumV2Elements == 3) {
14226     // Ideally canonicalizeShuffleMaskWithCommute should have caught this, but
14227     // we can get here due to other paths (e.g repeated mask matching) that we
14228     // don't want to do another round of lowerVECTOR_SHUFFLE.
14229     ShuffleVectorSDNode::commuteMask(NewMask);
14230     return lowerShuffleWithSHUFPS(DL, VT, NewMask, V2, V1, DAG);
14231   }
14232   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
14233                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
14234 }
14235 
14236 /// Lower 4-lane 32-bit floating point shuffles.
14237 ///
14238 /// Uses instructions exclusively from the floating point unit to minimize
14239 /// domain crossing penalties, as these are sufficient to implement all v4f32
14240 /// shuffles.
14241 static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14242                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14243                                  const X86Subtarget &Subtarget,
14244                                  SelectionDAG &DAG) {
14245   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14246   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
14247   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14248 
14249   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14250 
14251   if (NumV2Elements == 0) {
14252     // Check for being able to broadcast a single element.
14253     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
14254                                                     Mask, Subtarget, DAG))
14255       return Broadcast;
14256 
14257     // Use even/odd duplicate instructions for masks that match their pattern.
14258     if (Subtarget.hasSSE3()) {
14259       if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
14260         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
14261       if (isShuffleEquivalent(Mask, {1, 1, 3, 3}, V1, V2))
14262         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
14263     }
14264 
14265     if (Subtarget.hasAVX()) {
14266       // If we have AVX, we can use VPERMILPS which will allow folding a load
14267       // into the shuffle.
14268       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
14269                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14270     }
14271 
14272     // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
14273     // in SSE1 because otherwise they are widened to v2f64 and never get here.
14274     if (!Subtarget.hasSSE2()) {
14275       if (isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2))
14276         return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
14277       if (isShuffleEquivalent(Mask, {2, 3, 2, 3}, V1, V2))
14278         return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
14279     }
14280 
14281     // Otherwise, use a straight shuffle of a single input vector. We pass the
14282     // input vector to both operands to simulate this with a SHUFPS.
14283     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
14284                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14285   }
14286 
14287   if (Subtarget.hasAVX2())
14288     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14289       return Extract;
14290 
14291   // There are special ways we can lower some single-element blends. However, we
14292   // have custom ways we can lower more complex single-element blends below that
14293   // we defer to if both this and BLENDPS fail to match, so restrict this to
14294   // when the V2 input is targeting element 0 of the mask -- that is the fast
14295   // case here.
14296   if (NumV2Elements == 1 && Mask[0] >= 4)
14297     if (SDValue V = lowerShuffleAsElementInsertion(
14298             DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14299       return V;
14300 
14301   if (Subtarget.hasSSE41()) {
14302     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
14303                                             Zeroable, Subtarget, DAG))
14304       return Blend;
14305 
14306     // Use INSERTPS if we can complete the shuffle efficiently.
14307     if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
14308       return V;
14309 
14310     if (!isSingleSHUFPSMask(Mask))
14311       if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
14312                                                             V2, Mask, DAG))
14313         return BlendPerm;
14314   }
14315 
14316   // Use low/high mov instructions. These are only valid in SSE1 because
14317   // otherwise they are widened to v2f64 and never get here.
14318   if (!Subtarget.hasSSE2()) {
14319     if (isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2))
14320       return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
14321     if (isShuffleEquivalent(Mask, {2, 3, 6, 7}, V1, V2))
14322       return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
14323   }
14324 
14325   // Use dedicated unpack instructions for masks that match their pattern.
14326   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
14327     return V;
14328 
14329   // Otherwise fall back to a SHUFPS lowering strategy.
14330   return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
14331 }
14332 
14333 /// Lower 4-lane i32 vector shuffles.
14334 ///
14335 /// We try to handle these with integer-domain shuffles where we can, but for
14336 /// blends we use the floating point domain blend instructions.
14337 static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
14338                                  const APInt &Zeroable, SDValue V1, SDValue V2,
14339                                  const X86Subtarget &Subtarget,
14340                                  SelectionDAG &DAG) {
14341   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14342   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
14343   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
14344 
14345   // Whenever we can lower this as a zext, that instruction is strictly faster
14346   // than any alternative. It also allows us to fold memory operands into the
14347   // shuffle in many cases.
14348   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
14349                                                    Zeroable, Subtarget, DAG))
14350     return ZExt;
14351 
14352   int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
14353 
14354   if (NumV2Elements == 0) {
14355     // Try to use broadcast unless the mask only has one non-undef element.
14356     if (count_if(Mask, [](int M) { return M >= 0 && M < 4; }) > 1) {
14357       if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
14358                                                       Mask, Subtarget, DAG))
14359         return Broadcast;
14360     }
14361 
14362     // Straight shuffle of a single input vector. For everything from SSE2
14363     // onward this has a single fast instruction with no scary immediates.
14364     // We coerce the shuffle pattern to be compatible with UNPCK instructions
14365     // but we aren't actually going to use the UNPCK instruction because doing
14366     // so prevents folding a load into this instruction or making a copy.
14367     const int UnpackLoMask[] = {0, 0, 1, 1};
14368     const int UnpackHiMask[] = {2, 2, 3, 3};
14369     if (isShuffleEquivalent(Mask, {0, 0, 1, 1}, V1, V2))
14370       Mask = UnpackLoMask;
14371     else if (isShuffleEquivalent(Mask, {2, 2, 3, 3}, V1, V2))
14372       Mask = UnpackHiMask;
14373 
14374     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
14375                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
14376   }
14377 
14378   if (Subtarget.hasAVX2())
14379     if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
14380       return Extract;
14381 
14382   // Try to use shift instructions.
14383   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
14384                                           Zeroable, Subtarget, DAG))
14385     return Shift;
14386 
14387   // There are special ways we can lower some single-element blends.
14388   if (NumV2Elements == 1)
14389     if (SDValue V = lowerShuffleAsElementInsertion(
14390             DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
14391       return V;
14392 
14393   // We have different paths for blend lowering, but they all must use the
14394   // *exact* same predicate.
14395   bool IsBlendSupported = Subtarget.hasSSE41();
14396   if (IsBlendSupported)
14397     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
14398                                             Zeroable, Subtarget, DAG))
14399       return Blend;
14400 
14401   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
14402                                              Zeroable, Subtarget, DAG))
14403     return Masked;
14404 
14405   // Use dedicated unpack instructions for masks that match their pattern.
14406   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
14407     return V;
14408 
14409   // Try to use byte rotation instructions.
14410   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
14411   if (Subtarget.hasSSSE3()) {
14412     if (Subtarget.hasVLX())
14413       if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i32, V1, V2, Mask,
14414                                                 Subtarget, DAG))
14415         return Rotate;
14416 
14417     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
14418                                                   Subtarget, DAG))
14419       return Rotate;
14420   }
14421 
14422   // Assume that a single SHUFPS is faster than an alternative sequence of
14423   // multiple instructions (even if the CPU has a domain penalty).
14424   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
14425   if (!isSingleSHUFPSMask(Mask)) {
14426     // If we have direct support for blends, we should lower by decomposing into
14427     // a permute. That will be faster than the domain cross.
14428     if (IsBlendSupported)
14429       return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i32, V1, V2, Mask,
14430                                                   Subtarget, DAG);
14431 
14432     // Try to lower by permuting the inputs into an unpack instruction.
14433     if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
14434                                                         Mask, Subtarget, DAG))
14435       return Unpack;
14436   }
14437 
14438   // We implement this with SHUFPS because it can blend from two vectors.
14439   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
14440   // up the inputs, bypassing domain shift penalties that we would incur if we
14441   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
14442   // relevant.
14443   SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
14444   SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
14445   SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
14446   return DAG.getBitcast(MVT::v4i32, ShufPS);
14447 }
14448 
14449 /// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
14450 /// shuffle lowering, and the most complex part.
14451 ///
14452 /// The lowering strategy is to try to form pairs of input lanes which are
14453 /// targeted at the same half of the final vector, and then use a dword shuffle
14454 /// to place them onto the right half, and finally unpack the paired lanes into
14455 /// their final position.
14456 ///
14457 /// The exact breakdown of how to form these dword pairs and align them on the
14458 /// correct sides is really tricky. See the comments within the function for
14459 /// more of the details.
14460 ///
14461 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
14462 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
14463 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
14464 /// vector, form the analogous 128-bit 8-element Mask.
14465 static SDValue lowerV8I16GeneralSingleInputShuffle(
14466     const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
14467     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14468   assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
14469   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
14470 
14471   assert(Mask.size() == 8 && "Shuffle mask length doesn't match!");
14472   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
14473   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
14474 
14475   // Attempt to directly match PSHUFLW or PSHUFHW.
14476   if (isUndefOrInRange(LoMask, 0, 4) &&
14477       isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
14478     return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14479                        getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14480   }
14481   if (isUndefOrInRange(HiMask, 4, 8) &&
14482       isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
14483     for (int i = 0; i != 4; ++i)
14484       HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
14485     return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14486                        getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14487   }
14488 
14489   SmallVector<int, 4> LoInputs;
14490   copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
14491   array_pod_sort(LoInputs.begin(), LoInputs.end());
14492   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
14493   SmallVector<int, 4> HiInputs;
14494   copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
14495   array_pod_sort(HiInputs.begin(), HiInputs.end());
14496   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
14497   int NumLToL = llvm::lower_bound(LoInputs, 4) - LoInputs.begin();
14498   int NumHToL = LoInputs.size() - NumLToL;
14499   int NumLToH = llvm::lower_bound(HiInputs, 4) - HiInputs.begin();
14500   int NumHToH = HiInputs.size() - NumLToH;
14501   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
14502   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
14503   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
14504   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
14505 
14506   // If we are shuffling values from one half - check how many different DWORD
14507   // pairs we need to create. If only 1 or 2 then we can perform this as a
14508   // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
14509   auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
14510                                ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
14511     V = DAG.getNode(ShufWOp, DL, VT, V,
14512                     getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14513     V = DAG.getBitcast(PSHUFDVT, V);
14514     V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
14515                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
14516     return DAG.getBitcast(VT, V);
14517   };
14518 
14519   if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
14520     int PSHUFDMask[4] = { -1, -1, -1, -1 };
14521     SmallVector<std::pair<int, int>, 4> DWordPairs;
14522     int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
14523 
14524     // Collect the different DWORD pairs.
14525     for (int DWord = 0; DWord != 4; ++DWord) {
14526       int M0 = Mask[2 * DWord + 0];
14527       int M1 = Mask[2 * DWord + 1];
14528       M0 = (M0 >= 0 ? M0 % 4 : M0);
14529       M1 = (M1 >= 0 ? M1 % 4 : M1);
14530       if (M0 < 0 && M1 < 0)
14531         continue;
14532 
14533       bool Match = false;
14534       for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
14535         auto &DWordPair = DWordPairs[j];
14536         if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
14537             (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
14538           DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
14539           DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
14540           PSHUFDMask[DWord] = DOffset + j;
14541           Match = true;
14542           break;
14543         }
14544       }
14545       if (!Match) {
14546         PSHUFDMask[DWord] = DOffset + DWordPairs.size();
14547         DWordPairs.push_back(std::make_pair(M0, M1));
14548       }
14549     }
14550 
14551     if (DWordPairs.size() <= 2) {
14552       DWordPairs.resize(2, std::make_pair(-1, -1));
14553       int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
14554                               DWordPairs[1].first, DWordPairs[1].second};
14555       if ((NumHToL + NumHToH) == 0)
14556         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
14557       if ((NumLToL + NumLToH) == 0)
14558         return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
14559     }
14560   }
14561 
14562   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
14563   // such inputs we can swap two of the dwords across the half mark and end up
14564   // with <=2 inputs to each half in each half. Once there, we can fall through
14565   // to the generic code below. For example:
14566   //
14567   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14568   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
14569   //
14570   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
14571   // and an existing 2-into-2 on the other half. In this case we may have to
14572   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
14573   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
14574   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
14575   // because any other situation (including a 3-into-1 or 1-into-3 in the other
14576   // half than the one we target for fixing) will be fixed when we re-enter this
14577   // path. We will also combine away any sequence of PSHUFD instructions that
14578   // result into a single instruction. Here is an example of the tricky case:
14579   //
14580   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
14581   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
14582   //
14583   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
14584   //
14585   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
14586   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
14587   //
14588   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
14589   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
14590   //
14591   // The result is fine to be handled by the generic logic.
14592   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
14593                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
14594                           int AOffset, int BOffset) {
14595     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
14596            "Must call this with A having 3 or 1 inputs from the A half.");
14597     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
14598            "Must call this with B having 1 or 3 inputs from the B half.");
14599     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
14600            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
14601 
14602     bool ThreeAInputs = AToAInputs.size() == 3;
14603 
14604     // Compute the index of dword with only one word among the three inputs in
14605     // a half by taking the sum of the half with three inputs and subtracting
14606     // the sum of the actual three inputs. The difference is the remaining
14607     // slot.
14608     int ADWord = 0, BDWord = 0;
14609     int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
14610     int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
14611     int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
14612     ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
14613     int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
14614     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
14615     int TripleNonInputIdx =
14616         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
14617     TripleDWord = TripleNonInputIdx / 2;
14618 
14619     // We use xor with one to compute the adjacent DWord to whichever one the
14620     // OneInput is in.
14621     OneInputDWord = (OneInput / 2) ^ 1;
14622 
14623     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
14624     // and BToA inputs. If there is also such a problem with the BToB and AToB
14625     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
14626     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
14627     // is essential that we don't *create* a 3<-1 as then we might oscillate.
14628     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
14629       // Compute how many inputs will be flipped by swapping these DWords. We
14630       // need
14631       // to balance this to ensure we don't form a 3-1 shuffle in the other
14632       // half.
14633       int NumFlippedAToBInputs =
14634           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
14635           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
14636       int NumFlippedBToBInputs =
14637           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
14638           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
14639       if ((NumFlippedAToBInputs == 1 &&
14640            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
14641           (NumFlippedBToBInputs == 1 &&
14642            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
14643         // We choose whether to fix the A half or B half based on whether that
14644         // half has zero flipped inputs. At zero, we may not be able to fix it
14645         // with that half. We also bias towards fixing the B half because that
14646         // will more commonly be the high half, and we have to bias one way.
14647         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
14648                                                        ArrayRef<int> Inputs) {
14649           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
14650           bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
14651           // Determine whether the free index is in the flipped dword or the
14652           // unflipped dword based on where the pinned index is. We use this bit
14653           // in an xor to conditionally select the adjacent dword.
14654           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
14655           bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14656           if (IsFixIdxInput == IsFixFreeIdxInput)
14657             FixFreeIdx += 1;
14658           IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
14659           assert(IsFixIdxInput != IsFixFreeIdxInput &&
14660                  "We need to be changing the number of flipped inputs!");
14661           int PSHUFHalfMask[] = {0, 1, 2, 3};
14662           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
14663           V = DAG.getNode(
14664               FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
14665               MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
14666               getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
14667 
14668           for (int &M : Mask)
14669             if (M >= 0 && M == FixIdx)
14670               M = FixFreeIdx;
14671             else if (M >= 0 && M == FixFreeIdx)
14672               M = FixIdx;
14673         };
14674         if (NumFlippedBToBInputs != 0) {
14675           int BPinnedIdx =
14676               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
14677           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
14678         } else {
14679           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
14680           int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
14681           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
14682         }
14683       }
14684     }
14685 
14686     int PSHUFDMask[] = {0, 1, 2, 3};
14687     PSHUFDMask[ADWord] = BDWord;
14688     PSHUFDMask[BDWord] = ADWord;
14689     V = DAG.getBitcast(
14690         VT,
14691         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14692                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14693 
14694     // Adjust the mask to match the new locations of A and B.
14695     for (int &M : Mask)
14696       if (M >= 0 && M/2 == ADWord)
14697         M = 2 * BDWord + M % 2;
14698       else if (M >= 0 && M/2 == BDWord)
14699         M = 2 * ADWord + M % 2;
14700 
14701     // Recurse back into this routine to re-compute state now that this isn't
14702     // a 3 and 1 problem.
14703     return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
14704   };
14705   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
14706     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
14707   if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
14708     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
14709 
14710   // At this point there are at most two inputs to the low and high halves from
14711   // each half. That means the inputs can always be grouped into dwords and
14712   // those dwords can then be moved to the correct half with a dword shuffle.
14713   // We use at most one low and one high word shuffle to collect these paired
14714   // inputs into dwords, and finally a dword shuffle to place them.
14715   int PSHUFLMask[4] = {-1, -1, -1, -1};
14716   int PSHUFHMask[4] = {-1, -1, -1, -1};
14717   int PSHUFDMask[4] = {-1, -1, -1, -1};
14718 
14719   // First fix the masks for all the inputs that are staying in their
14720   // original halves. This will then dictate the targets of the cross-half
14721   // shuffles.
14722   auto fixInPlaceInputs =
14723       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
14724                     MutableArrayRef<int> SourceHalfMask,
14725                     MutableArrayRef<int> HalfMask, int HalfOffset) {
14726     if (InPlaceInputs.empty())
14727       return;
14728     if (InPlaceInputs.size() == 1) {
14729       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14730           InPlaceInputs[0] - HalfOffset;
14731       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
14732       return;
14733     }
14734     if (IncomingInputs.empty()) {
14735       // Just fix all of the in place inputs.
14736       for (int Input : InPlaceInputs) {
14737         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
14738         PSHUFDMask[Input / 2] = Input / 2;
14739       }
14740       return;
14741     }
14742 
14743     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
14744     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
14745         InPlaceInputs[0] - HalfOffset;
14746     // Put the second input next to the first so that they are packed into
14747     // a dword. We find the adjacent index by toggling the low bit.
14748     int AdjIndex = InPlaceInputs[0] ^ 1;
14749     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
14750     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
14751     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
14752   };
14753   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
14754   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
14755 
14756   // Now gather the cross-half inputs and place them into a free dword of
14757   // their target half.
14758   // FIXME: This operation could almost certainly be simplified dramatically to
14759   // look more like the 3-1 fixing operation.
14760   auto moveInputsToRightHalf = [&PSHUFDMask](
14761       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
14762       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
14763       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
14764       int DestOffset) {
14765     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
14766       return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
14767     };
14768     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
14769                                                int Word) {
14770       int LowWord = Word & ~1;
14771       int HighWord = Word | 1;
14772       return isWordClobbered(SourceHalfMask, LowWord) ||
14773              isWordClobbered(SourceHalfMask, HighWord);
14774     };
14775 
14776     if (IncomingInputs.empty())
14777       return;
14778 
14779     if (ExistingInputs.empty()) {
14780       // Map any dwords with inputs from them into the right half.
14781       for (int Input : IncomingInputs) {
14782         // If the source half mask maps over the inputs, turn those into
14783         // swaps and use the swapped lane.
14784         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
14785           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
14786             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
14787                 Input - SourceOffset;
14788             // We have to swap the uses in our half mask in one sweep.
14789             for (int &M : HalfMask)
14790               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
14791                 M = Input;
14792               else if (M == Input)
14793                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14794           } else {
14795             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
14796                        Input - SourceOffset &&
14797                    "Previous placement doesn't match!");
14798           }
14799           // Note that this correctly re-maps both when we do a swap and when
14800           // we observe the other side of the swap above. We rely on that to
14801           // avoid swapping the members of the input list directly.
14802           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
14803         }
14804 
14805         // Map the input's dword into the correct half.
14806         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
14807           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
14808         else
14809           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
14810                      Input / 2 &&
14811                  "Previous placement doesn't match!");
14812       }
14813 
14814       // And just directly shift any other-half mask elements to be same-half
14815       // as we will have mirrored the dword containing the element into the
14816       // same position within that half.
14817       for (int &M : HalfMask)
14818         if (M >= SourceOffset && M < SourceOffset + 4) {
14819           M = M - SourceOffset + DestOffset;
14820           assert(M >= 0 && "This should never wrap below zero!");
14821         }
14822       return;
14823     }
14824 
14825     // Ensure we have the input in a viable dword of its current half. This
14826     // is particularly tricky because the original position may be clobbered
14827     // by inputs being moved and *staying* in that half.
14828     if (IncomingInputs.size() == 1) {
14829       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14830         int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
14831                          SourceOffset;
14832         SourceHalfMask[InputFixed - SourceOffset] =
14833             IncomingInputs[0] - SourceOffset;
14834         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
14835                      InputFixed);
14836         IncomingInputs[0] = InputFixed;
14837       }
14838     } else if (IncomingInputs.size() == 2) {
14839       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
14840           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
14841         // We have two non-adjacent or clobbered inputs we need to extract from
14842         // the source half. To do this, we need to map them into some adjacent
14843         // dword slot in the source mask.
14844         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
14845                               IncomingInputs[1] - SourceOffset};
14846 
14847         // If there is a free slot in the source half mask adjacent to one of
14848         // the inputs, place the other input in it. We use (Index XOR 1) to
14849         // compute an adjacent index.
14850         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
14851             SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
14852           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
14853           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14854           InputsFixed[1] = InputsFixed[0] ^ 1;
14855         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
14856                    SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
14857           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
14858           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
14859           InputsFixed[0] = InputsFixed[1] ^ 1;
14860         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
14861                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
14862           // The two inputs are in the same DWord but it is clobbered and the
14863           // adjacent DWord isn't used at all. Move both inputs to the free
14864           // slot.
14865           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
14866           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
14867           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
14868           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
14869         } else {
14870           // The only way we hit this point is if there is no clobbering
14871           // (because there are no off-half inputs to this half) and there is no
14872           // free slot adjacent to one of the inputs. In this case, we have to
14873           // swap an input with a non-input.
14874           for (int i = 0; i < 4; ++i)
14875             assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
14876                    "We can't handle any clobbers here!");
14877           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
14878                  "Cannot have adjacent inputs here!");
14879 
14880           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
14881           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
14882 
14883           // We also have to update the final source mask in this case because
14884           // it may need to undo the above swap.
14885           for (int &M : FinalSourceHalfMask)
14886             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
14887               M = InputsFixed[1] + SourceOffset;
14888             else if (M == InputsFixed[1] + SourceOffset)
14889               M = (InputsFixed[0] ^ 1) + SourceOffset;
14890 
14891           InputsFixed[1] = InputsFixed[0] ^ 1;
14892         }
14893 
14894         // Point everything at the fixed inputs.
14895         for (int &M : HalfMask)
14896           if (M == IncomingInputs[0])
14897             M = InputsFixed[0] + SourceOffset;
14898           else if (M == IncomingInputs[1])
14899             M = InputsFixed[1] + SourceOffset;
14900 
14901         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
14902         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
14903       }
14904     } else {
14905       llvm_unreachable("Unhandled input size!");
14906     }
14907 
14908     // Now hoist the DWord down to the right half.
14909     int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
14910     assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free");
14911     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
14912     for (int &M : HalfMask)
14913       for (int Input : IncomingInputs)
14914         if (M == Input)
14915           M = FreeDWord * 2 + Input % 2;
14916   };
14917   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
14918                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
14919   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
14920                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
14921 
14922   // Now enact all the shuffles we've computed to move the inputs into their
14923   // target half.
14924   if (!isNoopShuffleMask(PSHUFLMask))
14925     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14926                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
14927   if (!isNoopShuffleMask(PSHUFHMask))
14928     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14929                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
14930   if (!isNoopShuffleMask(PSHUFDMask))
14931     V = DAG.getBitcast(
14932         VT,
14933         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
14934                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
14935 
14936   // At this point, each half should contain all its inputs, and we can then
14937   // just shuffle them into their final position.
14938   assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
14939          "Failed to lift all the high half inputs to the low mask!");
14940   assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&
14941          "Failed to lift all the low half inputs to the high mask!");
14942 
14943   // Do a half shuffle for the low mask.
14944   if (!isNoopShuffleMask(LoMask))
14945     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
14946                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
14947 
14948   // Do a half shuffle with the high mask after shifting its values down.
14949   for (int &M : HiMask)
14950     if (M >= 0)
14951       M -= 4;
14952   if (!isNoopShuffleMask(HiMask))
14953     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
14954                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
14955 
14956   return V;
14957 }
14958 
14959 /// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
14960 /// blend if only one input is used.
14961 static SDValue lowerShuffleAsBlendOfPSHUFBs(
14962     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14963     const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
14964   assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&
14965          "Lane crossing shuffle masks not supported");
14966 
14967   int NumBytes = VT.getSizeInBits() / 8;
14968   int Size = Mask.size();
14969   int Scale = NumBytes / Size;
14970 
14971   SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14972   SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
14973   V1InUse = false;
14974   V2InUse = false;
14975 
14976   for (int i = 0; i < NumBytes; ++i) {
14977     int M = Mask[i / Scale];
14978     if (M < 0)
14979       continue;
14980 
14981     const int ZeroMask = 0x80;
14982     int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
14983     int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
14984     if (Zeroable[i / Scale])
14985       V1Idx = V2Idx = ZeroMask;
14986 
14987     V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
14988     V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
14989     V1InUse |= (ZeroMask != V1Idx);
14990     V2InUse |= (ZeroMask != V2Idx);
14991   }
14992 
14993   MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
14994   if (V1InUse)
14995     V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
14996                      DAG.getBuildVector(ShufVT, DL, V1Mask));
14997   if (V2InUse)
14998     V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
14999                      DAG.getBuildVector(ShufVT, DL, V2Mask));
15000 
15001   // If we need shuffled inputs from both, blend the two.
15002   SDValue V;
15003   if (V1InUse && V2InUse)
15004     V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
15005   else
15006     V = V1InUse ? V1 : V2;
15007 
15008   // Cast the result back to the correct type.
15009   return DAG.getBitcast(VT, V);
15010 }
15011 
15012 /// Generic lowering of 8-lane i16 shuffles.
15013 ///
15014 /// This handles both single-input shuffles and combined shuffle/blends with
15015 /// two inputs. The single input shuffles are immediately delegated to
15016 /// a dedicated lowering routine.
15017 ///
15018 /// The blends are lowered in one of three fundamental ways. If there are few
15019 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
15020 /// of the input is significantly cheaper when lowered as an interleaving of
15021 /// the two inputs, try to interleave them. Otherwise, blend the low and high
15022 /// halves of the inputs separately (making them have relatively few inputs)
15023 /// and then concatenate them.
15024 static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15025                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15026                                  const X86Subtarget &Subtarget,
15027                                  SelectionDAG &DAG) {
15028   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
15029   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
15030   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
15031 
15032   // Whenever we can lower this as a zext, that instruction is strictly faster
15033   // than any alternative.
15034   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
15035                                                    Zeroable, Subtarget, DAG))
15036     return ZExt;
15037 
15038   // Try to use lower using a truncation.
15039   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15040                                         Subtarget, DAG))
15041     return V;
15042 
15043   int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
15044 
15045   if (NumV2Inputs == 0) {
15046     // Try to use shift instructions.
15047     if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
15048                                             Zeroable, Subtarget, DAG))
15049       return Shift;
15050 
15051     // Check for being able to broadcast a single element.
15052     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
15053                                                     Mask, Subtarget, DAG))
15054       return Broadcast;
15055 
15056     // Try to use bit rotation instructions.
15057     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v8i16, V1, Mask,
15058                                                  Subtarget, DAG))
15059       return Rotate;
15060 
15061     // Use dedicated unpack instructions for masks that match their pattern.
15062     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15063       return V;
15064 
15065     // Use dedicated pack instructions for masks that match their pattern.
15066     if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15067                                          Subtarget))
15068       return V;
15069 
15070     // Try to use byte rotation instructions.
15071     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
15072                                                   Subtarget, DAG))
15073       return Rotate;
15074 
15075     // Make a copy of the mask so it can be modified.
15076     SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
15077     return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
15078                                                Subtarget, DAG);
15079   }
15080 
15081   assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&
15082          "All single-input shuffles should be canonicalized to be V1-input "
15083          "shuffles.");
15084 
15085   // Try to use shift instructions.
15086   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
15087                                           Zeroable, Subtarget, DAG))
15088     return Shift;
15089 
15090   // See if we can use SSE4A Extraction / Insertion.
15091   if (Subtarget.hasSSE4A())
15092     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
15093                                           Zeroable, DAG))
15094       return V;
15095 
15096   // There are special ways we can lower some single-element blends.
15097   if (NumV2Inputs == 1)
15098     if (SDValue V = lowerShuffleAsElementInsertion(
15099             DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15100       return V;
15101 
15102   // We have different paths for blend lowering, but they all must use the
15103   // *exact* same predicate.
15104   bool IsBlendSupported = Subtarget.hasSSE41();
15105   if (IsBlendSupported)
15106     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
15107                                             Zeroable, Subtarget, DAG))
15108       return Blend;
15109 
15110   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
15111                                              Zeroable, Subtarget, DAG))
15112     return Masked;
15113 
15114   // Use dedicated unpack instructions for masks that match their pattern.
15115   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
15116     return V;
15117 
15118   // Use dedicated pack instructions for masks that match their pattern.
15119   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
15120                                        Subtarget))
15121     return V;
15122 
15123   // Try to use lower using a truncation.
15124   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v8i16, V1, V2, Mask, Zeroable,
15125                                        Subtarget, DAG))
15126     return V;
15127 
15128   // Try to use byte rotation instructions.
15129   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
15130                                                 Subtarget, DAG))
15131     return Rotate;
15132 
15133   if (SDValue BitBlend =
15134           lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
15135     return BitBlend;
15136 
15137   // Try to use byte shift instructions to mask.
15138   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v8i16, V1, V2, Mask,
15139                                               Zeroable, Subtarget, DAG))
15140     return V;
15141 
15142   // Attempt to lower using compaction, SSE41 is necessary for PACKUSDW.
15143   // We could use SIGN_EXTEND_INREG+PACKSSDW for older targets but this seems to
15144   // be slower than a PSHUFLW+PSHUFHW+PSHUFD chain.
15145   int NumEvenDrops = canLowerByDroppingEvenElements(Mask, false);
15146   if ((NumEvenDrops == 1 || NumEvenDrops == 2) && Subtarget.hasSSE41() &&
15147       !Subtarget.hasVLX()) {
15148     SmallVector<SDValue, 8> DWordClearOps(4, DAG.getConstant(0, DL, MVT::i32));
15149     for (unsigned i = 0; i != 4; i += 1 << (NumEvenDrops - 1))
15150       DWordClearOps[i] = DAG.getConstant(0xFFFF, DL, MVT::i32);
15151     SDValue DWordClearMask = DAG.getBuildVector(MVT::v4i32, DL, DWordClearOps);
15152     V1 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V1),
15153                      DWordClearMask);
15154     V2 = DAG.getNode(ISD::AND, DL, MVT::v4i32, DAG.getBitcast(MVT::v4i32, V2),
15155                      DWordClearMask);
15156     // Now pack things back together.
15157     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, V1, V2);
15158     if (NumEvenDrops == 2) {
15159       Result = DAG.getBitcast(MVT::v4i32, Result);
15160       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v8i16, Result, Result);
15161     }
15162     return Result;
15163   }
15164 
15165   // Try to lower by permuting the inputs into an unpack instruction.
15166   if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
15167                                                       Mask, Subtarget, DAG))
15168     return Unpack;
15169 
15170   // If we can't directly blend but can use PSHUFB, that will be better as it
15171   // can both shuffle and set up the inefficient blend.
15172   if (!IsBlendSupported && Subtarget.hasSSSE3()) {
15173     bool V1InUse, V2InUse;
15174     return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
15175                                         Zeroable, DAG, V1InUse, V2InUse);
15176   }
15177 
15178   // We can always bit-blend if we have to so the fallback strategy is to
15179   // decompose into single-input permutes and blends/unpacks.
15180   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i16, V1, V2,
15181                                               Mask, Subtarget, DAG);
15182 }
15183 
15184 // Lowers unary/binary shuffle as VPERMV/VPERMV3, for non-VLX targets,
15185 // sub-512-bit shuffles are padded to 512-bits for the shuffle and then
15186 // the active subvector is extracted.
15187 static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
15188                                      ArrayRef<int> Mask, SDValue V1, SDValue V2,
15189                                      const X86Subtarget &Subtarget,
15190                                      SelectionDAG &DAG) {
15191   MVT MaskVT = VT.changeTypeToInteger();
15192   SDValue MaskNode;
15193   MVT ShuffleVT = VT;
15194   if (!VT.is512BitVector() && !Subtarget.hasVLX()) {
15195     V1 = widenSubVector(V1, false, Subtarget, DAG, DL, 512);
15196     V2 = widenSubVector(V2, false, Subtarget, DAG, DL, 512);
15197     ShuffleVT = V1.getSimpleValueType();
15198 
15199     // Adjust mask to correct indices for the second input.
15200     int NumElts = VT.getVectorNumElements();
15201     unsigned Scale = 512 / VT.getSizeInBits();
15202     SmallVector<int, 32> AdjustedMask(Mask.begin(), Mask.end());
15203     for (int &M : AdjustedMask)
15204       if (NumElts <= M)
15205         M += (Scale - 1) * NumElts;
15206     MaskNode = getConstVector(AdjustedMask, MaskVT, DAG, DL, true);
15207     MaskNode = widenSubVector(MaskNode, false, Subtarget, DAG, DL, 512);
15208   } else {
15209     MaskNode = getConstVector(Mask, MaskVT, DAG, DL, true);
15210   }
15211 
15212   SDValue Result;
15213   if (V2.isUndef())
15214     Result = DAG.getNode(X86ISD::VPERMV, DL, ShuffleVT, MaskNode, V1);
15215   else
15216     Result = DAG.getNode(X86ISD::VPERMV3, DL, ShuffleVT, V1, MaskNode, V2);
15217 
15218   if (VT != ShuffleVT)
15219     Result = extractSubVector(Result, 0, DAG, DL, VT.getSizeInBits());
15220 
15221   return Result;
15222 }
15223 
15224 /// Generic lowering of v16i8 shuffles.
15225 ///
15226 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
15227 /// detect any complexity reducing interleaving. If that doesn't help, it uses
15228 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
15229 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
15230 /// back together.
15231 static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15232                                  const APInt &Zeroable, SDValue V1, SDValue V2,
15233                                  const X86Subtarget &Subtarget,
15234                                  SelectionDAG &DAG) {
15235   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15236   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
15237   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
15238 
15239   // Try to use shift instructions.
15240   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
15241                                           Zeroable, Subtarget, DAG))
15242     return Shift;
15243 
15244   // Try to use byte rotation instructions.
15245   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
15246                                                 Subtarget, DAG))
15247     return Rotate;
15248 
15249   // Use dedicated pack instructions for masks that match their pattern.
15250   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
15251                                        Subtarget))
15252     return V;
15253 
15254   // Try to use a zext lowering.
15255   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
15256                                                    Zeroable, Subtarget, DAG))
15257     return ZExt;
15258 
15259   // Try to use lower using a truncation.
15260   if (SDValue V = lowerShuffleWithVPMOV(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15261                                         Subtarget, DAG))
15262     return V;
15263 
15264   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i8, V1, V2, Mask, Zeroable,
15265                                        Subtarget, DAG))
15266     return V;
15267 
15268   // See if we can use SSE4A Extraction / Insertion.
15269   if (Subtarget.hasSSE4A())
15270     if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
15271                                           Zeroable, DAG))
15272       return V;
15273 
15274   int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
15275 
15276   // For single-input shuffles, there are some nicer lowering tricks we can use.
15277   if (NumV2Elements == 0) {
15278     // Check for being able to broadcast a single element.
15279     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
15280                                                     Mask, Subtarget, DAG))
15281       return Broadcast;
15282 
15283     // Try to use bit rotation instructions.
15284     if (SDValue Rotate = lowerShuffleAsBitRotate(DL, MVT::v16i8, V1, Mask,
15285                                                  Subtarget, DAG))
15286       return Rotate;
15287 
15288     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
15289       return V;
15290 
15291     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
15292     // Notably, this handles splat and partial-splat shuffles more efficiently.
15293     // However, it only makes sense if the pre-duplication shuffle simplifies
15294     // things significantly. Currently, this means we need to be able to
15295     // express the pre-duplication shuffle as an i16 shuffle.
15296     //
15297     // FIXME: We should check for other patterns which can be widened into an
15298     // i16 shuffle as well.
15299     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
15300       for (int i = 0; i < 16; i += 2)
15301         if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
15302           return false;
15303 
15304       return true;
15305     };
15306     auto tryToWidenViaDuplication = [&]() -> SDValue {
15307       if (!canWidenViaDuplication(Mask))
15308         return SDValue();
15309       SmallVector<int, 4> LoInputs;
15310       copy_if(Mask, std::back_inserter(LoInputs),
15311               [](int M) { return M >= 0 && M < 8; });
15312       array_pod_sort(LoInputs.begin(), LoInputs.end());
15313       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
15314                      LoInputs.end());
15315       SmallVector<int, 4> HiInputs;
15316       copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
15317       array_pod_sort(HiInputs.begin(), HiInputs.end());
15318       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
15319                      HiInputs.end());
15320 
15321       bool TargetLo = LoInputs.size() >= HiInputs.size();
15322       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
15323       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
15324 
15325       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
15326       SmallDenseMap<int, int, 8> LaneMap;
15327       for (int I : InPlaceInputs) {
15328         PreDupI16Shuffle[I/2] = I/2;
15329         LaneMap[I] = I;
15330       }
15331       int j = TargetLo ? 0 : 4, je = j + 4;
15332       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
15333         // Check if j is already a shuffle of this input. This happens when
15334         // there are two adjacent bytes after we move the low one.
15335         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
15336           // If we haven't yet mapped the input, search for a slot into which
15337           // we can map it.
15338           while (j < je && PreDupI16Shuffle[j] >= 0)
15339             ++j;
15340 
15341           if (j == je)
15342             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
15343             return SDValue();
15344 
15345           // Map this input with the i16 shuffle.
15346           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
15347         }
15348 
15349         // Update the lane map based on the mapping we ended up with.
15350         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
15351       }
15352       V1 = DAG.getBitcast(
15353           MVT::v16i8,
15354           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15355                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
15356 
15357       // Unpack the bytes to form the i16s that will be shuffled into place.
15358       bool EvenInUse = false, OddInUse = false;
15359       for (int i = 0; i < 16; i += 2) {
15360         EvenInUse |= (Mask[i + 0] >= 0);
15361         OddInUse |= (Mask[i + 1] >= 0);
15362         if (EvenInUse && OddInUse)
15363           break;
15364       }
15365       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
15366                        MVT::v16i8, EvenInUse ? V1 : DAG.getUNDEF(MVT::v16i8),
15367                        OddInUse ? V1 : DAG.getUNDEF(MVT::v16i8));
15368 
15369       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
15370       for (int i = 0; i < 16; ++i)
15371         if (Mask[i] >= 0) {
15372           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
15373           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
15374           if (PostDupI16Shuffle[i / 2] < 0)
15375             PostDupI16Shuffle[i / 2] = MappedMask;
15376           else
15377             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
15378                    "Conflicting entries in the original shuffle!");
15379         }
15380       return DAG.getBitcast(
15381           MVT::v16i8,
15382           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
15383                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
15384     };
15385     if (SDValue V = tryToWidenViaDuplication())
15386       return V;
15387   }
15388 
15389   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
15390                                              Zeroable, Subtarget, DAG))
15391     return Masked;
15392 
15393   // Use dedicated unpack instructions for masks that match their pattern.
15394   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
15395     return V;
15396 
15397   // Try to use byte shift instructions to mask.
15398   if (SDValue V = lowerShuffleAsByteShiftMask(DL, MVT::v16i8, V1, V2, Mask,
15399                                               Zeroable, Subtarget, DAG))
15400     return V;
15401 
15402   // Check for compaction patterns.
15403   bool IsSingleInput = V2.isUndef();
15404   int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput);
15405 
15406   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
15407   // with PSHUFB. It is important to do this before we attempt to generate any
15408   // blends but after all of the single-input lowerings. If the single input
15409   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
15410   // want to preserve that and we can DAG combine any longer sequences into
15411   // a PSHUFB in the end. But once we start blending from multiple inputs,
15412   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
15413   // and there are *very* few patterns that would actually be faster than the
15414   // PSHUFB approach because of its ability to zero lanes.
15415   //
15416   // If the mask is a binary compaction, we can more efficiently perform this
15417   // as a PACKUS(AND(),AND()) - which is quicker than UNPACK(PSHUFB(),PSHUFB()).
15418   //
15419   // FIXME: The only exceptions to the above are blends which are exact
15420   // interleavings with direct instructions supporting them. We currently don't
15421   // handle those well here.
15422   if (Subtarget.hasSSSE3() && (IsSingleInput || NumEvenDrops != 1)) {
15423     bool V1InUse = false;
15424     bool V2InUse = false;
15425 
15426     SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
15427         DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
15428 
15429     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
15430     // do so. This avoids using them to handle blends-with-zero which is
15431     // important as a single pshufb is significantly faster for that.
15432     if (V1InUse && V2InUse) {
15433       if (Subtarget.hasSSE41())
15434         if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
15435                                                 Zeroable, Subtarget, DAG))
15436           return Blend;
15437 
15438       // We can use an unpack to do the blending rather than an or in some
15439       // cases. Even though the or may be (very minorly) more efficient, we
15440       // preference this lowering because there are common cases where part of
15441       // the complexity of the shuffles goes away when we do the final blend as
15442       // an unpack.
15443       // FIXME: It might be worth trying to detect if the unpack-feeding
15444       // shuffles will both be pshufb, in which case we shouldn't bother with
15445       // this.
15446       if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
15447               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15448         return Unpack;
15449 
15450       // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
15451       if (Subtarget.hasVBMI())
15452         return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, Subtarget,
15453                                      DAG);
15454 
15455       // If we have XOP we can use one VPPERM instead of multiple PSHUFBs.
15456       if (Subtarget.hasXOP()) {
15457         SDValue MaskNode = getConstVector(Mask, MVT::v16i8, DAG, DL, true);
15458         return DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, V1, V2, MaskNode);
15459       }
15460 
15461       // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
15462       // PALIGNR will be cheaper than the second PSHUFB+OR.
15463       if (SDValue V = lowerShuffleAsByteRotateAndPermute(
15464               DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
15465         return V;
15466     }
15467 
15468     return PSHUFB;
15469   }
15470 
15471   // There are special ways we can lower some single-element blends.
15472   if (NumV2Elements == 1)
15473     if (SDValue V = lowerShuffleAsElementInsertion(
15474             DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
15475       return V;
15476 
15477   if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
15478     return Blend;
15479 
15480   // Check whether a compaction lowering can be done. This handles shuffles
15481   // which take every Nth element for some even N. See the helper function for
15482   // details.
15483   //
15484   // We special case these as they can be particularly efficiently handled with
15485   // the PACKUSB instruction on x86 and they show up in common patterns of
15486   // rearranging bytes to truncate wide elements.
15487   if (NumEvenDrops) {
15488     // NumEvenDrops is the power of two stride of the elements. Another way of
15489     // thinking about it is that we need to drop the even elements this many
15490     // times to get the original input.
15491 
15492     // First we need to zero all the dropped bytes.
15493     assert(NumEvenDrops <= 3 &&
15494            "No support for dropping even elements more than 3 times.");
15495     SmallVector<SDValue, 8> WordClearOps(8, DAG.getConstant(0, DL, MVT::i16));
15496     for (unsigned i = 0; i != 8; i += 1 << (NumEvenDrops - 1))
15497       WordClearOps[i] = DAG.getConstant(0xFF, DL, MVT::i16);
15498     SDValue WordClearMask = DAG.getBuildVector(MVT::v8i16, DL, WordClearOps);
15499     V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V1),
15500                      WordClearMask);
15501     if (!IsSingleInput)
15502       V2 = DAG.getNode(ISD::AND, DL, MVT::v8i16, DAG.getBitcast(MVT::v8i16, V2),
15503                        WordClearMask);
15504 
15505     // Now pack things back together.
15506     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1,
15507                                  IsSingleInput ? V1 : V2);
15508     for (int i = 1; i < NumEvenDrops; ++i) {
15509       Result = DAG.getBitcast(MVT::v8i16, Result);
15510       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
15511     }
15512     return Result;
15513   }
15514 
15515   // Handle multi-input cases by blending/unpacking single-input shuffles.
15516   if (NumV2Elements > 0)
15517     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v16i8, V1, V2, Mask,
15518                                                 Subtarget, DAG);
15519 
15520   // The fallback path for single-input shuffles widens this into two v8i16
15521   // vectors with unpacks, shuffles those, and then pulls them back together
15522   // with a pack.
15523   SDValue V = V1;
15524 
15525   std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15526   std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
15527   for (int i = 0; i < 16; ++i)
15528     if (Mask[i] >= 0)
15529       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
15530 
15531   SDValue VLoHalf, VHiHalf;
15532   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
15533   // them out and avoid using UNPCK{L,H} to extract the elements of V as
15534   // i16s.
15535   if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
15536       none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
15537     // Use a mask to drop the high bytes.
15538     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
15539     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
15540                           DAG.getConstant(0x00FF, DL, MVT::v8i16));
15541 
15542     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
15543     VHiHalf = DAG.getUNDEF(MVT::v8i16);
15544 
15545     // Squash the masks to point directly into VLoHalf.
15546     for (int &M : LoBlendMask)
15547       if (M >= 0)
15548         M /= 2;
15549     for (int &M : HiBlendMask)
15550       if (M >= 0)
15551         M /= 2;
15552   } else {
15553     // Otherwise just unpack the low half of V into VLoHalf and the high half into
15554     // VHiHalf so that we can blend them as i16s.
15555     SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
15556 
15557     VLoHalf = DAG.getBitcast(
15558         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
15559     VHiHalf = DAG.getBitcast(
15560         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
15561   }
15562 
15563   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
15564   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
15565 
15566   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
15567 }
15568 
15569 /// Dispatching routine to lower various 128-bit x86 vector shuffles.
15570 ///
15571 /// This routine breaks down the specific type of 128-bit shuffle and
15572 /// dispatches to the lowering routines accordingly.
15573 static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
15574                                   MVT VT, SDValue V1, SDValue V2,
15575                                   const APInt &Zeroable,
15576                                   const X86Subtarget &Subtarget,
15577                                   SelectionDAG &DAG) {
15578   switch (VT.SimpleTy) {
15579   case MVT::v2i64:
15580     return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15581   case MVT::v2f64:
15582     return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15583   case MVT::v4i32:
15584     return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15585   case MVT::v4f32:
15586     return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15587   case MVT::v8i16:
15588     return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15589   case MVT::v16i8:
15590     return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15591 
15592   default:
15593     llvm_unreachable("Unimplemented!");
15594   }
15595 }
15596 
15597 /// Generic routine to split vector shuffle into half-sized shuffles.
15598 ///
15599 /// This routine just extracts two subvectors, shuffles them independently, and
15600 /// then concatenates them back together. This should work effectively with all
15601 /// AVX vector shuffle types.
15602 static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
15603                                     SDValue V2, ArrayRef<int> Mask,
15604                                     SelectionDAG &DAG) {
15605   assert(VT.getSizeInBits() >= 256 &&
15606          "Only for 256-bit or wider vector shuffles!");
15607   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
15608   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
15609 
15610   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
15611   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
15612 
15613   int NumElements = VT.getVectorNumElements();
15614   int SplitNumElements = NumElements / 2;
15615   MVT ScalarVT = VT.getVectorElementType();
15616   MVT SplitVT = MVT::getVectorVT(ScalarVT, SplitNumElements);
15617 
15618   // Use splitVector/extractSubVector so that split build-vectors just build two
15619   // narrower build vectors. This helps shuffling with splats and zeros.
15620   auto SplitVector = [&](SDValue V) {
15621     SDValue LoV, HiV;
15622     std::tie(LoV, HiV) = splitVector(peekThroughBitcasts(V), DAG, DL);
15623     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
15624                           DAG.getBitcast(SplitVT, HiV));
15625   };
15626 
15627   SDValue LoV1, HiV1, LoV2, HiV2;
15628   std::tie(LoV1, HiV1) = SplitVector(V1);
15629   std::tie(LoV2, HiV2) = SplitVector(V2);
15630 
15631   // Now create two 4-way blends of these half-width vectors.
15632   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
15633     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
15634     SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
15635     SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
15636     SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
15637     for (int i = 0; i < SplitNumElements; ++i) {
15638       int M = HalfMask[i];
15639       if (M >= NumElements) {
15640         if (M >= NumElements + SplitNumElements)
15641           UseHiV2 = true;
15642         else
15643           UseLoV2 = true;
15644         V2BlendMask[i] = M - NumElements;
15645         BlendMask[i] = SplitNumElements + i;
15646       } else if (M >= 0) {
15647         if (M >= SplitNumElements)
15648           UseHiV1 = true;
15649         else
15650           UseLoV1 = true;
15651         V1BlendMask[i] = M;
15652         BlendMask[i] = i;
15653       }
15654     }
15655 
15656     // Because the lowering happens after all combining takes place, we need to
15657     // manually combine these blend masks as much as possible so that we create
15658     // a minimal number of high-level vector shuffle nodes.
15659 
15660     // First try just blending the halves of V1 or V2.
15661     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
15662       return DAG.getUNDEF(SplitVT);
15663     if (!UseLoV2 && !UseHiV2)
15664       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15665     if (!UseLoV1 && !UseHiV1)
15666       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15667 
15668     SDValue V1Blend, V2Blend;
15669     if (UseLoV1 && UseHiV1) {
15670       V1Blend =
15671         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
15672     } else {
15673       // We only use half of V1 so map the usage down into the final blend mask.
15674       V1Blend = UseLoV1 ? LoV1 : HiV1;
15675       for (int i = 0; i < SplitNumElements; ++i)
15676         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
15677           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
15678     }
15679     if (UseLoV2 && UseHiV2) {
15680       V2Blend =
15681         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
15682     } else {
15683       // We only use half of V2 so map the usage down into the final blend mask.
15684       V2Blend = UseLoV2 ? LoV2 : HiV2;
15685       for (int i = 0; i < SplitNumElements; ++i)
15686         if (BlendMask[i] >= SplitNumElements)
15687           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
15688     }
15689     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
15690   };
15691   SDValue Lo = HalfBlend(LoMask);
15692   SDValue Hi = HalfBlend(HiMask);
15693   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
15694 }
15695 
15696 /// Either split a vector in halves or decompose the shuffles and the
15697 /// blend/unpack.
15698 ///
15699 /// This is provided as a good fallback for many lowerings of non-single-input
15700 /// shuffles with more than one 128-bit lane. In those cases, we want to select
15701 /// between splitting the shuffle into 128-bit components and stitching those
15702 /// back together vs. extracting the single-input shuffles and blending those
15703 /// results.
15704 static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
15705                                           SDValue V2, ArrayRef<int> Mask,
15706                                           const X86Subtarget &Subtarget,
15707                                           SelectionDAG &DAG) {
15708   assert(!V2.isUndef() && "This routine must not be used to lower single-input "
15709          "shuffles as it could then recurse on itself.");
15710   int Size = Mask.size();
15711 
15712   // If this can be modeled as a broadcast of two elements followed by a blend,
15713   // prefer that lowering. This is especially important because broadcasts can
15714   // often fold with memory operands.
15715   auto DoBothBroadcast = [&] {
15716     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
15717     for (int M : Mask)
15718       if (M >= Size) {
15719         if (V2BroadcastIdx < 0)
15720           V2BroadcastIdx = M - Size;
15721         else if (M - Size != V2BroadcastIdx)
15722           return false;
15723       } else if (M >= 0) {
15724         if (V1BroadcastIdx < 0)
15725           V1BroadcastIdx = M;
15726         else if (M != V1BroadcastIdx)
15727           return false;
15728       }
15729     return true;
15730   };
15731   if (DoBothBroadcast())
15732     return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
15733                                                 DAG);
15734 
15735   // If the inputs all stem from a single 128-bit lane of each input, then we
15736   // split them rather than blending because the split will decompose to
15737   // unusually few instructions.
15738   int LaneCount = VT.getSizeInBits() / 128;
15739   int LaneSize = Size / LaneCount;
15740   SmallBitVector LaneInputs[2];
15741   LaneInputs[0].resize(LaneCount, false);
15742   LaneInputs[1].resize(LaneCount, false);
15743   for (int i = 0; i < Size; ++i)
15744     if (Mask[i] >= 0)
15745       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
15746   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
15747     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15748 
15749   // Otherwise, just fall back to decomposed shuffles and a blend/unpack. This
15750   // requires that the decomposed single-input shuffles don't end up here.
15751   return lowerShuffleAsDecomposedShuffleMerge(DL, VT, V1, V2, Mask, Subtarget,
15752                                               DAG);
15753 }
15754 
15755 // Lower as SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15756 // TODO: Extend to support v8f32 (+ 512-bit shuffles).
15757 static SDValue lowerShuffleAsLanePermuteAndSHUFP(const SDLoc &DL, MVT VT,
15758                                                  SDValue V1, SDValue V2,
15759                                                  ArrayRef<int> Mask,
15760                                                  SelectionDAG &DAG) {
15761   assert(VT == MVT::v4f64 && "Only for v4f64 shuffles");
15762 
15763   int LHSMask[4] = {-1, -1, -1, -1};
15764   int RHSMask[4] = {-1, -1, -1, -1};
15765   unsigned SHUFPMask = 0;
15766 
15767   // As SHUFPD uses a single LHS/RHS element per lane, we can always
15768   // perform the shuffle once the lanes have been shuffled in place.
15769   for (int i = 0; i != 4; ++i) {
15770     int M = Mask[i];
15771     if (M < 0)
15772       continue;
15773     int LaneBase = i & ~1;
15774     auto &LaneMask = (i & 1) ? RHSMask : LHSMask;
15775     LaneMask[LaneBase + (M & 1)] = M;
15776     SHUFPMask |= (M & 1) << i;
15777   }
15778 
15779   SDValue LHS = DAG.getVectorShuffle(VT, DL, V1, V2, LHSMask);
15780   SDValue RHS = DAG.getVectorShuffle(VT, DL, V1, V2, RHSMask);
15781   return DAG.getNode(X86ISD::SHUFP, DL, VT, LHS, RHS,
15782                      DAG.getTargetConstant(SHUFPMask, DL, MVT::i8));
15783 }
15784 
15785 /// Lower a vector shuffle crossing multiple 128-bit lanes as
15786 /// a lane permutation followed by a per-lane permutation.
15787 ///
15788 /// This is mainly for cases where we can have non-repeating permutes
15789 /// in each lane.
15790 ///
15791 /// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
15792 /// we should investigate merging them.
15793 static SDValue lowerShuffleAsLanePermuteAndPermute(
15794     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15795     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15796   int NumElts = VT.getVectorNumElements();
15797   int NumLanes = VT.getSizeInBits() / 128;
15798   int NumEltsPerLane = NumElts / NumLanes;
15799   bool CanUseSublanes = Subtarget.hasAVX2() && V2.isUndef();
15800 
15801   /// Attempts to find a sublane permute with the given size
15802   /// that gets all elements into their target lanes.
15803   ///
15804   /// If successful, fills CrossLaneMask and InLaneMask and returns true.
15805   /// If unsuccessful, returns false and may overwrite InLaneMask.
15806   auto getSublanePermute = [&](int NumSublanes) -> SDValue {
15807     int NumSublanesPerLane = NumSublanes / NumLanes;
15808     int NumEltsPerSublane = NumElts / NumSublanes;
15809 
15810     SmallVector<int, 16> CrossLaneMask;
15811     SmallVector<int, 16> InLaneMask(NumElts, SM_SentinelUndef);
15812     // CrossLaneMask but one entry == one sublane.
15813     SmallVector<int, 16> CrossLaneMaskLarge(NumSublanes, SM_SentinelUndef);
15814 
15815     for (int i = 0; i != NumElts; ++i) {
15816       int M = Mask[i];
15817       if (M < 0)
15818         continue;
15819 
15820       int SrcSublane = M / NumEltsPerSublane;
15821       int DstLane = i / NumEltsPerLane;
15822 
15823       // We only need to get the elements into the right lane, not sublane.
15824       // So search all sublanes that make up the destination lane.
15825       bool Found = false;
15826       int DstSubStart = DstLane * NumSublanesPerLane;
15827       int DstSubEnd = DstSubStart + NumSublanesPerLane;
15828       for (int DstSublane = DstSubStart; DstSublane < DstSubEnd; ++DstSublane) {
15829         if (!isUndefOrEqual(CrossLaneMaskLarge[DstSublane], SrcSublane))
15830           continue;
15831 
15832         Found = true;
15833         CrossLaneMaskLarge[DstSublane] = SrcSublane;
15834         int DstSublaneOffset = DstSublane * NumEltsPerSublane;
15835         InLaneMask[i] = DstSublaneOffset + M % NumEltsPerSublane;
15836         break;
15837       }
15838       if (!Found)
15839         return SDValue();
15840     }
15841 
15842     // Fill CrossLaneMask using CrossLaneMaskLarge.
15843     narrowShuffleMaskElts(NumEltsPerSublane, CrossLaneMaskLarge, CrossLaneMask);
15844 
15845     if (!CanUseSublanes) {
15846       // If we're only shuffling a single lowest lane and the rest are identity
15847       // then don't bother.
15848       // TODO - isShuffleMaskInputInPlace could be extended to something like
15849       // this.
15850       int NumIdentityLanes = 0;
15851       bool OnlyShuffleLowestLane = true;
15852       for (int i = 0; i != NumLanes; ++i) {
15853         int LaneOffset = i * NumEltsPerLane;
15854         if (isSequentialOrUndefInRange(InLaneMask, LaneOffset, NumEltsPerLane,
15855                                        i * NumEltsPerLane))
15856           NumIdentityLanes++;
15857         else if (CrossLaneMask[LaneOffset] != 0)
15858           OnlyShuffleLowestLane = false;
15859       }
15860       if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
15861         return SDValue();
15862     }
15863 
15864     SDValue CrossLane = DAG.getVectorShuffle(VT, DL, V1, V2, CrossLaneMask);
15865     return DAG.getVectorShuffle(VT, DL, CrossLane, DAG.getUNDEF(VT),
15866                                 InLaneMask);
15867   };
15868 
15869   // First attempt a solution with full lanes.
15870   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes))
15871     return V;
15872 
15873   // The rest of the solutions use sublanes.
15874   if (!CanUseSublanes)
15875     return SDValue();
15876 
15877   // Then attempt a solution with 64-bit sublanes (vpermq).
15878   if (SDValue V = getSublanePermute(/*NumSublanes=*/NumLanes * 2))
15879     return V;
15880 
15881   // If that doesn't work and we have fast variable shuffle,
15882   // attempt 32-bit sublanes (vpermd).
15883   if (!Subtarget.hasFastVariableShuffle())
15884     return SDValue();
15885 
15886   return getSublanePermute(/*NumSublanes=*/NumLanes * 4);
15887 }
15888 
15889 /// Lower a vector shuffle crossing multiple 128-bit lanes by shuffling one
15890 /// source with a lane permutation.
15891 ///
15892 /// This lowering strategy results in four instructions in the worst case for a
15893 /// single-input cross lane shuffle which is lower than any other fully general
15894 /// cross-lane shuffle strategy I'm aware of. Special cases for each particular
15895 /// shuffle pattern should be handled prior to trying this lowering.
15896 static SDValue lowerShuffleAsLanePermuteAndShuffle(
15897     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
15898     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
15899   // FIXME: This should probably be generalized for 512-bit vectors as well.
15900   assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
15901   int Size = Mask.size();
15902   int LaneSize = Size / 2;
15903 
15904   // Fold to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
15905   // Only do this if the elements aren't all from the lower lane,
15906   // otherwise we're (probably) better off doing a split.
15907   if (VT == MVT::v4f64 &&
15908       !all_of(Mask, [LaneSize](int M) { return M < LaneSize; }))
15909     if (SDValue V =
15910             lowerShuffleAsLanePermuteAndSHUFP(DL, VT, V1, V2, Mask, DAG))
15911       return V;
15912 
15913   // If there are only inputs from one 128-bit lane, splitting will in fact be
15914   // less expensive. The flags track whether the given lane contains an element
15915   // that crosses to another lane.
15916   if (!Subtarget.hasAVX2()) {
15917     bool LaneCrossing[2] = {false, false};
15918     for (int i = 0; i < Size; ++i)
15919       if (Mask[i] >= 0 && ((Mask[i] % Size) / LaneSize) != (i / LaneSize))
15920         LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
15921     if (!LaneCrossing[0] || !LaneCrossing[1])
15922       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15923   } else {
15924     bool LaneUsed[2] = {false, false};
15925     for (int i = 0; i < Size; ++i)
15926       if (Mask[i] >= 0)
15927         LaneUsed[(Mask[i] % Size) / LaneSize] = true;
15928     if (!LaneUsed[0] || !LaneUsed[1])
15929       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15930   }
15931 
15932   // TODO - we could support shuffling V2 in the Flipped input.
15933   assert(V2.isUndef() &&
15934          "This last part of this routine only works on single input shuffles");
15935 
15936   SmallVector<int, 32> InLaneMask(Mask.begin(), Mask.end());
15937   for (int i = 0; i < Size; ++i) {
15938     int &M = InLaneMask[i];
15939     if (M < 0)
15940       continue;
15941     if (((M % Size) / LaneSize) != (i / LaneSize))
15942       M = (M % LaneSize) + ((i / LaneSize) * LaneSize) + Size;
15943   }
15944   assert(!is128BitLaneCrossingShuffleMask(VT, InLaneMask) &&
15945          "In-lane shuffle mask expected");
15946 
15947   // Flip the lanes, and shuffle the results which should now be in-lane.
15948   MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
15949   SDValue Flipped = DAG.getBitcast(PVT, V1);
15950   Flipped =
15951       DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT), {2, 3, 0, 1});
15952   Flipped = DAG.getBitcast(VT, Flipped);
15953   return DAG.getVectorShuffle(VT, DL, V1, Flipped, InLaneMask);
15954 }
15955 
15956 /// Handle lowering 2-lane 128-bit shuffles.
15957 static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
15958                                   SDValue V2, ArrayRef<int> Mask,
15959                                   const APInt &Zeroable,
15960                                   const X86Subtarget &Subtarget,
15961                                   SelectionDAG &DAG) {
15962   // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
15963   if (Subtarget.hasAVX2() && V2.isUndef())
15964     return SDValue();
15965 
15966   bool V2IsZero = !V2.isUndef() && ISD::isBuildVectorAllZeros(V2.getNode());
15967 
15968   SmallVector<int, 4> WidenedMask;
15969   if (!canWidenShuffleElements(Mask, Zeroable, V2IsZero, WidenedMask))
15970     return SDValue();
15971 
15972   bool IsLowZero = (Zeroable & 0x3) == 0x3;
15973   bool IsHighZero = (Zeroable & 0xc) == 0xc;
15974 
15975   // Try to use an insert into a zero vector.
15976   if (WidenedMask[0] == 0 && IsHighZero) {
15977     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15978     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15979                               DAG.getIntPtrConstant(0, DL));
15980     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15981                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
15982                        DAG.getIntPtrConstant(0, DL));
15983   }
15984 
15985   // TODO: If minimizing size and one of the inputs is a zero vector and the
15986   // the zero vector has only one use, we could use a VPERM2X128 to save the
15987   // instruction bytes needed to explicitly generate the zero vector.
15988 
15989   // Blends are faster and handle all the non-lane-crossing cases.
15990   if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
15991                                           Subtarget, DAG))
15992     return Blend;
15993 
15994   // If either input operand is a zero vector, use VPERM2X128 because its mask
15995   // allows us to replace the zero input with an implicit zero.
15996   if (!IsLowZero && !IsHighZero) {
15997     // Check for patterns which can be matched with a single insert of a 128-bit
15998     // subvector.
15999     bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 0, 1}, V1, V2);
16000     if (OnlyUsesV1 || isShuffleEquivalent(Mask, {0, 1, 4, 5}, V1, V2)) {
16001 
16002       // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
16003       // this will likely become vinsertf128 which can't fold a 256-bit memop.
16004       if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
16005         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
16006         SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
16007                                      OnlyUsesV1 ? V1 : V2,
16008                                      DAG.getIntPtrConstant(0, DL));
16009         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
16010                            DAG.getIntPtrConstant(2, DL));
16011       }
16012     }
16013 
16014     // Try to use SHUF128 if possible.
16015     if (Subtarget.hasVLX()) {
16016       if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
16017         unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
16018                             ((WidenedMask[1] % 2) << 1);
16019         return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
16020                            DAG.getTargetConstant(PermMask, DL, MVT::i8));
16021       }
16022     }
16023   }
16024 
16025   // Otherwise form a 128-bit permutation. After accounting for undefs,
16026   // convert the 64-bit shuffle mask selection values into 128-bit
16027   // selection bits by dividing the indexes by 2 and shifting into positions
16028   // defined by a vperm2*128 instruction's immediate control byte.
16029 
16030   // The immediate permute control byte looks like this:
16031   //    [1:0] - select 128 bits from sources for low half of destination
16032   //    [2]   - ignore
16033   //    [3]   - zero low half of destination
16034   //    [5:4] - select 128 bits from sources for high half of destination
16035   //    [6]   - ignore
16036   //    [7]   - zero high half of destination
16037 
16038   assert((WidenedMask[0] >= 0 || IsLowZero) &&
16039          (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?");
16040 
16041   unsigned PermMask = 0;
16042   PermMask |= IsLowZero  ? 0x08 : (WidenedMask[0] << 0);
16043   PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
16044 
16045   // Check the immediate mask and replace unused sources with undef.
16046   if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
16047     V1 = DAG.getUNDEF(VT);
16048   if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
16049     V2 = DAG.getUNDEF(VT);
16050 
16051   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
16052                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
16053 }
16054 
16055 /// Lower a vector shuffle by first fixing the 128-bit lanes and then
16056 /// shuffling each lane.
16057 ///
16058 /// This attempts to create a repeated lane shuffle where each lane uses one
16059 /// or two of the lanes of the inputs. The lanes of the input vectors are
16060 /// shuffled in one or two independent shuffles to get the lanes into the
16061 /// position needed by the final shuffle.
16062 static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
16063     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16064     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16065   assert(!V2.isUndef() && "This is only useful with multiple inputs.");
16066 
16067   if (is128BitLaneRepeatedShuffleMask(VT, Mask))
16068     return SDValue();
16069 
16070   int NumElts = Mask.size();
16071   int NumLanes = VT.getSizeInBits() / 128;
16072   int NumLaneElts = 128 / VT.getScalarSizeInBits();
16073   SmallVector<int, 16> RepeatMask(NumLaneElts, -1);
16074   SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
16075 
16076   // First pass will try to fill in the RepeatMask from lanes that need two
16077   // sources.
16078   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16079     int Srcs[2] = {-1, -1};
16080     SmallVector<int, 16> InLaneMask(NumLaneElts, -1);
16081     for (int i = 0; i != NumLaneElts; ++i) {
16082       int M = Mask[(Lane * NumLaneElts) + i];
16083       if (M < 0)
16084         continue;
16085       // Determine which of the possible input lanes (NumLanes from each source)
16086       // this element comes from. Assign that as one of the sources for this
16087       // lane. We can assign up to 2 sources for this lane. If we run out
16088       // sources we can't do anything.
16089       int LaneSrc = M / NumLaneElts;
16090       int Src;
16091       if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
16092         Src = 0;
16093       else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
16094         Src = 1;
16095       else
16096         return SDValue();
16097 
16098       Srcs[Src] = LaneSrc;
16099       InLaneMask[i] = (M % NumLaneElts) + Src * NumElts;
16100     }
16101 
16102     // If this lane has two sources, see if it fits with the repeat mask so far.
16103     if (Srcs[1] < 0)
16104       continue;
16105 
16106     LaneSrcs[Lane][0] = Srcs[0];
16107     LaneSrcs[Lane][1] = Srcs[1];
16108 
16109     auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
16110       assert(M1.size() == M2.size() && "Unexpected mask size");
16111       for (int i = 0, e = M1.size(); i != e; ++i)
16112         if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
16113           return false;
16114       return true;
16115     };
16116 
16117     auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
16118       assert(Mask.size() == MergedMask.size() && "Unexpected mask size");
16119       for (int i = 0, e = MergedMask.size(); i != e; ++i) {
16120         int M = Mask[i];
16121         if (M < 0)
16122           continue;
16123         assert((MergedMask[i] < 0 || MergedMask[i] == M) &&
16124                "Unexpected mask element");
16125         MergedMask[i] = M;
16126       }
16127     };
16128 
16129     if (MatchMasks(InLaneMask, RepeatMask)) {
16130       // Merge this lane mask into the final repeat mask.
16131       MergeMasks(InLaneMask, RepeatMask);
16132       continue;
16133     }
16134 
16135     // Didn't find a match. Swap the operands and try again.
16136     std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
16137     ShuffleVectorSDNode::commuteMask(InLaneMask);
16138 
16139     if (MatchMasks(InLaneMask, RepeatMask)) {
16140       // Merge this lane mask into the final repeat mask.
16141       MergeMasks(InLaneMask, RepeatMask);
16142       continue;
16143     }
16144 
16145     // Couldn't find a match with the operands in either order.
16146     return SDValue();
16147   }
16148 
16149   // Now handle any lanes with only one source.
16150   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16151     // If this lane has already been processed, skip it.
16152     if (LaneSrcs[Lane][0] >= 0)
16153       continue;
16154 
16155     for (int i = 0; i != NumLaneElts; ++i) {
16156       int M = Mask[(Lane * NumLaneElts) + i];
16157       if (M < 0)
16158         continue;
16159 
16160       // If RepeatMask isn't defined yet we can define it ourself.
16161       if (RepeatMask[i] < 0)
16162         RepeatMask[i] = M % NumLaneElts;
16163 
16164       if (RepeatMask[i] < NumElts) {
16165         if (RepeatMask[i] != M % NumLaneElts)
16166           return SDValue();
16167         LaneSrcs[Lane][0] = M / NumLaneElts;
16168       } else {
16169         if (RepeatMask[i] != ((M % NumLaneElts) + NumElts))
16170           return SDValue();
16171         LaneSrcs[Lane][1] = M / NumLaneElts;
16172       }
16173     }
16174 
16175     if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
16176       return SDValue();
16177   }
16178 
16179   SmallVector<int, 16> NewMask(NumElts, -1);
16180   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16181     int Src = LaneSrcs[Lane][0];
16182     for (int i = 0; i != NumLaneElts; ++i) {
16183       int M = -1;
16184       if (Src >= 0)
16185         M = Src * NumLaneElts + i;
16186       NewMask[Lane * NumLaneElts + i] = M;
16187     }
16188   }
16189   SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16190   // Ensure we didn't get back the shuffle we started with.
16191   // FIXME: This is a hack to make up for some splat handling code in
16192   // getVectorShuffle.
16193   if (isa<ShuffleVectorSDNode>(NewV1) &&
16194       cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
16195     return SDValue();
16196 
16197   for (int Lane = 0; Lane != NumLanes; ++Lane) {
16198     int Src = LaneSrcs[Lane][1];
16199     for (int i = 0; i != NumLaneElts; ++i) {
16200       int M = -1;
16201       if (Src >= 0)
16202         M = Src * NumLaneElts + i;
16203       NewMask[Lane * NumLaneElts + i] = M;
16204     }
16205   }
16206   SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16207   // Ensure we didn't get back the shuffle we started with.
16208   // FIXME: This is a hack to make up for some splat handling code in
16209   // getVectorShuffle.
16210   if (isa<ShuffleVectorSDNode>(NewV2) &&
16211       cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
16212     return SDValue();
16213 
16214   for (int i = 0; i != NumElts; ++i) {
16215     NewMask[i] = RepeatMask[i % NumLaneElts];
16216     if (NewMask[i] < 0)
16217       continue;
16218 
16219     NewMask[i] += (i / NumLaneElts) * NumLaneElts;
16220   }
16221   return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
16222 }
16223 
16224 /// If the input shuffle mask results in a vector that is undefined in all upper
16225 /// or lower half elements and that mask accesses only 2 halves of the
16226 /// shuffle's operands, return true. A mask of half the width with mask indexes
16227 /// adjusted to access the extracted halves of the original shuffle operands is
16228 /// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
16229 /// lower half of each input operand is accessed.
16230 static bool
16231 getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
16232                    int &HalfIdx1, int &HalfIdx2) {
16233   assert((Mask.size() == HalfMask.size() * 2) &&
16234          "Expected input mask to be twice as long as output");
16235 
16236   // Exactly one half of the result must be undef to allow narrowing.
16237   bool UndefLower = isUndefLowerHalf(Mask);
16238   bool UndefUpper = isUndefUpperHalf(Mask);
16239   if (UndefLower == UndefUpper)
16240     return false;
16241 
16242   unsigned HalfNumElts = HalfMask.size();
16243   unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
16244   HalfIdx1 = -1;
16245   HalfIdx2 = -1;
16246   for (unsigned i = 0; i != HalfNumElts; ++i) {
16247     int M = Mask[i + MaskIndexOffset];
16248     if (M < 0) {
16249       HalfMask[i] = M;
16250       continue;
16251     }
16252 
16253     // Determine which of the 4 half vectors this element is from.
16254     // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
16255     int HalfIdx = M / HalfNumElts;
16256 
16257     // Determine the element index into its half vector source.
16258     int HalfElt = M % HalfNumElts;
16259 
16260     // We can shuffle with up to 2 half vectors, set the new 'half'
16261     // shuffle mask accordingly.
16262     if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
16263       HalfMask[i] = HalfElt;
16264       HalfIdx1 = HalfIdx;
16265       continue;
16266     }
16267     if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
16268       HalfMask[i] = HalfElt + HalfNumElts;
16269       HalfIdx2 = HalfIdx;
16270       continue;
16271     }
16272 
16273     // Too many half vectors referenced.
16274     return false;
16275   }
16276 
16277   return true;
16278 }
16279 
16280 /// Given the output values from getHalfShuffleMask(), create a half width
16281 /// shuffle of extracted vectors followed by an insert back to full width.
16282 static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
16283                                      ArrayRef<int> HalfMask, int HalfIdx1,
16284                                      int HalfIdx2, bool UndefLower,
16285                                      SelectionDAG &DAG, bool UseConcat = false) {
16286   assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?");
16287   assert(V1.getValueType().isSimple() && "Expecting only simple types");
16288 
16289   MVT VT = V1.getSimpleValueType();
16290   MVT HalfVT = VT.getHalfNumVectorElementsVT();
16291   unsigned HalfNumElts = HalfVT.getVectorNumElements();
16292 
16293   auto getHalfVector = [&](int HalfIdx) {
16294     if (HalfIdx < 0)
16295       return DAG.getUNDEF(HalfVT);
16296     SDValue V = (HalfIdx < 2 ? V1 : V2);
16297     HalfIdx = (HalfIdx % 2) * HalfNumElts;
16298     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
16299                        DAG.getIntPtrConstant(HalfIdx, DL));
16300   };
16301 
16302   // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
16303   SDValue Half1 = getHalfVector(HalfIdx1);
16304   SDValue Half2 = getHalfVector(HalfIdx2);
16305   SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
16306   if (UseConcat) {
16307     SDValue Op0 = V;
16308     SDValue Op1 = DAG.getUNDEF(HalfVT);
16309     if (UndefLower)
16310       std::swap(Op0, Op1);
16311     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Op0, Op1);
16312   }
16313 
16314   unsigned Offset = UndefLower ? HalfNumElts : 0;
16315   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
16316                      DAG.getIntPtrConstant(Offset, DL));
16317 }
16318 
16319 /// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
16320 /// This allows for fast cases such as subvector extraction/insertion
16321 /// or shuffling smaller vector types which can lower more efficiently.
16322 static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
16323                                          SDValue V2, ArrayRef<int> Mask,
16324                                          const X86Subtarget &Subtarget,
16325                                          SelectionDAG &DAG) {
16326   assert((VT.is256BitVector() || VT.is512BitVector()) &&
16327          "Expected 256-bit or 512-bit vector");
16328 
16329   bool UndefLower = isUndefLowerHalf(Mask);
16330   if (!UndefLower && !isUndefUpperHalf(Mask))
16331     return SDValue();
16332 
16333   assert((!UndefLower || !isUndefUpperHalf(Mask)) &&
16334          "Completely undef shuffle mask should have been simplified already");
16335 
16336   // Upper half is undef and lower half is whole upper subvector.
16337   // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16338   MVT HalfVT = VT.getHalfNumVectorElementsVT();
16339   unsigned HalfNumElts = HalfVT.getVectorNumElements();
16340   if (!UndefLower &&
16341       isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
16342     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16343                              DAG.getIntPtrConstant(HalfNumElts, DL));
16344     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16345                        DAG.getIntPtrConstant(0, DL));
16346   }
16347 
16348   // Lower half is undef and upper half is whole lower subvector.
16349   // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16350   if (UndefLower &&
16351       isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
16352     SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
16353                              DAG.getIntPtrConstant(0, DL));
16354     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
16355                        DAG.getIntPtrConstant(HalfNumElts, DL));
16356   }
16357 
16358   int HalfIdx1, HalfIdx2;
16359   SmallVector<int, 8> HalfMask(HalfNumElts);
16360   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
16361     return SDValue();
16362 
16363   assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
16364 
16365   // Only shuffle the halves of the inputs when useful.
16366   unsigned NumLowerHalves =
16367       (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
16368   unsigned NumUpperHalves =
16369       (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
16370   assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed");
16371 
16372   // Determine the larger pattern of undef/halves, then decide if it's worth
16373   // splitting the shuffle based on subtarget capabilities and types.
16374   unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
16375   if (!UndefLower) {
16376     // XXXXuuuu: no insert is needed.
16377     // Always extract lowers when setting lower - these are all free subreg ops.
16378     if (NumUpperHalves == 0)
16379       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16380                                    UndefLower, DAG);
16381 
16382     if (NumUpperHalves == 1) {
16383       // AVX2 has efficient 32/64-bit element cross-lane shuffles.
16384       if (Subtarget.hasAVX2()) {
16385         // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
16386         if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
16387             !is128BitUnpackShuffleMask(HalfMask) &&
16388             (!isSingleSHUFPSMask(HalfMask) ||
16389              Subtarget.hasFastVariableShuffle()))
16390           return SDValue();
16391         // If this is a unary shuffle (assume that the 2nd operand is
16392         // canonicalized to undef), then we can use vpermpd. Otherwise, we
16393         // are better off extracting the upper half of 1 operand and using a
16394         // narrow shuffle.
16395         if (EltWidth == 64 && V2.isUndef())
16396           return SDValue();
16397       }
16398       // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16399       if (Subtarget.hasAVX512() && VT.is512BitVector())
16400         return SDValue();
16401       // Extract + narrow shuffle is better than the wide alternative.
16402       return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16403                                    UndefLower, DAG);
16404     }
16405 
16406     // Don't extract both uppers, instead shuffle and then extract.
16407     assert(NumUpperHalves == 2 && "Half vector count went wrong");
16408     return SDValue();
16409   }
16410 
16411   // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
16412   if (NumUpperHalves == 0) {
16413     // AVX2 has efficient 64-bit element cross-lane shuffles.
16414     // TODO: Refine to account for unary shuffle, splat, and other masks?
16415     if (Subtarget.hasAVX2() && EltWidth == 64)
16416       return SDValue();
16417     // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
16418     if (Subtarget.hasAVX512() && VT.is512BitVector())
16419       return SDValue();
16420     // Narrow shuffle + insert is better than the wide alternative.
16421     return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
16422                                  UndefLower, DAG);
16423   }
16424 
16425   // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
16426   return SDValue();
16427 }
16428 
16429 /// Test whether the specified input (0 or 1) is in-place blended by the
16430 /// given mask.
16431 ///
16432 /// This returns true if the elements from a particular input are already in the
16433 /// slot required by the given mask and require no permutation.
16434 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
16435   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
16436   int Size = Mask.size();
16437   for (int i = 0; i < Size; ++i)
16438     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
16439       return false;
16440 
16441   return true;
16442 }
16443 
16444 /// Handle case where shuffle sources are coming from the same 128-bit lane and
16445 /// every lane can be represented as the same repeating mask - allowing us to
16446 /// shuffle the sources with the repeating shuffle and then permute the result
16447 /// to the destination lanes.
16448 static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
16449     const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
16450     const X86Subtarget &Subtarget, SelectionDAG &DAG) {
16451   int NumElts = VT.getVectorNumElements();
16452   int NumLanes = VT.getSizeInBits() / 128;
16453   int NumLaneElts = NumElts / NumLanes;
16454 
16455   // On AVX2 we may be able to just shuffle the lowest elements and then
16456   // broadcast the result.
16457   if (Subtarget.hasAVX2()) {
16458     for (unsigned BroadcastSize : {16, 32, 64}) {
16459       if (BroadcastSize <= VT.getScalarSizeInBits())
16460         continue;
16461       int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
16462 
16463       // Attempt to match a repeating pattern every NumBroadcastElts,
16464       // accounting for UNDEFs but only references the lowest 128-bit
16465       // lane of the inputs.
16466       auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
16467         for (int i = 0; i != NumElts; i += NumBroadcastElts)
16468           for (int j = 0; j != NumBroadcastElts; ++j) {
16469             int M = Mask[i + j];
16470             if (M < 0)
16471               continue;
16472             int &R = RepeatMask[j];
16473             if (0 != ((M % NumElts) / NumLaneElts))
16474               return false;
16475             if (0 <= R && R != M)
16476               return false;
16477             R = M;
16478           }
16479         return true;
16480       };
16481 
16482       SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
16483       if (!FindRepeatingBroadcastMask(RepeatMask))
16484         continue;
16485 
16486       // Shuffle the (lowest) repeated elements in place for broadcast.
16487       SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
16488 
16489       // Shuffle the actual broadcast.
16490       SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
16491       for (int i = 0; i != NumElts; i += NumBroadcastElts)
16492         for (int j = 0; j != NumBroadcastElts; ++j)
16493           BroadcastMask[i + j] = j;
16494       return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
16495                                   BroadcastMask);
16496     }
16497   }
16498 
16499   // Bail if the shuffle mask doesn't cross 128-bit lanes.
16500   if (!is128BitLaneCrossingShuffleMask(VT, Mask))
16501     return SDValue();
16502 
16503   // Bail if we already have a repeated lane shuffle mask.
16504   SmallVector<int, 8> RepeatedShuffleMask;
16505   if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
16506     return SDValue();
16507 
16508   // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
16509   // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
16510   int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
16511   int NumSubLanes = NumLanes * SubLaneScale;
16512   int NumSubLaneElts = NumLaneElts / SubLaneScale;
16513 
16514   // Check that all the sources are coming from the same lane and see if we can
16515   // form a repeating shuffle mask (local to each sub-lane). At the same time,
16516   // determine the source sub-lane for each destination sub-lane.
16517   int TopSrcSubLane = -1;
16518   SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
16519   SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
16520       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
16521       SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
16522 
16523   for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
16524     // Extract the sub-lane mask, check that it all comes from the same lane
16525     // and normalize the mask entries to come from the first lane.
16526     int SrcLane = -1;
16527     SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
16528     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16529       int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
16530       if (M < 0)
16531         continue;
16532       int Lane = (M % NumElts) / NumLaneElts;
16533       if ((0 <= SrcLane) && (SrcLane != Lane))
16534         return SDValue();
16535       SrcLane = Lane;
16536       int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
16537       SubLaneMask[Elt] = LocalM;
16538     }
16539 
16540     // Whole sub-lane is UNDEF.
16541     if (SrcLane < 0)
16542       continue;
16543 
16544     // Attempt to match against the candidate repeated sub-lane masks.
16545     for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
16546       auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
16547         for (int i = 0; i != NumSubLaneElts; ++i) {
16548           if (M1[i] < 0 || M2[i] < 0)
16549             continue;
16550           if (M1[i] != M2[i])
16551             return false;
16552         }
16553         return true;
16554       };
16555 
16556       auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
16557       if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
16558         continue;
16559 
16560       // Merge the sub-lane mask into the matching repeated sub-lane mask.
16561       for (int i = 0; i != NumSubLaneElts; ++i) {
16562         int M = SubLaneMask[i];
16563         if (M < 0)
16564           continue;
16565         assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&
16566                "Unexpected mask element");
16567         RepeatedSubLaneMask[i] = M;
16568       }
16569 
16570       // Track the top most source sub-lane - by setting the remaining to UNDEF
16571       // we can greatly simplify shuffle matching.
16572       int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
16573       TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
16574       Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
16575       break;
16576     }
16577 
16578     // Bail if we failed to find a matching repeated sub-lane mask.
16579     if (Dst2SrcSubLanes[DstSubLane] < 0)
16580       return SDValue();
16581   }
16582   assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&
16583          "Unexpected source lane");
16584 
16585   // Create a repeating shuffle mask for the entire vector.
16586   SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
16587   for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
16588     int Lane = SubLane / SubLaneScale;
16589     auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
16590     for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
16591       int M = RepeatedSubLaneMask[Elt];
16592       if (M < 0)
16593         continue;
16594       int Idx = (SubLane * NumSubLaneElts) + Elt;
16595       RepeatedMask[Idx] = M + (Lane * NumLaneElts);
16596     }
16597   }
16598   SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
16599 
16600   // Shuffle each source sub-lane to its destination.
16601   SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
16602   for (int i = 0; i != NumElts; i += NumSubLaneElts) {
16603     int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
16604     if (SrcSubLane < 0)
16605       continue;
16606     for (int j = 0; j != NumSubLaneElts; ++j)
16607       SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
16608   }
16609 
16610   return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
16611                               SubLaneMask);
16612 }
16613 
16614 static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
16615                                    bool &ForceV1Zero, bool &ForceV2Zero,
16616                                    unsigned &ShuffleImm, ArrayRef<int> Mask,
16617                                    const APInt &Zeroable) {
16618   int NumElts = VT.getVectorNumElements();
16619   assert(VT.getScalarSizeInBits() == 64 &&
16620          (NumElts == 2 || NumElts == 4 || NumElts == 8) &&
16621          "Unexpected data type for VSHUFPD");
16622   assert(isUndefOrZeroOrInRange(Mask, 0, 2 * NumElts) &&
16623          "Illegal shuffle mask");
16624 
16625   bool ZeroLane[2] = { true, true };
16626   for (int i = 0; i < NumElts; ++i)
16627     ZeroLane[i & 1] &= Zeroable[i];
16628 
16629   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
16630   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
16631   ShuffleImm = 0;
16632   bool ShufpdMask = true;
16633   bool CommutableMask = true;
16634   for (int i = 0; i < NumElts; ++i) {
16635     if (Mask[i] == SM_SentinelUndef || ZeroLane[i & 1])
16636       continue;
16637     if (Mask[i] < 0)
16638       return false;
16639     int Val = (i & 6) + NumElts * (i & 1);
16640     int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
16641     if (Mask[i] < Val || Mask[i] > Val + 1)
16642       ShufpdMask = false;
16643     if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
16644       CommutableMask = false;
16645     ShuffleImm |= (Mask[i] % 2) << i;
16646   }
16647 
16648   if (!ShufpdMask && !CommutableMask)
16649     return false;
16650 
16651   if (!ShufpdMask && CommutableMask)
16652     std::swap(V1, V2);
16653 
16654   ForceV1Zero = ZeroLane[0];
16655   ForceV2Zero = ZeroLane[1];
16656   return true;
16657 }
16658 
16659 static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT, SDValue V1,
16660                                       SDValue V2, ArrayRef<int> Mask,
16661                                       const APInt &Zeroable,
16662                                       const X86Subtarget &Subtarget,
16663                                       SelectionDAG &DAG) {
16664   assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64) &&
16665          "Unexpected data type for VSHUFPD");
16666 
16667   unsigned Immediate = 0;
16668   bool ForceV1Zero = false, ForceV2Zero = false;
16669   if (!matchShuffleWithSHUFPD(VT, V1, V2, ForceV1Zero, ForceV2Zero, Immediate,
16670                               Mask, Zeroable))
16671     return SDValue();
16672 
16673   // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
16674   if (ForceV1Zero)
16675     V1 = getZeroVector(VT, Subtarget, DAG, DL);
16676   if (ForceV2Zero)
16677     V2 = getZeroVector(VT, Subtarget, DAG, DL);
16678 
16679   return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
16680                      DAG.getTargetConstant(Immediate, DL, MVT::i8));
16681 }
16682 
16683 // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
16684 // by zeroable elements in the remaining 24 elements. Turn this into two
16685 // vmovqb instructions shuffled together.
16686 static SDValue lowerShuffleAsVTRUNCAndUnpack(const SDLoc &DL, MVT VT,
16687                                              SDValue V1, SDValue V2,
16688                                              ArrayRef<int> Mask,
16689                                              const APInt &Zeroable,
16690                                              SelectionDAG &DAG) {
16691   assert(VT == MVT::v32i8 && "Unexpected type!");
16692 
16693   // The first 8 indices should be every 8th element.
16694   if (!isSequentialOrUndefInRange(Mask, 0, 8, 0, 8))
16695     return SDValue();
16696 
16697   // Remaining elements need to be zeroable.
16698   if (Zeroable.countLeadingOnes() < (Mask.size() - 8))
16699     return SDValue();
16700 
16701   V1 = DAG.getBitcast(MVT::v4i64, V1);
16702   V2 = DAG.getBitcast(MVT::v4i64, V2);
16703 
16704   V1 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V1);
16705   V2 = DAG.getNode(X86ISD::VTRUNC, DL, MVT::v16i8, V2);
16706 
16707   // The VTRUNCs will put 0s in the upper 12 bytes. Use them to put zeroes in
16708   // the upper bits of the result using an unpckldq.
16709   SDValue Unpack = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2,
16710                                         { 0, 1, 2, 3, 16, 17, 18, 19,
16711                                           4, 5, 6, 7, 20, 21, 22, 23 });
16712   // Insert the unpckldq into a zero vector to widen to v32i8.
16713   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v32i8,
16714                      DAG.getConstant(0, DL, MVT::v32i8), Unpack,
16715                      DAG.getIntPtrConstant(0, DL));
16716 }
16717 
16718 
16719 /// Handle lowering of 4-lane 64-bit floating point shuffles.
16720 ///
16721 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
16722 /// isn't available.
16723 static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16724                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16725                                  const X86Subtarget &Subtarget,
16726                                  SelectionDAG &DAG) {
16727   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16728   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
16729   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16730 
16731   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
16732                                      Subtarget, DAG))
16733     return V;
16734 
16735   if (V2.isUndef()) {
16736     // Check for being able to broadcast a single element.
16737     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
16738                                                     Mask, Subtarget, DAG))
16739       return Broadcast;
16740 
16741     // Use low duplicate instructions for masks that match their pattern.
16742     if (isShuffleEquivalent(Mask, {0, 0, 2, 2}, V1, V2))
16743       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
16744 
16745     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
16746       // Non-half-crossing single input shuffles can be lowered with an
16747       // interleaved permutation.
16748       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
16749                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
16750       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
16751                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
16752     }
16753 
16754     // With AVX2 we have direct support for this permutation.
16755     if (Subtarget.hasAVX2())
16756       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
16757                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16758 
16759     // Try to create an in-lane repeating shuffle mask and then shuffle the
16760     // results into the target lanes.
16761     if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16762             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16763       return V;
16764 
16765     // Try to permute the lanes and then use a per-lane permute.
16766     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
16767                                                         Mask, DAG, Subtarget))
16768       return V;
16769 
16770     // Otherwise, fall back.
16771     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v4f64, V1, V2, Mask,
16772                                                DAG, Subtarget);
16773   }
16774 
16775   // Use dedicated unpack instructions for masks that match their pattern.
16776   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
16777     return V;
16778 
16779   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
16780                                           Zeroable, Subtarget, DAG))
16781     return Blend;
16782 
16783   // Check if the blend happens to exactly fit that of SHUFPD.
16784   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, V1, V2, Mask,
16785                                           Zeroable, Subtarget, DAG))
16786     return Op;
16787 
16788   // If we have lane crossing shuffles AND they don't all come from the lower
16789   // lane elements, lower to SHUFPD(VPERM2F128(V1, V2), VPERM2F128(V1, V2)).
16790   // TODO: Handle BUILD_VECTOR sources which getVectorShuffle currently
16791   // canonicalize to a blend of splat which isn't necessary for this combine.
16792   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask) &&
16793       !all_of(Mask, [](int M) { return M < 2 || (4 <= M && M < 6); }) &&
16794       (V1.getOpcode() != ISD::BUILD_VECTOR) &&
16795       (V2.getOpcode() != ISD::BUILD_VECTOR))
16796     if (SDValue Op = lowerShuffleAsLanePermuteAndSHUFP(DL, MVT::v4f64, V1, V2,
16797                                                        Mask, DAG))
16798       return Op;
16799 
16800   // If we have one input in place, then we can permute the other input and
16801   // blend the result.
16802   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
16803     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16804                                                 Subtarget, DAG);
16805 
16806   // Try to create an in-lane repeating shuffle mask and then shuffle the
16807   // results into the target lanes.
16808   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16809           DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16810     return V;
16811 
16812   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16813   // shuffle. However, if we have AVX2 and either inputs are already in place,
16814   // we will be able to shuffle even across lanes the other input in a single
16815   // instruction so skip this pattern.
16816   if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
16817                                 isShuffleMaskInputInPlace(1, Mask))))
16818     if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
16819             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
16820       return V;
16821 
16822   // If we have VLX support, we can use VEXPAND.
16823   if (Subtarget.hasVLX())
16824     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
16825                                          DAG, Subtarget))
16826       return V;
16827 
16828   // If we have AVX2 then we always want to lower with a blend because an v4 we
16829   // can fully permute the elements.
16830   if (Subtarget.hasAVX2())
16831     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4f64, V1, V2, Mask,
16832                                                 Subtarget, DAG);
16833 
16834   // Otherwise fall back on generic lowering.
16835   return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
16836                                     Subtarget, DAG);
16837 }
16838 
16839 /// Handle lowering of 4-lane 64-bit integer shuffles.
16840 ///
16841 /// This routine is only called when we have AVX2 and thus a reasonable
16842 /// instruction set for v4i64 shuffling..
16843 static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16844                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16845                                  const X86Subtarget &Subtarget,
16846                                  SelectionDAG &DAG) {
16847   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16848   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
16849   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
16850   assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!");
16851 
16852   if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
16853                                      Subtarget, DAG))
16854     return V;
16855 
16856   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
16857                                           Zeroable, Subtarget, DAG))
16858     return Blend;
16859 
16860   // Check for being able to broadcast a single element.
16861   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
16862                                                   Subtarget, DAG))
16863     return Broadcast;
16864 
16865   if (V2.isUndef()) {
16866     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
16867     // can use lower latency instructions that will operate on both lanes.
16868     SmallVector<int, 2> RepeatedMask;
16869     if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
16870       SmallVector<int, 4> PSHUFDMask;
16871       narrowShuffleMaskElts(2, RepeatedMask, PSHUFDMask);
16872       return DAG.getBitcast(
16873           MVT::v4i64,
16874           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
16875                       DAG.getBitcast(MVT::v8i32, V1),
16876                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
16877     }
16878 
16879     // AVX2 provides a direct instruction for permuting a single input across
16880     // lanes.
16881     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
16882                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
16883   }
16884 
16885   // Try to use shift instructions.
16886   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
16887                                           Zeroable, Subtarget, DAG))
16888     return Shift;
16889 
16890   // If we have VLX support, we can use VALIGN or VEXPAND.
16891   if (Subtarget.hasVLX()) {
16892     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v4i64, V1, V2, Mask,
16893                                               Subtarget, DAG))
16894       return Rotate;
16895 
16896     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
16897                                          DAG, Subtarget))
16898       return V;
16899   }
16900 
16901   // Try to use PALIGNR.
16902   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
16903                                                 Subtarget, DAG))
16904     return Rotate;
16905 
16906   // Use dedicated unpack instructions for masks that match their pattern.
16907   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
16908     return V;
16909 
16910   // If we have one input in place, then we can permute the other input and
16911   // blend the result.
16912   if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
16913     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
16914                                                 Subtarget, DAG);
16915 
16916   // Try to create an in-lane repeating shuffle mask and then shuffle the
16917   // results into the target lanes.
16918   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16919           DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16920     return V;
16921 
16922   // Try to simplify this by merging 128-bit lanes to enable a lane-based
16923   // shuffle. However, if we have AVX2 and either inputs are already in place,
16924   // we will be able to shuffle even across lanes the other input in a single
16925   // instruction so skip this pattern.
16926   if (!isShuffleMaskInputInPlace(0, Mask) &&
16927       !isShuffleMaskInputInPlace(1, Mask))
16928     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16929             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
16930       return Result;
16931 
16932   // Otherwise fall back on generic blend lowering.
16933   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v4i64, V1, V2, Mask,
16934                                               Subtarget, DAG);
16935 }
16936 
16937 /// Handle lowering of 8-lane 32-bit floating point shuffles.
16938 ///
16939 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
16940 /// isn't available.
16941 static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16942                                  const APInt &Zeroable, SDValue V1, SDValue V2,
16943                                  const X86Subtarget &Subtarget,
16944                                  SelectionDAG &DAG) {
16945   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16946   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
16947   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
16948 
16949   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
16950                                           Zeroable, Subtarget, DAG))
16951     return Blend;
16952 
16953   // Check for being able to broadcast a single element.
16954   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
16955                                                   Subtarget, DAG))
16956     return Broadcast;
16957 
16958   // If the shuffle mask is repeated in each 128-bit lane, we have many more
16959   // options to efficiently lower the shuffle.
16960   SmallVector<int, 4> RepeatedMask;
16961   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
16962     assert(RepeatedMask.size() == 4 &&
16963            "Repeated masks must be half the mask width!");
16964 
16965     // Use even/odd duplicate instructions for masks that match their pattern.
16966     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
16967       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
16968     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
16969       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
16970 
16971     if (V2.isUndef())
16972       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
16973                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16974 
16975     // Use dedicated unpack instructions for masks that match their pattern.
16976     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
16977       return V;
16978 
16979     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
16980     // have already handled any direct blends.
16981     return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
16982   }
16983 
16984   // Try to create an in-lane repeating shuffle mask and then shuffle the
16985   // results into the target lanes.
16986   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16987           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
16988     return V;
16989 
16990   // If we have a single input shuffle with different shuffle patterns in the
16991   // two 128-bit lanes use the variable mask to VPERMILPS.
16992   if (V2.isUndef()) {
16993     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask)) {
16994       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16995       return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
16996     }
16997     if (Subtarget.hasAVX2()) {
16998       SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
16999       return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
17000     }
17001     // Otherwise, fall back.
17002     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v8f32, V1, V2, Mask,
17003                                                DAG, Subtarget);
17004   }
17005 
17006   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17007   // shuffle.
17008   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17009           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
17010     return Result;
17011 
17012   // If we have VLX support, we can use VEXPAND.
17013   if (Subtarget.hasVLX())
17014     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
17015                                          DAG, Subtarget))
17016       return V;
17017 
17018   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17019   // since after split we get a more efficient code using vpunpcklwd and
17020   // vpunpckhwd instrs than vblend.
17021   if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
17022     return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, Subtarget,
17023                                       DAG);
17024 
17025   // If we have AVX2 then we always want to lower with a blend because at v8 we
17026   // can fully permute the elements.
17027   if (Subtarget.hasAVX2())
17028     return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8f32, V1, V2, Mask,
17029                                                 Subtarget, DAG);
17030 
17031   // Otherwise fall back on generic lowering.
17032   return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
17033                                     Subtarget, DAG);
17034 }
17035 
17036 /// Handle lowering of 8-lane 32-bit integer shuffles.
17037 ///
17038 /// This routine is only called when we have AVX2 and thus a reasonable
17039 /// instruction set for v8i32 shuffling..
17040 static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17041                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17042                                  const X86Subtarget &Subtarget,
17043                                  SelectionDAG &DAG) {
17044   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17045   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
17046   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17047   assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!");
17048 
17049   // Whenever we can lower this as a zext, that instruction is strictly faster
17050   // than any alternative. It also allows us to fold memory operands into the
17051   // shuffle in many cases.
17052   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
17053                                                    Zeroable, Subtarget, DAG))
17054     return ZExt;
17055 
17056   // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
17057   // since after split we get a more efficient code than vblend by using
17058   // vpunpcklwd and vpunpckhwd instrs.
17059   if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
17060       !Subtarget.hasAVX512())
17061     return lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask, Subtarget,
17062                                       DAG);
17063 
17064   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
17065                                           Zeroable, Subtarget, DAG))
17066     return Blend;
17067 
17068   // Check for being able to broadcast a single element.
17069   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
17070                                                   Subtarget, DAG))
17071     return Broadcast;
17072 
17073   // If the shuffle mask is repeated in each 128-bit lane we can use more
17074   // efficient instructions that mirror the shuffles across the two 128-bit
17075   // lanes.
17076   SmallVector<int, 4> RepeatedMask;
17077   bool Is128BitLaneRepeatedShuffle =
17078       is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
17079   if (Is128BitLaneRepeatedShuffle) {
17080     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17081     if (V2.isUndef())
17082       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
17083                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17084 
17085     // Use dedicated unpack instructions for masks that match their pattern.
17086     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
17087       return V;
17088   }
17089 
17090   // Try to use shift instructions.
17091   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
17092                                           Zeroable, Subtarget, DAG))
17093     return Shift;
17094 
17095   // If we have VLX support, we can use VALIGN or EXPAND.
17096   if (Subtarget.hasVLX()) {
17097     if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i32, V1, V2, Mask,
17098                                               Subtarget, DAG))
17099       return Rotate;
17100 
17101     if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
17102                                          DAG, Subtarget))
17103       return V;
17104   }
17105 
17106   // Try to use byte rotation instructions.
17107   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
17108                                                 Subtarget, DAG))
17109     return Rotate;
17110 
17111   // Try to create an in-lane repeating shuffle mask and then shuffle the
17112   // results into the target lanes.
17113   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17114           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17115     return V;
17116 
17117   if (V2.isUndef()) {
17118     // Try to produce a fixed cross-128-bit lane permute followed by unpack
17119     // because that should be faster than the variable permute alternatives.
17120     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v8i32, Mask, V1, V2, DAG))
17121       return V;
17122 
17123     // If the shuffle patterns aren't repeated but it's a single input, directly
17124     // generate a cross-lane VPERMD instruction.
17125     SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
17126     return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
17127   }
17128 
17129   // Assume that a single SHUFPS is faster than an alternative sequence of
17130   // multiple instructions (even if the CPU has a domain penalty).
17131   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17132   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17133     SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
17134     SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
17135     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
17136                                             CastV1, CastV2, DAG);
17137     return DAG.getBitcast(MVT::v8i32, ShufPS);
17138   }
17139 
17140   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17141   // shuffle.
17142   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17143           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
17144     return Result;
17145 
17146   // Otherwise fall back on generic blend lowering.
17147   return lowerShuffleAsDecomposedShuffleMerge(DL, MVT::v8i32, V1, V2, Mask,
17148                                               Subtarget, DAG);
17149 }
17150 
17151 /// Handle lowering of 16-lane 16-bit integer shuffles.
17152 ///
17153 /// This routine is only called when we have AVX2 and thus a reasonable
17154 /// instruction set for v16i16 shuffling..
17155 static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17156                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17157                                   const X86Subtarget &Subtarget,
17158                                   SelectionDAG &DAG) {
17159   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17160   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
17161   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17162   assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!");
17163 
17164   // Whenever we can lower this as a zext, that instruction is strictly faster
17165   // than any alternative. It also allows us to fold memory operands into the
17166   // shuffle in many cases.
17167   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17168           DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17169     return ZExt;
17170 
17171   // Check for being able to broadcast a single element.
17172   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
17173                                                   Subtarget, DAG))
17174     return Broadcast;
17175 
17176   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
17177                                           Zeroable, Subtarget, DAG))
17178     return Blend;
17179 
17180   // Use dedicated unpack instructions for masks that match their pattern.
17181   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
17182     return V;
17183 
17184   // Use dedicated pack instructions for masks that match their pattern.
17185   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
17186                                        Subtarget))
17187     return V;
17188 
17189   // Try to use lower using a truncation.
17190   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v16i16, V1, V2, Mask, Zeroable,
17191                                        Subtarget, DAG))
17192     return V;
17193 
17194   // Try to use shift instructions.
17195   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
17196                                           Zeroable, Subtarget, DAG))
17197     return Shift;
17198 
17199   // Try to use byte rotation instructions.
17200   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
17201                                                 Subtarget, DAG))
17202     return Rotate;
17203 
17204   // Try to create an in-lane repeating shuffle mask and then shuffle the
17205   // results into the target lanes.
17206   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17207           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17208     return V;
17209 
17210   if (V2.isUndef()) {
17211     // Try to use bit rotation instructions.
17212     if (SDValue Rotate =
17213             lowerShuffleAsBitRotate(DL, MVT::v16i16, V1, Mask, Subtarget, DAG))
17214       return Rotate;
17215 
17216     // Try to produce a fixed cross-128-bit lane permute followed by unpack
17217     // because that should be faster than the variable permute alternatives.
17218     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v16i16, Mask, V1, V2, DAG))
17219       return V;
17220 
17221     // There are no generalized cross-lane shuffle operations available on i16
17222     // element types.
17223     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
17224       if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17225               DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17226         return V;
17227 
17228       return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v16i16, V1, V2, Mask,
17229                                                  DAG, Subtarget);
17230     }
17231 
17232     SmallVector<int, 8> RepeatedMask;
17233     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
17234       // As this is a single-input shuffle, the repeated mask should be
17235       // a strictly valid v8i16 mask that we can pass through to the v8i16
17236       // lowering to handle even the v16 case.
17237       return lowerV8I16GeneralSingleInputShuffle(
17238           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
17239     }
17240   }
17241 
17242   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
17243                                               Zeroable, Subtarget, DAG))
17244     return PSHUFB;
17245 
17246   // AVX512BW can lower to VPERMW (non-VLX will pad to v32i16).
17247   if (Subtarget.hasBWI())
17248     return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, Subtarget, DAG);
17249 
17250   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17251   // shuffle.
17252   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17253           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
17254     return Result;
17255 
17256   // Try to permute the lanes and then use a per-lane permute.
17257   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17258           DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
17259     return V;
17260 
17261   // Otherwise fall back on generic lowering.
17262   return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
17263                                     Subtarget, DAG);
17264 }
17265 
17266 /// Handle lowering of 32-lane 8-bit integer shuffles.
17267 ///
17268 /// This routine is only called when we have AVX2 and thus a reasonable
17269 /// instruction set for v32i8 shuffling..
17270 static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17271                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17272                                  const X86Subtarget &Subtarget,
17273                                  SelectionDAG &DAG) {
17274   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17275   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
17276   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17277   assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!");
17278 
17279   // Whenever we can lower this as a zext, that instruction is strictly faster
17280   // than any alternative. It also allows us to fold memory operands into the
17281   // shuffle in many cases.
17282   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
17283                                                    Zeroable, Subtarget, DAG))
17284     return ZExt;
17285 
17286   // Check for being able to broadcast a single element.
17287   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
17288                                                   Subtarget, DAG))
17289     return Broadcast;
17290 
17291   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
17292                                           Zeroable, Subtarget, DAG))
17293     return Blend;
17294 
17295   // Use dedicated unpack instructions for masks that match their pattern.
17296   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
17297     return V;
17298 
17299   // Use dedicated pack instructions for masks that match their pattern.
17300   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
17301                                        Subtarget))
17302     return V;
17303 
17304   // Try to use lower using a truncation.
17305   if (SDValue V = lowerShuffleAsVTRUNC(DL, MVT::v32i8, V1, V2, Mask, Zeroable,
17306                                        Subtarget, DAG))
17307     return V;
17308 
17309   // Try to use shift instructions.
17310   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
17311                                           Zeroable, Subtarget, DAG))
17312     return Shift;
17313 
17314   // Try to use byte rotation instructions.
17315   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
17316                                                 Subtarget, DAG))
17317     return Rotate;
17318 
17319   // Try to use bit rotation instructions.
17320   if (V2.isUndef())
17321     if (SDValue Rotate =
17322             lowerShuffleAsBitRotate(DL, MVT::v32i8, V1, Mask, Subtarget, DAG))
17323       return Rotate;
17324 
17325   // Try to create an in-lane repeating shuffle mask and then shuffle the
17326   // results into the target lanes.
17327   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17328           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17329     return V;
17330 
17331   // There are no generalized cross-lane shuffle operations available on i8
17332   // element types.
17333   if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
17334     // Try to produce a fixed cross-128-bit lane permute followed by unpack
17335     // because that should be faster than the variable permute alternatives.
17336     if (SDValue V = lowerShuffleWithUNPCK256(DL, MVT::v32i8, Mask, V1, V2, DAG))
17337       return V;
17338 
17339     if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17340             DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17341       return V;
17342 
17343     return lowerShuffleAsLanePermuteAndShuffle(DL, MVT::v32i8, V1, V2, Mask,
17344                                                DAG, Subtarget);
17345   }
17346 
17347   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
17348                                               Zeroable, Subtarget, DAG))
17349     return PSHUFB;
17350 
17351   // AVX512VBMI can lower to VPERMB (non-VLX will pad to v64i8).
17352   if (Subtarget.hasVBMI())
17353     return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, Subtarget, DAG);
17354 
17355   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17356   // shuffle.
17357   if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17358           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
17359     return Result;
17360 
17361   // Try to permute the lanes and then use a per-lane permute.
17362   if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
17363           DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
17364     return V;
17365 
17366   // Look for {0, 8, 16, 24, 32, 40, 48, 56 } in the first 8 elements. Followed
17367   // by zeroable elements in the remaining 24 elements. Turn this into two
17368   // vmovqb instructions shuffled together.
17369   if (Subtarget.hasVLX())
17370     if (SDValue V = lowerShuffleAsVTRUNCAndUnpack(DL, MVT::v32i8, V1, V2,
17371                                                   Mask, Zeroable, DAG))
17372       return V;
17373 
17374   // Otherwise fall back on generic lowering.
17375   return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
17376                                     Subtarget, DAG);
17377 }
17378 
17379 /// High-level routine to lower various 256-bit x86 vector shuffles.
17380 ///
17381 /// This routine either breaks down the specific type of a 256-bit x86 vector
17382 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
17383 /// together based on the available instructions.
17384 static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
17385                                   SDValue V1, SDValue V2, const APInt &Zeroable,
17386                                   const X86Subtarget &Subtarget,
17387                                   SelectionDAG &DAG) {
17388   // If we have a single input to the zero element, insert that into V1 if we
17389   // can do so cheaply.
17390   int NumElts = VT.getVectorNumElements();
17391   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17392 
17393   if (NumV2Elements == 1 && Mask[0] >= NumElts)
17394     if (SDValue Insertion = lowerShuffleAsElementInsertion(
17395             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17396       return Insertion;
17397 
17398   // Handle special cases where the lower or upper half is UNDEF.
17399   if (SDValue V =
17400           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17401     return V;
17402 
17403   // There is a really nice hard cut-over between AVX1 and AVX2 that means we
17404   // can check for those subtargets here and avoid much of the subtarget
17405   // querying in the per-vector-type lowering routines. With AVX1 we have
17406   // essentially *zero* ability to manipulate a 256-bit vector with integer
17407   // types. Since we'll use floating point types there eventually, just
17408   // immediately cast everything to a float and operate entirely in that domain.
17409   if (VT.isInteger() && !Subtarget.hasAVX2()) {
17410     int ElementBits = VT.getScalarSizeInBits();
17411     if (ElementBits < 32) {
17412       // No floating point type available, if we can't use the bit operations
17413       // for masking/blending then decompose into 128-bit vectors.
17414       if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
17415                                             Subtarget, DAG))
17416         return V;
17417       if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17418         return V;
17419       return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
17420     }
17421 
17422     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
17423                                 VT.getVectorNumElements());
17424     V1 = DAG.getBitcast(FpVT, V1);
17425     V2 = DAG.getBitcast(FpVT, V2);
17426     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
17427   }
17428 
17429   switch (VT.SimpleTy) {
17430   case MVT::v4f64:
17431     return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17432   case MVT::v4i64:
17433     return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17434   case MVT::v8f32:
17435     return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17436   case MVT::v8i32:
17437     return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17438   case MVT::v16i16:
17439     return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17440   case MVT::v32i8:
17441     return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
17442 
17443   default:
17444     llvm_unreachable("Not a valid 256-bit x86 vector type!");
17445   }
17446 }
17447 
17448 /// Try to lower a vector shuffle as a 128-bit shuffles.
17449 static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
17450                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17451                                   const X86Subtarget &Subtarget,
17452                                   SelectionDAG &DAG) {
17453   assert(VT.getScalarSizeInBits() == 64 &&
17454          "Unexpected element type size for 128bit shuffle.");
17455 
17456   // To handle 256 bit vector requires VLX and most probably
17457   // function lowerV2X128VectorShuffle() is better solution.
17458   assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.");
17459 
17460   // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
17461   SmallVector<int, 4> Widened128Mask;
17462   if (!canWidenShuffleElements(Mask, Widened128Mask))
17463     return SDValue();
17464   assert(Widened128Mask.size() == 4 && "Shuffle widening mismatch");
17465 
17466   // Try to use an insert into a zero vector.
17467   if (Widened128Mask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
17468       (Widened128Mask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
17469     unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
17470     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
17471     SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
17472                               DAG.getIntPtrConstant(0, DL));
17473     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
17474                        getZeroVector(VT, Subtarget, DAG, DL), LoV,
17475                        DAG.getIntPtrConstant(0, DL));
17476   }
17477 
17478   // Check for patterns which can be matched with a single insert of a 256-bit
17479   // subvector.
17480   bool OnlyUsesV1 = isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3}, V1, V2);
17481   if (OnlyUsesV1 ||
17482       isShuffleEquivalent(Mask, {0, 1, 2, 3, 8, 9, 10, 11}, V1, V2)) {
17483     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
17484     SDValue SubVec =
17485         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, OnlyUsesV1 ? V1 : V2,
17486                     DAG.getIntPtrConstant(0, DL));
17487     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
17488                        DAG.getIntPtrConstant(4, DL));
17489   }
17490 
17491   // See if this is an insertion of the lower 128-bits of V2 into V1.
17492   bool IsInsert = true;
17493   int V2Index = -1;
17494   for (int i = 0; i < 4; ++i) {
17495     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17496     if (Widened128Mask[i] < 0)
17497       continue;
17498 
17499     // Make sure all V1 subvectors are in place.
17500     if (Widened128Mask[i] < 4) {
17501       if (Widened128Mask[i] != i) {
17502         IsInsert = false;
17503         break;
17504       }
17505     } else {
17506       // Make sure we only have a single V2 index and its the lowest 128-bits.
17507       if (V2Index >= 0 || Widened128Mask[i] != 4) {
17508         IsInsert = false;
17509         break;
17510       }
17511       V2Index = i;
17512     }
17513   }
17514   if (IsInsert && V2Index >= 0) {
17515     MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
17516     SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
17517                                  DAG.getIntPtrConstant(0, DL));
17518     return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
17519   }
17520 
17521   // See if we can widen to a 256-bit lane shuffle, we're going to lose 128-lane
17522   // UNDEF info by lowering to X86ISD::SHUF128 anyway, so by widening where
17523   // possible we at least ensure the lanes stay sequential to help later
17524   // combines.
17525   SmallVector<int, 2> Widened256Mask;
17526   if (canWidenShuffleElements(Widened128Mask, Widened256Mask)) {
17527     Widened128Mask.clear();
17528     narrowShuffleMaskElts(2, Widened256Mask, Widened128Mask);
17529   }
17530 
17531   // Try to lower to vshuf64x2/vshuf32x4.
17532   SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
17533   unsigned PermMask = 0;
17534   // Insure elements came from the same Op.
17535   for (int i = 0; i < 4; ++i) {
17536     assert(Widened128Mask[i] >= -1 && "Illegal shuffle sentinel value");
17537     if (Widened128Mask[i] < 0)
17538       continue;
17539 
17540     SDValue Op = Widened128Mask[i] >= 4 ? V2 : V1;
17541     unsigned OpIndex = i / 2;
17542     if (Ops[OpIndex].isUndef())
17543       Ops[OpIndex] = Op;
17544     else if (Ops[OpIndex] != Op)
17545       return SDValue();
17546 
17547     // Convert the 128-bit shuffle mask selection values into 128-bit selection
17548     // bits defined by a vshuf64x2 instruction's immediate control byte.
17549     PermMask |= (Widened128Mask[i] % 4) << (i * 2);
17550   }
17551 
17552   return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
17553                      DAG.getTargetConstant(PermMask, DL, MVT::i8));
17554 }
17555 
17556 /// Handle lowering of 8-lane 64-bit floating point shuffles.
17557 static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17558                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17559                                  const X86Subtarget &Subtarget,
17560                                  SelectionDAG &DAG) {
17561   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17562   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
17563   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17564 
17565   if (V2.isUndef()) {
17566     // Use low duplicate instructions for masks that match their pattern.
17567     if (isShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1, V2))
17568       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
17569 
17570     if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
17571       // Non-half-crossing single input shuffles can be lowered with an
17572       // interleaved permutation.
17573       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
17574                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
17575                               ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
17576                               ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
17577       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
17578                          DAG.getTargetConstant(VPERMILPMask, DL, MVT::i8));
17579     }
17580 
17581     SmallVector<int, 4> RepeatedMask;
17582     if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
17583       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
17584                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17585   }
17586 
17587   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
17588                                            V2, Subtarget, DAG))
17589     return Shuf128;
17590 
17591   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
17592     return Unpck;
17593 
17594   // Check if the blend happens to exactly fit that of SHUFPD.
17595   if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, V1, V2, Mask,
17596                                           Zeroable, Subtarget, DAG))
17597     return Op;
17598 
17599   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
17600                                        DAG, Subtarget))
17601     return V;
17602 
17603   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
17604                                           Zeroable, Subtarget, DAG))
17605     return Blend;
17606 
17607   return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, Subtarget, DAG);
17608 }
17609 
17610 /// Handle lowering of 16-lane 32-bit floating point shuffles.
17611 static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17612                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17613                                   const X86Subtarget &Subtarget,
17614                                   SelectionDAG &DAG) {
17615   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17616   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
17617   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17618 
17619   // If the shuffle mask is repeated in each 128-bit lane, we have many more
17620   // options to efficiently lower the shuffle.
17621   SmallVector<int, 4> RepeatedMask;
17622   if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
17623     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17624 
17625     // Use even/odd duplicate instructions for masks that match their pattern.
17626     if (isShuffleEquivalent(RepeatedMask, {0, 0, 2, 2}, V1, V2))
17627       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
17628     if (isShuffleEquivalent(RepeatedMask, {1, 1, 3, 3}, V1, V2))
17629       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
17630 
17631     if (V2.isUndef())
17632       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
17633                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17634 
17635     // Use dedicated unpack instructions for masks that match their pattern.
17636     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
17637       return V;
17638 
17639     if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
17640                                             Zeroable, Subtarget, DAG))
17641       return Blend;
17642 
17643     // Otherwise, fall back to a SHUFPS sequence.
17644     return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
17645   }
17646 
17647   // Try to create an in-lane repeating shuffle mask and then shuffle the
17648   // results into the target lanes.
17649   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17650           DL, MVT::v16f32, V1, V2, Mask, Subtarget, DAG))
17651     return V;
17652 
17653   // If we have a single input shuffle with different shuffle patterns in the
17654   // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
17655   if (V2.isUndef() &&
17656       !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
17657     SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
17658     return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
17659   }
17660 
17661   // If we have AVX512F support, we can use VEXPAND.
17662   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
17663                                              V1, V2, DAG, Subtarget))
17664     return V;
17665 
17666   return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, Subtarget, DAG);
17667 }
17668 
17669 /// Handle lowering of 8-lane 64-bit integer shuffles.
17670 static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17671                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17672                                  const X86Subtarget &Subtarget,
17673                                  SelectionDAG &DAG) {
17674   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17675   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
17676   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
17677 
17678   if (V2.isUndef()) {
17679     // When the shuffle is mirrored between the 128-bit lanes of the unit, we
17680     // can use lower latency instructions that will operate on all four
17681     // 128-bit lanes.
17682     SmallVector<int, 2> Repeated128Mask;
17683     if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
17684       SmallVector<int, 4> PSHUFDMask;
17685       narrowShuffleMaskElts(2, Repeated128Mask, PSHUFDMask);
17686       return DAG.getBitcast(
17687           MVT::v8i64,
17688           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
17689                       DAG.getBitcast(MVT::v16i32, V1),
17690                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
17691     }
17692 
17693     SmallVector<int, 4> Repeated256Mask;
17694     if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
17695       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
17696                          getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
17697   }
17698 
17699   if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
17700                                            V2, Subtarget, DAG))
17701     return Shuf128;
17702 
17703   // Try to use shift instructions.
17704   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
17705                                           Zeroable, Subtarget, DAG))
17706     return Shift;
17707 
17708   // Try to use VALIGN.
17709   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v8i64, V1, V2, Mask,
17710                                             Subtarget, DAG))
17711     return Rotate;
17712 
17713   // Try to use PALIGNR.
17714   if (Subtarget.hasBWI())
17715     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
17716                                                   Subtarget, DAG))
17717       return Rotate;
17718 
17719   if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
17720     return Unpck;
17721 
17722   // If we have AVX512F support, we can use VEXPAND.
17723   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
17724                                        DAG, Subtarget))
17725     return V;
17726 
17727   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
17728                                           Zeroable, Subtarget, DAG))
17729     return Blend;
17730 
17731   return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, Subtarget, DAG);
17732 }
17733 
17734 /// Handle lowering of 16-lane 32-bit integer shuffles.
17735 static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17736                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17737                                   const X86Subtarget &Subtarget,
17738                                   SelectionDAG &DAG) {
17739   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17740   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
17741   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
17742 
17743   // Whenever we can lower this as a zext, that instruction is strictly faster
17744   // than any alternative. It also allows us to fold memory operands into the
17745   // shuffle in many cases.
17746   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17747           DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
17748     return ZExt;
17749 
17750   // If the shuffle mask is repeated in each 128-bit lane we can use more
17751   // efficient instructions that mirror the shuffles across the four 128-bit
17752   // lanes.
17753   SmallVector<int, 4> RepeatedMask;
17754   bool Is128BitLaneRepeatedShuffle =
17755       is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
17756   if (Is128BitLaneRepeatedShuffle) {
17757     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
17758     if (V2.isUndef())
17759       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
17760                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
17761 
17762     // Use dedicated unpack instructions for masks that match their pattern.
17763     if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
17764       return V;
17765   }
17766 
17767   // Try to use shift instructions.
17768   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
17769                                           Zeroable, Subtarget, DAG))
17770     return Shift;
17771 
17772   // Try to use VALIGN.
17773   if (SDValue Rotate = lowerShuffleAsVALIGN(DL, MVT::v16i32, V1, V2, Mask,
17774                                             Subtarget, DAG))
17775     return Rotate;
17776 
17777   // Try to use byte rotation instructions.
17778   if (Subtarget.hasBWI())
17779     if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
17780                                                   Subtarget, DAG))
17781       return Rotate;
17782 
17783   // Assume that a single SHUFPS is faster than using a permv shuffle.
17784   // If some CPU is harmed by the domain switch, we can fix it in a later pass.
17785   if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
17786     SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
17787     SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
17788     SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
17789                                             CastV1, CastV2, DAG);
17790     return DAG.getBitcast(MVT::v16i32, ShufPS);
17791   }
17792 
17793   // Try to create an in-lane repeating shuffle mask and then shuffle the
17794   // results into the target lanes.
17795   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17796           DL, MVT::v16i32, V1, V2, Mask, Subtarget, DAG))
17797     return V;
17798 
17799   // If we have AVX512F support, we can use VEXPAND.
17800   if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
17801                                        DAG, Subtarget))
17802     return V;
17803 
17804   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
17805                                           Zeroable, Subtarget, DAG))
17806     return Blend;
17807 
17808   return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, Subtarget, DAG);
17809 }
17810 
17811 /// Handle lowering of 32-lane 16-bit integer shuffles.
17812 static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17813                                   const APInt &Zeroable, SDValue V1, SDValue V2,
17814                                   const X86Subtarget &Subtarget,
17815                                   SelectionDAG &DAG) {
17816   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
17817   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
17818   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
17819   assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
17820 
17821   // Whenever we can lower this as a zext, that instruction is strictly faster
17822   // than any alternative. It also allows us to fold memory operands into the
17823   // shuffle in many cases.
17824   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17825           DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
17826     return ZExt;
17827 
17828   // Use dedicated unpack instructions for masks that match their pattern.
17829   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
17830     return V;
17831 
17832   // Use dedicated pack instructions for masks that match their pattern.
17833   if (SDValue V =
17834           lowerShuffleWithPACK(DL, MVT::v32i16, Mask, V1, V2, DAG, Subtarget))
17835     return V;
17836 
17837   // Try to use shift instructions.
17838   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
17839                                           Zeroable, Subtarget, DAG))
17840     return Shift;
17841 
17842   // Try to use byte rotation instructions.
17843   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
17844                                                 Subtarget, DAG))
17845     return Rotate;
17846 
17847   if (V2.isUndef()) {
17848     // Try to use bit rotation instructions.
17849     if (SDValue Rotate =
17850             lowerShuffleAsBitRotate(DL, MVT::v32i16, V1, Mask, Subtarget, DAG))
17851       return Rotate;
17852 
17853     SmallVector<int, 8> RepeatedMask;
17854     if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
17855       // As this is a single-input shuffle, the repeated mask should be
17856       // a strictly valid v8i16 mask that we can pass through to the v8i16
17857       // lowering to handle even the v32 case.
17858       return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v32i16, V1,
17859                                                  RepeatedMask, Subtarget, DAG);
17860     }
17861   }
17862 
17863   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
17864                                           Zeroable, Subtarget, DAG))
17865     return Blend;
17866 
17867   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
17868                                               Zeroable, Subtarget, DAG))
17869     return PSHUFB;
17870 
17871   return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, Subtarget, DAG);
17872 }
17873 
17874 /// Handle lowering of 64-lane 8-bit integer shuffles.
17875 static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
17876                                  const APInt &Zeroable, SDValue V1, SDValue V2,
17877                                  const X86Subtarget &Subtarget,
17878                                  SelectionDAG &DAG) {
17879   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
17880   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
17881   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
17882   assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
17883 
17884   // Whenever we can lower this as a zext, that instruction is strictly faster
17885   // than any alternative. It also allows us to fold memory operands into the
17886   // shuffle in many cases.
17887   if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
17888           DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
17889     return ZExt;
17890 
17891   // Use dedicated unpack instructions for masks that match their pattern.
17892   if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
17893     return V;
17894 
17895   // Use dedicated pack instructions for masks that match their pattern.
17896   if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
17897                                        Subtarget))
17898     return V;
17899 
17900   // Try to use shift instructions.
17901   if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
17902                                           Zeroable, Subtarget, DAG))
17903     return Shift;
17904 
17905   // Try to use byte rotation instructions.
17906   if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
17907                                                 Subtarget, DAG))
17908     return Rotate;
17909 
17910   // Try to use bit rotation instructions.
17911   if (V2.isUndef())
17912     if (SDValue Rotate =
17913             lowerShuffleAsBitRotate(DL, MVT::v64i8, V1, Mask, Subtarget, DAG))
17914       return Rotate;
17915 
17916   // Lower as AND if possible.
17917   if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v64i8, V1, V2, Mask,
17918                                              Zeroable, Subtarget, DAG))
17919     return Masked;
17920 
17921   if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
17922                                               Zeroable, Subtarget, DAG))
17923     return PSHUFB;
17924 
17925   // VBMI can use VPERMV/VPERMV3 byte shuffles.
17926   if (Subtarget.hasVBMI())
17927     return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, Subtarget, DAG);
17928 
17929   // Try to create an in-lane repeating shuffle mask and then shuffle the
17930   // results into the target lanes.
17931   if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
17932           DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17933     return V;
17934 
17935   if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
17936                                           Zeroable, Subtarget, DAG))
17937     return Blend;
17938 
17939   // Try to simplify this by merging 128-bit lanes to enable a lane-based
17940   // shuffle.
17941   if (!V2.isUndef())
17942     if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
17943             DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
17944       return Result;
17945 
17946   // FIXME: Implement direct support for this type!
17947   return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
17948 }
17949 
17950 /// High-level routine to lower various 512-bit x86 vector shuffles.
17951 ///
17952 /// This routine either breaks down the specific type of a 512-bit x86 vector
17953 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
17954 /// together based on the available instructions.
17955 static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
17956                                   MVT VT, SDValue V1, SDValue V2,
17957                                   const APInt &Zeroable,
17958                                   const X86Subtarget &Subtarget,
17959                                   SelectionDAG &DAG) {
17960   assert(Subtarget.hasAVX512() &&
17961          "Cannot lower 512-bit vectors w/ basic ISA!");
17962 
17963   // If we have a single input to the zero element, insert that into V1 if we
17964   // can do so cheaply.
17965   int NumElts = Mask.size();
17966   int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
17967 
17968   if (NumV2Elements == 1 && Mask[0] >= NumElts)
17969     if (SDValue Insertion = lowerShuffleAsElementInsertion(
17970             DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
17971       return Insertion;
17972 
17973   // Handle special cases where the lower or upper half is UNDEF.
17974   if (SDValue V =
17975           lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
17976     return V;
17977 
17978   // Check for being able to broadcast a single element.
17979   if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
17980                                                   Subtarget, DAG))
17981     return Broadcast;
17982 
17983   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI()) {
17984     // Try using bit ops for masking and blending before falling back to
17985     // splitting.
17986     if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
17987                                           Subtarget, DAG))
17988       return V;
17989     if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
17990       return V;
17991 
17992     return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
17993   }
17994 
17995   // Dispatch to each element type for lowering. If we don't have support for
17996   // specific element type shuffles at 512 bits, immediately split them and
17997   // lower them. Each lowering routine of a given type is allowed to assume that
17998   // the requisite ISA extensions for that element type are available.
17999   switch (VT.SimpleTy) {
18000   case MVT::v8f64:
18001     return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18002   case MVT::v16f32:
18003     return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18004   case MVT::v8i64:
18005     return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18006   case MVT::v16i32:
18007     return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18008   case MVT::v32i16:
18009     return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18010   case MVT::v64i8:
18011     return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
18012 
18013   default:
18014     llvm_unreachable("Not a valid 512-bit x86 vector type!");
18015   }
18016 }
18017 
18018 static SDValue lower1BitShuffleAsKSHIFTR(const SDLoc &DL, ArrayRef<int> Mask,
18019                                          MVT VT, SDValue V1, SDValue V2,
18020                                          const X86Subtarget &Subtarget,
18021                                          SelectionDAG &DAG) {
18022   // Shuffle should be unary.
18023   if (!V2.isUndef())
18024     return SDValue();
18025 
18026   int ShiftAmt = -1;
18027   int NumElts = Mask.size();
18028   for (int i = 0; i != NumElts; ++i) {
18029     int M = Mask[i];
18030     assert((M == SM_SentinelUndef || (0 <= M && M < NumElts)) &&
18031            "Unexpected mask index.");
18032     if (M < 0)
18033       continue;
18034 
18035     // The first non-undef element determines our shift amount.
18036     if (ShiftAmt < 0) {
18037       ShiftAmt = M - i;
18038       // Need to be shifting right.
18039       if (ShiftAmt <= 0)
18040         return SDValue();
18041     }
18042     // All non-undef elements must shift by the same amount.
18043     if (ShiftAmt != M - i)
18044       return SDValue();
18045   }
18046   assert(ShiftAmt >= 0 && "All undef?");
18047 
18048   // Great we found a shift right.
18049   MVT WideVT = VT;
18050   if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
18051     WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18052   SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
18053                             DAG.getUNDEF(WideVT), V1,
18054                             DAG.getIntPtrConstant(0, DL));
18055   Res = DAG.getNode(X86ISD::KSHIFTR, DL, WideVT, Res,
18056                     DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18057   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18058                      DAG.getIntPtrConstant(0, DL));
18059 }
18060 
18061 // Determine if this shuffle can be implemented with a KSHIFT instruction.
18062 // Returns the shift amount if possible or -1 if not. This is a simplified
18063 // version of matchShuffleAsShift.
18064 static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
18065                                     int MaskOffset, const APInt &Zeroable) {
18066   int Size = Mask.size();
18067 
18068   auto CheckZeros = [&](int Shift, bool Left) {
18069     for (int j = 0; j < Shift; ++j)
18070       if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
18071         return false;
18072 
18073     return true;
18074   };
18075 
18076   auto MatchShift = [&](int Shift, bool Left) {
18077     unsigned Pos = Left ? Shift : 0;
18078     unsigned Low = Left ? 0 : Shift;
18079     unsigned Len = Size - Shift;
18080     return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
18081   };
18082 
18083   for (int Shift = 1; Shift != Size; ++Shift)
18084     for (bool Left : {true, false})
18085       if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
18086         Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
18087         return Shift;
18088       }
18089 
18090   return -1;
18091 }
18092 
18093 
18094 // Lower vXi1 vector shuffles.
18095 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
18096 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
18097 // vector, shuffle and then truncate it back.
18098 static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
18099                                 MVT VT, SDValue V1, SDValue V2,
18100                                 const APInt &Zeroable,
18101                                 const X86Subtarget &Subtarget,
18102                                 SelectionDAG &DAG) {
18103   assert(Subtarget.hasAVX512() &&
18104          "Cannot lower 512-bit vectors w/o basic ISA!");
18105 
18106   int NumElts = Mask.size();
18107 
18108   // Try to recognize shuffles that are just padding a subvector with zeros.
18109   int SubvecElts = 0;
18110   int Src = -1;
18111   for (int i = 0; i != NumElts; ++i) {
18112     if (Mask[i] >= 0) {
18113       // Grab the source from the first valid mask. All subsequent elements need
18114       // to use this same source.
18115       if (Src < 0)
18116         Src = Mask[i] / NumElts;
18117       if (Src != (Mask[i] / NumElts) || (Mask[i] % NumElts) != i)
18118         break;
18119     }
18120 
18121     ++SubvecElts;
18122   }
18123   assert(SubvecElts != NumElts && "Identity shuffle?");
18124 
18125   // Clip to a power 2.
18126   SubvecElts = PowerOf2Floor(SubvecElts);
18127 
18128   // Make sure the number of zeroable bits in the top at least covers the bits
18129   // not covered by the subvector.
18130   if ((int)Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
18131     assert(Src >= 0 && "Expected a source!");
18132     MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
18133     SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
18134                                   Src == 0 ? V1 : V2,
18135                                   DAG.getIntPtrConstant(0, DL));
18136     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
18137                        DAG.getConstant(0, DL, VT),
18138                        Extract, DAG.getIntPtrConstant(0, DL));
18139   }
18140 
18141   // Try a simple shift right with undef elements. Later we'll try with zeros.
18142   if (SDValue Shift = lower1BitShuffleAsKSHIFTR(DL, Mask, VT, V1, V2, Subtarget,
18143                                                 DAG))
18144     return Shift;
18145 
18146   // Try to match KSHIFTs.
18147   unsigned Offset = 0;
18148   for (SDValue V : { V1, V2 }) {
18149     unsigned Opcode;
18150     int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
18151     if (ShiftAmt >= 0) {
18152       MVT WideVT = VT;
18153       if ((!Subtarget.hasDQI() && NumElts == 8) || NumElts < 8)
18154         WideVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18155       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideVT,
18156                                 DAG.getUNDEF(WideVT), V,
18157                                 DAG.getIntPtrConstant(0, DL));
18158       // Widened right shifts need two shifts to ensure we shift in zeroes.
18159       if (Opcode == X86ISD::KSHIFTR && WideVT != VT) {
18160         int WideElts = WideVT.getVectorNumElements();
18161         // Shift left to put the original vector in the MSBs of the new size.
18162         Res = DAG.getNode(X86ISD::KSHIFTL, DL, WideVT, Res,
18163                           DAG.getTargetConstant(WideElts - NumElts, DL, MVT::i8));
18164         // Increase the shift amount to account for the left shift.
18165         ShiftAmt += WideElts - NumElts;
18166       }
18167 
18168       Res = DAG.getNode(Opcode, DL, WideVT, Res,
18169                         DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
18170       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
18171                          DAG.getIntPtrConstant(0, DL));
18172     }
18173     Offset += NumElts; // Increment for next iteration.
18174   }
18175 
18176 
18177 
18178   MVT ExtVT;
18179   switch (VT.SimpleTy) {
18180   default:
18181     llvm_unreachable("Expected a vector of i1 elements");
18182   case MVT::v2i1:
18183     ExtVT = MVT::v2i64;
18184     break;
18185   case MVT::v4i1:
18186     ExtVT = MVT::v4i32;
18187     break;
18188   case MVT::v8i1:
18189     // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
18190     // shuffle.
18191     ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
18192     break;
18193   case MVT::v16i1:
18194     // Take 512-bit type, unless we are avoiding 512-bit types and have the
18195     // 256-bit operation available.
18196     ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
18197     break;
18198   case MVT::v32i1:
18199     // Take 512-bit type, unless we are avoiding 512-bit types and have the
18200     // 256-bit operation available.
18201     assert(Subtarget.hasBWI() && "Expected AVX512BW support");
18202     ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
18203     break;
18204   case MVT::v64i1:
18205     // Fall back to scalarization. FIXME: We can do better if the shuffle
18206     // can be partitioned cleanly.
18207     if (!Subtarget.useBWIRegs())
18208       return SDValue();
18209     ExtVT = MVT::v64i8;
18210     break;
18211   }
18212 
18213   V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
18214   V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
18215 
18216   SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
18217   // i1 was sign extended we can use X86ISD::CVT2MASK.
18218   int NumElems = VT.getVectorNumElements();
18219   if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
18220       (Subtarget.hasDQI() && (NumElems < 32)))
18221     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
18222                        Shuffle, ISD::SETGT);
18223 
18224   return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
18225 }
18226 
18227 /// Helper function that returns true if the shuffle mask should be
18228 /// commuted to improve canonicalization.
18229 static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
18230   int NumElements = Mask.size();
18231 
18232   int NumV1Elements = 0, NumV2Elements = 0;
18233   for (int M : Mask)
18234     if (M < 0)
18235       continue;
18236     else if (M < NumElements)
18237       ++NumV1Elements;
18238     else
18239       ++NumV2Elements;
18240 
18241   // Commute the shuffle as needed such that more elements come from V1 than
18242   // V2. This allows us to match the shuffle pattern strictly on how many
18243   // elements come from V1 without handling the symmetric cases.
18244   if (NumV2Elements > NumV1Elements)
18245     return true;
18246 
18247   assert(NumV1Elements > 0 && "No V1 indices");
18248 
18249   if (NumV2Elements == 0)
18250     return false;
18251 
18252   // When the number of V1 and V2 elements are the same, try to minimize the
18253   // number of uses of V2 in the low half of the vector. When that is tied,
18254   // ensure that the sum of indices for V1 is equal to or lower than the sum
18255   // indices for V2. When those are equal, try to ensure that the number of odd
18256   // indices for V1 is lower than the number of odd indices for V2.
18257   if (NumV1Elements == NumV2Elements) {
18258     int LowV1Elements = 0, LowV2Elements = 0;
18259     for (int M : Mask.slice(0, NumElements / 2))
18260       if (M >= NumElements)
18261         ++LowV2Elements;
18262       else if (M >= 0)
18263         ++LowV1Elements;
18264     if (LowV2Elements > LowV1Elements)
18265       return true;
18266     if (LowV2Elements == LowV1Elements) {
18267       int SumV1Indices = 0, SumV2Indices = 0;
18268       for (int i = 0, Size = Mask.size(); i < Size; ++i)
18269         if (Mask[i] >= NumElements)
18270           SumV2Indices += i;
18271         else if (Mask[i] >= 0)
18272           SumV1Indices += i;
18273       if (SumV2Indices < SumV1Indices)
18274         return true;
18275       if (SumV2Indices == SumV1Indices) {
18276         int NumV1OddIndices = 0, NumV2OddIndices = 0;
18277         for (int i = 0, Size = Mask.size(); i < Size; ++i)
18278           if (Mask[i] >= NumElements)
18279             NumV2OddIndices += i % 2;
18280           else if (Mask[i] >= 0)
18281             NumV1OddIndices += i % 2;
18282         if (NumV2OddIndices < NumV1OddIndices)
18283           return true;
18284       }
18285     }
18286   }
18287 
18288   return false;
18289 }
18290 
18291 /// Top-level lowering for x86 vector shuffles.
18292 ///
18293 /// This handles decomposition, canonicalization, and lowering of all x86
18294 /// vector shuffles. Most of the specific lowering strategies are encapsulated
18295 /// above in helper routines. The canonicalization attempts to widen shuffles
18296 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
18297 /// s.t. only one of the two inputs needs to be tested, etc.
18298 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, const X86Subtarget &Subtarget,
18299                                    SelectionDAG &DAG) {
18300   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
18301   ArrayRef<int> OrigMask = SVOp->getMask();
18302   SDValue V1 = Op.getOperand(0);
18303   SDValue V2 = Op.getOperand(1);
18304   MVT VT = Op.getSimpleValueType();
18305   int NumElements = VT.getVectorNumElements();
18306   SDLoc DL(Op);
18307   bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
18308 
18309   assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
18310          "Can't lower MMX shuffles");
18311 
18312   bool V1IsUndef = V1.isUndef();
18313   bool V2IsUndef = V2.isUndef();
18314   if (V1IsUndef && V2IsUndef)
18315     return DAG.getUNDEF(VT);
18316 
18317   // When we create a shuffle node we put the UNDEF node to second operand,
18318   // but in some cases the first operand may be transformed to UNDEF.
18319   // In this case we should just commute the node.
18320   if (V1IsUndef)
18321     return DAG.getCommutedVectorShuffle(*SVOp);
18322 
18323   // Check for non-undef masks pointing at an undef vector and make the masks
18324   // undef as well. This makes it easier to match the shuffle based solely on
18325   // the mask.
18326   if (V2IsUndef &&
18327       any_of(OrigMask, [NumElements](int M) { return M >= NumElements; })) {
18328     SmallVector<int, 8> NewMask(OrigMask.begin(), OrigMask.end());
18329     for (int &M : NewMask)
18330       if (M >= NumElements)
18331         M = -1;
18332     return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
18333   }
18334 
18335   // Check for illegal shuffle mask element index values.
18336   int MaskUpperLimit = OrigMask.size() * (V2IsUndef ? 1 : 2);
18337   (void)MaskUpperLimit;
18338   assert(llvm::all_of(OrigMask,
18339                       [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&
18340          "Out of bounds shuffle index");
18341 
18342   // We actually see shuffles that are entirely re-arrangements of a set of
18343   // zero inputs. This mostly happens while decomposing complex shuffles into
18344   // simple ones. Directly lower these as a buildvector of zeros.
18345   APInt KnownUndef, KnownZero;
18346   computeZeroableShuffleElements(OrigMask, V1, V2, KnownUndef, KnownZero);
18347 
18348   APInt Zeroable = KnownUndef | KnownZero;
18349   if (Zeroable.isAllOnesValue())
18350     return getZeroVector(VT, Subtarget, DAG, DL);
18351 
18352   bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
18353 
18354   // Try to collapse shuffles into using a vector type with fewer elements but
18355   // wider element types. We cap this to not form integers or floating point
18356   // elements wider than 64 bits, but it might be interesting to form i128
18357   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
18358   SmallVector<int, 16> WidenedMask;
18359   if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
18360       canWidenShuffleElements(OrigMask, Zeroable, V2IsZero, WidenedMask)) {
18361     // Shuffle mask widening should not interfere with a broadcast opportunity
18362     // by obfuscating the operands with bitcasts.
18363     // TODO: Avoid lowering directly from this top-level function: make this
18364     // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
18365     if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, OrigMask,
18366                                                     Subtarget, DAG))
18367       return Broadcast;
18368 
18369     MVT NewEltVT = VT.isFloatingPoint()
18370                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
18371                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
18372     int NewNumElts = NumElements / 2;
18373     MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
18374     // Make sure that the new vector type is legal. For example, v2f64 isn't
18375     // legal on SSE1.
18376     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
18377       if (V2IsZero) {
18378         // Modify the new Mask to take all zeros from the all-zero vector.
18379         // Choose indices that are blend-friendly.
18380         bool UsedZeroVector = false;
18381         assert(is_contained(WidenedMask, SM_SentinelZero) &&
18382                "V2's non-undef elements are used?!");
18383         for (int i = 0; i != NewNumElts; ++i)
18384           if (WidenedMask[i] == SM_SentinelZero) {
18385             WidenedMask[i] = i + NewNumElts;
18386             UsedZeroVector = true;
18387           }
18388         // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
18389         // some elements to be undef.
18390         if (UsedZeroVector)
18391           V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
18392       }
18393       V1 = DAG.getBitcast(NewVT, V1);
18394       V2 = DAG.getBitcast(NewVT, V2);
18395       return DAG.getBitcast(
18396           VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
18397     }
18398   }
18399 
18400   // Commute the shuffle if it will improve canonicalization.
18401   SmallVector<int, 64> Mask(OrigMask.begin(), OrigMask.end());
18402   if (canonicalizeShuffleMaskWithCommute(Mask)) {
18403     ShuffleVectorSDNode::commuteMask(Mask);
18404     std::swap(V1, V2);
18405   }
18406 
18407   // For each vector width, delegate to a specialized lowering routine.
18408   if (VT.is128BitVector())
18409     return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18410 
18411   if (VT.is256BitVector())
18412     return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18413 
18414   if (VT.is512BitVector())
18415     return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18416 
18417   if (Is1BitVector)
18418     return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
18419 
18420   llvm_unreachable("Unimplemented!");
18421 }
18422 
18423 /// Try to lower a VSELECT instruction to a vector shuffle.
18424 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
18425                                            const X86Subtarget &Subtarget,
18426                                            SelectionDAG &DAG) {
18427   SDValue Cond = Op.getOperand(0);
18428   SDValue LHS = Op.getOperand(1);
18429   SDValue RHS = Op.getOperand(2);
18430   MVT VT = Op.getSimpleValueType();
18431 
18432   // Only non-legal VSELECTs reach this lowering, convert those into generic
18433   // shuffles and re-use the shuffle lowering path for blends.
18434   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
18435     SmallVector<int, 32> Mask;
18436     if (createShuffleMaskFromVSELECT(Mask, Cond))
18437       return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
18438   }
18439 
18440   return SDValue();
18441 }
18442 
18443 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
18444   SDValue Cond = Op.getOperand(0);
18445   SDValue LHS = Op.getOperand(1);
18446   SDValue RHS = Op.getOperand(2);
18447 
18448   // A vselect where all conditions and data are constants can be optimized into
18449   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
18450   if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
18451       ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
18452       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
18453     return SDValue();
18454 
18455   // Try to lower this to a blend-style vector shuffle. This can handle all
18456   // constant condition cases.
18457   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
18458     return BlendOp;
18459 
18460   // If this VSELECT has a vector if i1 as a mask, it will be directly matched
18461   // with patterns on the mask registers on AVX-512.
18462   MVT CondVT = Cond.getSimpleValueType();
18463   unsigned CondEltSize = Cond.getScalarValueSizeInBits();
18464   if (CondEltSize == 1)
18465     return Op;
18466 
18467   // Variable blends are only legal from SSE4.1 onward.
18468   if (!Subtarget.hasSSE41())
18469     return SDValue();
18470 
18471   SDLoc dl(Op);
18472   MVT VT = Op.getSimpleValueType();
18473   unsigned EltSize = VT.getScalarSizeInBits();
18474   unsigned NumElts = VT.getVectorNumElements();
18475 
18476   // Expand v32i16/v64i8 without BWI.
18477   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
18478     return SDValue();
18479 
18480   // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
18481   // into an i1 condition so that we can use the mask-based 512-bit blend
18482   // instructions.
18483   if (VT.getSizeInBits() == 512) {
18484     // Build a mask by testing the condition against zero.
18485     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
18486     SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
18487                                 DAG.getConstant(0, dl, CondVT),
18488                                 ISD::SETNE);
18489     // Now return a new VSELECT using the mask.
18490     return DAG.getSelect(dl, VT, Mask, LHS, RHS);
18491   }
18492 
18493   // SEXT/TRUNC cases where the mask doesn't match the destination size.
18494   if (CondEltSize != EltSize) {
18495     // If we don't have a sign splat, rely on the expansion.
18496     if (CondEltSize != DAG.ComputeNumSignBits(Cond))
18497       return SDValue();
18498 
18499     MVT NewCondSVT = MVT::getIntegerVT(EltSize);
18500     MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
18501     Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
18502     return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
18503   }
18504 
18505   // Only some types will be legal on some subtargets. If we can emit a legal
18506   // VSELECT-matching blend, return Op, and but if we need to expand, return
18507   // a null value.
18508   switch (VT.SimpleTy) {
18509   default:
18510     // Most of the vector types have blends past SSE4.1.
18511     return Op;
18512 
18513   case MVT::v32i8:
18514     // The byte blends for AVX vectors were introduced only in AVX2.
18515     if (Subtarget.hasAVX2())
18516       return Op;
18517 
18518     return SDValue();
18519 
18520   case MVT::v8i16:
18521   case MVT::v16i16: {
18522     // Bitcast everything to the vXi8 type and use a vXi8 vselect.
18523     MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
18524     Cond = DAG.getBitcast(CastVT, Cond);
18525     LHS = DAG.getBitcast(CastVT, LHS);
18526     RHS = DAG.getBitcast(CastVT, RHS);
18527     SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
18528     return DAG.getBitcast(VT, Select);
18529   }
18530   }
18531 }
18532 
18533 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
18534   MVT VT = Op.getSimpleValueType();
18535   SDValue Vec = Op.getOperand(0);
18536   SDValue Idx = Op.getOperand(1);
18537   assert(isa<ConstantSDNode>(Idx) && "Constant index expected");
18538   SDLoc dl(Op);
18539 
18540   if (!Vec.getSimpleValueType().is128BitVector())
18541     return SDValue();
18542 
18543   if (VT.getSizeInBits() == 8) {
18544     // If IdxVal is 0, it's cheaper to do a move instead of a pextrb, unless
18545     // we're going to zero extend the register or fold the store.
18546     if (llvm::isNullConstant(Idx) && !MayFoldIntoZeroExtend(Op) &&
18547         !MayFoldIntoStore(Op))
18548       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i8,
18549                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18550                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
18551 
18552     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
18553     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32, Vec,
18554                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18555     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18556   }
18557 
18558   if (VT == MVT::f32) {
18559     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
18560     // the result back to FR32 register. It's only worth matching if the
18561     // result has a single use which is a store or a bitcast to i32.  And in
18562     // the case of a store, it's not worth it if the index is a constant 0,
18563     // because a MOVSSmr can be used instead, which is smaller and faster.
18564     if (!Op.hasOneUse())
18565       return SDValue();
18566     SDNode *User = *Op.getNode()->use_begin();
18567     if ((User->getOpcode() != ISD::STORE || isNullConstant(Idx)) &&
18568         (User->getOpcode() != ISD::BITCAST ||
18569          User->getValueType(0) != MVT::i32))
18570       return SDValue();
18571     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18572                                   DAG.getBitcast(MVT::v4i32, Vec), Idx);
18573     return DAG.getBitcast(MVT::f32, Extract);
18574   }
18575 
18576   if (VT == MVT::i32 || VT == MVT::i64)
18577       return Op;
18578 
18579   return SDValue();
18580 }
18581 
18582 /// Extract one bit from mask vector, like v16i1 or v8i1.
18583 /// AVX-512 feature.
18584 static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
18585                                         const X86Subtarget &Subtarget) {
18586   SDValue Vec = Op.getOperand(0);
18587   SDLoc dl(Vec);
18588   MVT VecVT = Vec.getSimpleValueType();
18589   SDValue Idx = Op.getOperand(1);
18590   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18591   MVT EltVT = Op.getSimpleValueType();
18592 
18593   assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&
18594          "Unexpected vector type in ExtractBitFromMaskVector");
18595 
18596   // variable index can't be handled in mask registers,
18597   // extend vector to VR512/128
18598   if (!IdxC) {
18599     unsigned NumElts = VecVT.getVectorNumElements();
18600     // Extending v8i1/v16i1 to 512-bit get better performance on KNL
18601     // than extending to 128/256bit.
18602     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18603     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18604     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
18605     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
18606     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
18607   }
18608 
18609   unsigned IdxVal = IdxC->getZExtValue();
18610   if (IdxVal == 0) // the operation is legal
18611     return Op;
18612 
18613   // Extend to natively supported kshift.
18614   unsigned NumElems = VecVT.getVectorNumElements();
18615   MVT WideVecVT = VecVT;
18616   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
18617     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
18618     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
18619                       DAG.getUNDEF(WideVecVT), Vec,
18620                       DAG.getIntPtrConstant(0, dl));
18621   }
18622 
18623   // Use kshiftr instruction to move to the lower element.
18624   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
18625                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18626 
18627   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18628                      DAG.getIntPtrConstant(0, dl));
18629 }
18630 
18631 SDValue
18632 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
18633                                            SelectionDAG &DAG) const {
18634   SDLoc dl(Op);
18635   SDValue Vec = Op.getOperand(0);
18636   MVT VecVT = Vec.getSimpleValueType();
18637   SDValue Idx = Op.getOperand(1);
18638   auto* IdxC = dyn_cast<ConstantSDNode>(Idx);
18639 
18640   if (VecVT.getVectorElementType() == MVT::i1)
18641     return ExtractBitFromMaskVector(Op, DAG, Subtarget);
18642 
18643   if (!IdxC) {
18644     // Its more profitable to go through memory (1 cycles throughput)
18645     // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
18646     // IACA tool was used to get performance estimation
18647     // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
18648     //
18649     // example : extractelement <16 x i8> %a, i32 %i
18650     //
18651     // Block Throughput: 3.00 Cycles
18652     // Throughput Bottleneck: Port5
18653     //
18654     // | Num Of |   Ports pressure in cycles  |    |
18655     // |  Uops  |  0  - DV  |  5  |  6  |  7  |    |
18656     // ---------------------------------------------
18657     // |   1    |           | 1.0 |     |     | CP | vmovd xmm1, edi
18658     // |   1    |           | 1.0 |     |     | CP | vpshufb xmm0, xmm0, xmm1
18659     // |   2    | 1.0       | 1.0 |     |     | CP | vpextrb eax, xmm0, 0x0
18660     // Total Num Of Uops: 4
18661     //
18662     //
18663     // Block Throughput: 1.00 Cycles
18664     // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
18665     //
18666     // |    |  Ports pressure in cycles   |  |
18667     // |Uops| 1 | 2 - D  |3 -  D  | 4 | 5 |  |
18668     // ---------------------------------------------------------
18669     // |2^  |   | 0.5    | 0.5    |1.0|   |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
18670     // |1   |0.5|        |        |   |0.5|  | lea rax, ptr [rsp-0x18]
18671     // |1   |   |0.5, 0.5|0.5, 0.5|   |   |CP| mov al, byte ptr [rdi+rax*1]
18672     // Total Num Of Uops: 4
18673 
18674     return SDValue();
18675   }
18676 
18677   unsigned IdxVal = IdxC->getZExtValue();
18678 
18679   // If this is a 256-bit vector result, first extract the 128-bit vector and
18680   // then extract the element from the 128-bit vector.
18681   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
18682     // Get the 128-bit vector.
18683     Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
18684     MVT EltVT = VecVT.getVectorElementType();
18685 
18686     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
18687     assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
18688 
18689     // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
18690     // this can be done with a mask.
18691     IdxVal &= ElemsPerChunk - 1;
18692     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
18693                        DAG.getIntPtrConstant(IdxVal, dl));
18694   }
18695 
18696   assert(VecVT.is128BitVector() && "Unexpected vector length");
18697 
18698   MVT VT = Op.getSimpleValueType();
18699 
18700   if (VT.getSizeInBits() == 16) {
18701     // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
18702     // we're going to zero extend the register or fold the store (SSE41 only).
18703     if (IdxVal == 0 && !MayFoldIntoZeroExtend(Op) &&
18704         !(Subtarget.hasSSE41() && MayFoldIntoStore(Op)))
18705       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
18706                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18707                                      DAG.getBitcast(MVT::v4i32, Vec), Idx));
18708 
18709     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32, Vec,
18710                                   DAG.getTargetConstant(IdxVal, dl, MVT::i8));
18711     return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
18712   }
18713 
18714   if (Subtarget.hasSSE41())
18715     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
18716       return Res;
18717 
18718   // TODO: We only extract a single element from v16i8, we can probably afford
18719   // to be more aggressive here before using the default approach of spilling to
18720   // stack.
18721   if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
18722     // Extract either the lowest i32 or any i16, and extract the sub-byte.
18723     int DWordIdx = IdxVal / 4;
18724     if (DWordIdx == 0) {
18725       SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
18726                                 DAG.getBitcast(MVT::v4i32, Vec),
18727                                 DAG.getIntPtrConstant(DWordIdx, dl));
18728       int ShiftVal = (IdxVal % 4) * 8;
18729       if (ShiftVal != 0)
18730         Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
18731                           DAG.getConstant(ShiftVal, dl, MVT::i8));
18732       return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18733     }
18734 
18735     int WordIdx = IdxVal / 2;
18736     SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
18737                               DAG.getBitcast(MVT::v8i16, Vec),
18738                               DAG.getIntPtrConstant(WordIdx, dl));
18739     int ShiftVal = (IdxVal % 2) * 8;
18740     if (ShiftVal != 0)
18741       Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
18742                         DAG.getConstant(ShiftVal, dl, MVT::i8));
18743     return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18744   }
18745 
18746   if (VT.getSizeInBits() == 32) {
18747     if (IdxVal == 0)
18748       return Op;
18749 
18750     // SHUFPS the element to the lowest double word, then movss.
18751     int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
18752     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18753     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18754                        DAG.getIntPtrConstant(0, dl));
18755   }
18756 
18757   if (VT.getSizeInBits() == 64) {
18758     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
18759     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
18760     //        to match extract_elt for f64.
18761     if (IdxVal == 0)
18762       return Op;
18763 
18764     // UNPCKHPD the element to the lowest double word, then movsd.
18765     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
18766     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
18767     int Mask[2] = { 1, -1 };
18768     Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
18769     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
18770                        DAG.getIntPtrConstant(0, dl));
18771   }
18772 
18773   return SDValue();
18774 }
18775 
18776 /// Insert one bit to mask vector, like v16i1 or v8i1.
18777 /// AVX-512 feature.
18778 static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
18779                                      const X86Subtarget &Subtarget) {
18780   SDLoc dl(Op);
18781   SDValue Vec = Op.getOperand(0);
18782   SDValue Elt = Op.getOperand(1);
18783   SDValue Idx = Op.getOperand(2);
18784   MVT VecVT = Vec.getSimpleValueType();
18785 
18786   if (!isa<ConstantSDNode>(Idx)) {
18787     // Non constant index. Extend source and destination,
18788     // insert element and then truncate the result.
18789     unsigned NumElts = VecVT.getVectorNumElements();
18790     MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
18791     MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
18792     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
18793       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
18794       DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
18795     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
18796   }
18797 
18798   // Copy into a k-register, extract to v1i1 and insert_subvector.
18799   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
18800   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec, Idx);
18801 }
18802 
18803 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
18804                                                   SelectionDAG &DAG) const {
18805   MVT VT = Op.getSimpleValueType();
18806   MVT EltVT = VT.getVectorElementType();
18807   unsigned NumElts = VT.getVectorNumElements();
18808 
18809   if (EltVT == MVT::i1)
18810     return InsertBitToMaskVector(Op, DAG, Subtarget);
18811 
18812   SDLoc dl(Op);
18813   SDValue N0 = Op.getOperand(0);
18814   SDValue N1 = Op.getOperand(1);
18815   SDValue N2 = Op.getOperand(2);
18816 
18817   auto *N2C = dyn_cast<ConstantSDNode>(N2);
18818   if (!N2C || N2C->getAPIntValue().uge(NumElts))
18819     return SDValue();
18820   uint64_t IdxVal = N2C->getZExtValue();
18821 
18822   bool IsZeroElt = X86::isZeroNode(N1);
18823   bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
18824 
18825   // If we are inserting a element, see if we can do this more efficiently with
18826   // a blend shuffle with a rematerializable vector than a costly integer
18827   // insertion.
18828   if ((IsZeroElt || IsAllOnesElt) && Subtarget.hasSSE41() &&
18829       16 <= EltVT.getSizeInBits()) {
18830     SmallVector<int, 8> BlendMask;
18831     for (unsigned i = 0; i != NumElts; ++i)
18832       BlendMask.push_back(i == IdxVal ? i + NumElts : i);
18833     SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
18834                                   : getOnesVector(VT, DAG, dl);
18835     return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
18836   }
18837 
18838   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
18839   // into that, and then insert the subvector back into the result.
18840   if (VT.is256BitVector() || VT.is512BitVector()) {
18841     // With a 256-bit vector, we can insert into the zero element efficiently
18842     // using a blend if we have AVX or AVX2 and the right data type.
18843     if (VT.is256BitVector() && IdxVal == 0) {
18844       // TODO: It is worthwhile to cast integer to floating point and back
18845       // and incur a domain crossing penalty if that's what we'll end up
18846       // doing anyway after extracting to a 128-bit vector.
18847       if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
18848           (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
18849         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18850         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec,
18851                            DAG.getTargetConstant(1, dl, MVT::i8));
18852       }
18853     }
18854 
18855     // Get the desired 128-bit vector chunk.
18856     SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
18857 
18858     // Insert the element into the desired chunk.
18859     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
18860     assert(isPowerOf2_32(NumEltsIn128));
18861     // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
18862     unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
18863 
18864     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
18865                     DAG.getIntPtrConstant(IdxIn128, dl));
18866 
18867     // Insert the changed part back into the bigger vector
18868     return insert128BitVector(N0, V, IdxVal, DAG, dl);
18869   }
18870   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
18871 
18872   // This will be just movd/movq/movss/movsd.
18873   if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode())) {
18874     if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
18875         EltVT == MVT::i64) {
18876       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
18877       return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18878     }
18879 
18880     // We can't directly insert an i8 or i16 into a vector, so zero extend
18881     // it to i32 first.
18882     if (EltVT == MVT::i16 || EltVT == MVT::i8) {
18883       N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, N1);
18884       MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
18885       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, N1);
18886       N1 = getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
18887       return DAG.getBitcast(VT, N1);
18888     }
18889   }
18890 
18891   // Transform it so it match pinsr{b,w} which expects a GR32 as its second
18892   // argument. SSE41 required for pinsrb.
18893   if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
18894     unsigned Opc;
18895     if (VT == MVT::v8i16) {
18896       assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW");
18897       Opc = X86ISD::PINSRW;
18898     } else {
18899       assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector");
18900       assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB");
18901       Opc = X86ISD::PINSRB;
18902     }
18903 
18904     assert(N1.getValueType() != MVT::i32 && "Unexpected VT");
18905     N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
18906     N2 = DAG.getTargetConstant(IdxVal, dl, MVT::i8);
18907     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
18908   }
18909 
18910   if (Subtarget.hasSSE41()) {
18911     if (EltVT == MVT::f32) {
18912       // Bits [7:6] of the constant are the source select. This will always be
18913       //   zero here. The DAG Combiner may combine an extract_elt index into
18914       //   these bits. For example (insert (extract, 3), 2) could be matched by
18915       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
18916       // Bits [5:4] of the constant are the destination select. This is the
18917       //   value of the incoming immediate.
18918       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
18919       //   combine either bitwise AND or insert of float 0.0 to set these bits.
18920 
18921       bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
18922       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
18923         // If this is an insertion of 32-bits into the low 32-bits of
18924         // a vector, we prefer to generate a blend with immediate rather
18925         // than an insertps. Blends are simpler operations in hardware and so
18926         // will always have equal or better performance than insertps.
18927         // But if optimizing for size and there's a load folding opportunity,
18928         // generate insertps because blendps does not have a 32-bit memory
18929         // operand form.
18930         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18931         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1,
18932                            DAG.getTargetConstant(1, dl, MVT::i8));
18933       }
18934       // Create this as a scalar to vector..
18935       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
18936       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1,
18937                          DAG.getTargetConstant(IdxVal << 4, dl, MVT::i8));
18938     }
18939 
18940     // PINSR* works with constant index.
18941     if (EltVT == MVT::i32 || EltVT == MVT::i64)
18942       return Op;
18943   }
18944 
18945   return SDValue();
18946 }
18947 
18948 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
18949                                      SelectionDAG &DAG) {
18950   SDLoc dl(Op);
18951   MVT OpVT = Op.getSimpleValueType();
18952 
18953   // It's always cheaper to replace a xor+movd with xorps and simplifies further
18954   // combines.
18955   if (X86::isZeroNode(Op.getOperand(0)))
18956     return getZeroVector(OpVT, Subtarget, DAG, dl);
18957 
18958   // If this is a 256-bit vector result, first insert into a 128-bit
18959   // vector and then insert into the 256-bit vector.
18960   if (!OpVT.is128BitVector()) {
18961     // Insert into a 128-bit vector.
18962     unsigned SizeFactor = OpVT.getSizeInBits() / 128;
18963     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
18964                                  OpVT.getVectorNumElements() / SizeFactor);
18965 
18966     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
18967 
18968     // Insert the 128-bit vector.
18969     return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
18970   }
18971   assert(OpVT.is128BitVector() && OpVT.isInteger() && OpVT != MVT::v2i64 &&
18972          "Expected an SSE type!");
18973 
18974   // Pass through a v4i32 SCALAR_TO_VECTOR as that's what we use in tblgen.
18975   if (OpVT == MVT::v4i32)
18976     return Op;
18977 
18978   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
18979   return DAG.getBitcast(
18980       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
18981 }
18982 
18983 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
18984 // simple superregister reference or explicit instructions to insert
18985 // the upper bits of a vector.
18986 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18987                                      SelectionDAG &DAG) {
18988   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1);
18989 
18990   return insert1BitVector(Op, DAG, Subtarget);
18991 }
18992 
18993 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
18994                                       SelectionDAG &DAG) {
18995   assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
18996          "Only vXi1 extract_subvectors need custom lowering");
18997 
18998   SDLoc dl(Op);
18999   SDValue Vec = Op.getOperand(0);
19000   uint64_t IdxVal = Op.getConstantOperandVal(1);
19001 
19002   if (IdxVal == 0) // the operation is legal
19003     return Op;
19004 
19005   MVT VecVT = Vec.getSimpleValueType();
19006   unsigned NumElems = VecVT.getVectorNumElements();
19007 
19008   // Extend to natively supported kshift.
19009   MVT WideVecVT = VecVT;
19010   if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
19011     WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
19012     Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
19013                       DAG.getUNDEF(WideVecVT), Vec,
19014                       DAG.getIntPtrConstant(0, dl));
19015   }
19016 
19017   // Shift to the LSB.
19018   Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
19019                     DAG.getTargetConstant(IdxVal, dl, MVT::i8));
19020 
19021   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
19022                      DAG.getIntPtrConstant(0, dl));
19023 }
19024 
19025 // Returns the appropriate wrapper opcode for a global reference.
19026 unsigned X86TargetLowering::getGlobalWrapperKind(
19027     const GlobalValue *GV, const unsigned char OpFlags) const {
19028   // References to absolute symbols are never PC-relative.
19029   if (GV && GV->isAbsoluteSymbolRef())
19030     return X86ISD::Wrapper;
19031 
19032   CodeModel::Model M = getTargetMachine().getCodeModel();
19033   if (Subtarget.isPICStyleRIPRel() &&
19034       (M == CodeModel::Small || M == CodeModel::Kernel))
19035     return X86ISD::WrapperRIP;
19036 
19037   // GOTPCREL references must always use RIP.
19038   if (OpFlags == X86II::MO_GOTPCREL)
19039     return X86ISD::WrapperRIP;
19040 
19041   return X86ISD::Wrapper;
19042 }
19043 
19044 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
19045 // their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
19046 // one of the above mentioned nodes. It has to be wrapped because otherwise
19047 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
19048 // be used to form addressing mode. These wrapped nodes will be selected
19049 // into MOV32ri.
19050 SDValue
19051 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
19052   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
19053 
19054   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19055   // global base reg.
19056   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19057 
19058   auto PtrVT = getPointerTy(DAG.getDataLayout());
19059   SDValue Result = DAG.getTargetConstantPool(
19060       CP->getConstVal(), PtrVT, CP->getAlign(), CP->getOffset(), OpFlag);
19061   SDLoc DL(CP);
19062   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
19063   // With PIC, the address is actually $g + Offset.
19064   if (OpFlag) {
19065     Result =
19066         DAG.getNode(ISD::ADD, DL, PtrVT,
19067                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19068   }
19069 
19070   return Result;
19071 }
19072 
19073 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
19074   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
19075 
19076   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19077   // global base reg.
19078   unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
19079 
19080   auto PtrVT = getPointerTy(DAG.getDataLayout());
19081   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
19082   SDLoc DL(JT);
19083   Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
19084 
19085   // With PIC, the address is actually $g + Offset.
19086   if (OpFlag)
19087     Result =
19088         DAG.getNode(ISD::ADD, DL, PtrVT,
19089                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
19090 
19091   return Result;
19092 }
19093 
19094 SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
19095                                                SelectionDAG &DAG) const {
19096   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
19097 }
19098 
19099 SDValue
19100 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
19101   // Create the TargetBlockAddressAddress node.
19102   unsigned char OpFlags =
19103     Subtarget.classifyBlockAddressReference();
19104   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
19105   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
19106   SDLoc dl(Op);
19107   auto PtrVT = getPointerTy(DAG.getDataLayout());
19108   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
19109   Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
19110 
19111   // With PIC, the address is actually $g + Offset.
19112   if (isGlobalRelativeToPICBase(OpFlags)) {
19113     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19114                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19115   }
19116 
19117   return Result;
19118 }
19119 
19120 /// Creates target global address or external symbol nodes for calls or
19121 /// other uses.
19122 SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
19123                                                  bool ForCall) const {
19124   // Unpack the global address or external symbol.
19125   const SDLoc &dl = SDLoc(Op);
19126   const GlobalValue *GV = nullptr;
19127   int64_t Offset = 0;
19128   const char *ExternalSym = nullptr;
19129   if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
19130     GV = G->getGlobal();
19131     Offset = G->getOffset();
19132   } else {
19133     const auto *ES = cast<ExternalSymbolSDNode>(Op);
19134     ExternalSym = ES->getSymbol();
19135   }
19136 
19137   // Calculate some flags for address lowering.
19138   const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
19139   unsigned char OpFlags;
19140   if (ForCall)
19141     OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
19142   else
19143     OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
19144   bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
19145   bool NeedsLoad = isGlobalStubReference(OpFlags);
19146 
19147   CodeModel::Model M = DAG.getTarget().getCodeModel();
19148   auto PtrVT = getPointerTy(DAG.getDataLayout());
19149   SDValue Result;
19150 
19151   if (GV) {
19152     // Create a target global address if this is a global. If possible, fold the
19153     // offset into the global address reference. Otherwise, ADD it on later.
19154     // Suppress the folding if Offset is negative: movl foo-1, %eax is not
19155     // allowed because if the address of foo is 0, the ELF R_X86_64_32
19156     // relocation will compute to a negative value, which is invalid.
19157     int64_t GlobalOffset = 0;
19158     if (OpFlags == X86II::MO_NO_FLAG && Offset >= 0 &&
19159         X86::isOffsetSuitableForCodeModel(Offset, M, true)) {
19160       std::swap(GlobalOffset, Offset);
19161     }
19162     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
19163   } else {
19164     // If this is not a global address, this must be an external symbol.
19165     Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
19166   }
19167 
19168   // If this is a direct call, avoid the wrapper if we don't need to do any
19169   // loads or adds. This allows SDAG ISel to match direct calls.
19170   if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
19171     return Result;
19172 
19173   Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
19174 
19175   // With PIC, the address is actually $g + Offset.
19176   if (HasPICReg) {
19177     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
19178                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
19179   }
19180 
19181   // For globals that require a load from a stub to get the address, emit the
19182   // load.
19183   if (NeedsLoad)
19184     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
19185                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
19186 
19187   // If there was a non-zero offset that we didn't fold, create an explicit
19188   // addition for it.
19189   if (Offset != 0)
19190     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
19191                          DAG.getConstant(Offset, dl, PtrVT));
19192 
19193   return Result;
19194 }
19195 
19196 SDValue
19197 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
19198   return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
19199 }
19200 
19201 static SDValue
19202 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
19203            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
19204            unsigned char OperandFlags, bool LocalDynamic = false) {
19205   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
19206   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19207   SDLoc dl(GA);
19208   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19209                                            GA->getValueType(0),
19210                                            GA->getOffset(),
19211                                            OperandFlags);
19212 
19213   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
19214                                            : X86ISD::TLSADDR;
19215 
19216   if (InFlag) {
19217     SDValue Ops[] = { Chain,  TGA, *InFlag };
19218     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
19219   } else {
19220     SDValue Ops[]  = { Chain, TGA };
19221     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
19222   }
19223 
19224   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
19225   MFI.setAdjustsStack(true);
19226   MFI.setHasCalls(true);
19227 
19228   SDValue Flag = Chain.getValue(1);
19229   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
19230 }
19231 
19232 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
19233 static SDValue
19234 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19235                                 const EVT PtrVT) {
19236   SDValue InFlag;
19237   SDLoc dl(GA);  // ? function entry point might be better
19238   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
19239                                    DAG.getNode(X86ISD::GlobalBaseReg,
19240                                                SDLoc(), PtrVT), InFlag);
19241   InFlag = Chain.getValue(1);
19242 
19243   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
19244 }
19245 
19246 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit LP64
19247 static SDValue
19248 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19249                                 const EVT PtrVT) {
19250   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
19251                     X86::RAX, X86II::MO_TLSGD);
19252 }
19253 
19254 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit ILP32
19255 static SDValue
19256 LowerToTLSGeneralDynamicModelX32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19257                                  const EVT PtrVT) {
19258   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
19259                     X86::EAX, X86II::MO_TLSGD);
19260 }
19261 
19262 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
19263                                            SelectionDAG &DAG, const EVT PtrVT,
19264                                            bool Is64Bit, bool Is64BitLP64) {
19265   SDLoc dl(GA);
19266 
19267   // Get the start address of the TLS block for this module.
19268   X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
19269       .getInfo<X86MachineFunctionInfo>();
19270   MFI->incNumLocalDynamicTLSAccesses();
19271 
19272   SDValue Base;
19273   if (Is64Bit) {
19274     unsigned ReturnReg = Is64BitLP64 ? X86::RAX : X86::EAX;
19275     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, ReturnReg,
19276                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
19277   } else {
19278     SDValue InFlag;
19279     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
19280         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
19281     InFlag = Chain.getValue(1);
19282     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
19283                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
19284   }
19285 
19286   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
19287   // of Base.
19288 
19289   // Build x@dtpoff.
19290   unsigned char OperandFlags = X86II::MO_DTPOFF;
19291   unsigned WrapperKind = X86ISD::Wrapper;
19292   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19293                                            GA->getValueType(0),
19294                                            GA->getOffset(), OperandFlags);
19295   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19296 
19297   // Add x@dtpoff with the base.
19298   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
19299 }
19300 
19301 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
19302 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
19303                                    const EVT PtrVT, TLSModel::Model model,
19304                                    bool is64Bit, bool isPIC) {
19305   SDLoc dl(GA);
19306 
19307   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
19308   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
19309                                                          is64Bit ? 257 : 256));
19310 
19311   SDValue ThreadPointer =
19312       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
19313                   MachinePointerInfo(Ptr));
19314 
19315   unsigned char OperandFlags = 0;
19316   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
19317   // initialexec.
19318   unsigned WrapperKind = X86ISD::Wrapper;
19319   if (model == TLSModel::LocalExec) {
19320     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
19321   } else if (model == TLSModel::InitialExec) {
19322     if (is64Bit) {
19323       OperandFlags = X86II::MO_GOTTPOFF;
19324       WrapperKind = X86ISD::WrapperRIP;
19325     } else {
19326       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
19327     }
19328   } else {
19329     llvm_unreachable("Unexpected model");
19330   }
19331 
19332   // emit "addl x@ntpoff,%eax" (local exec)
19333   // or "addl x@indntpoff,%eax" (initial exec)
19334   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
19335   SDValue TGA =
19336       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
19337                                  GA->getOffset(), OperandFlags);
19338   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
19339 
19340   if (model == TLSModel::InitialExec) {
19341     if (isPIC && !is64Bit) {
19342       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
19343                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
19344                            Offset);
19345     }
19346 
19347     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
19348                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
19349   }
19350 
19351   // The address of the thread local variable is the add of the thread
19352   // pointer with the offset of the variable.
19353   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
19354 }
19355 
19356 SDValue
19357 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
19358 
19359   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
19360 
19361   if (DAG.getTarget().useEmulatedTLS())
19362     return LowerToTLSEmulatedModel(GA, DAG);
19363 
19364   const GlobalValue *GV = GA->getGlobal();
19365   auto PtrVT = getPointerTy(DAG.getDataLayout());
19366   bool PositionIndependent = isPositionIndependent();
19367 
19368   if (Subtarget.isTargetELF()) {
19369     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
19370     switch (model) {
19371       case TLSModel::GeneralDynamic:
19372         if (Subtarget.is64Bit()) {
19373           if (Subtarget.isTarget64BitLP64())
19374             return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
19375           return LowerToTLSGeneralDynamicModelX32(GA, DAG, PtrVT);
19376         }
19377         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
19378       case TLSModel::LocalDynamic:
19379         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT, Subtarget.is64Bit(),
19380                                            Subtarget.isTarget64BitLP64());
19381       case TLSModel::InitialExec:
19382       case TLSModel::LocalExec:
19383         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
19384                                    PositionIndependent);
19385     }
19386     llvm_unreachable("Unknown TLS model.");
19387   }
19388 
19389   if (Subtarget.isTargetDarwin()) {
19390     // Darwin only has one model of TLS.  Lower to that.
19391     unsigned char OpFlag = 0;
19392     unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
19393                            X86ISD::WrapperRIP : X86ISD::Wrapper;
19394 
19395     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
19396     // global base reg.
19397     bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
19398     if (PIC32)
19399       OpFlag = X86II::MO_TLVP_PIC_BASE;
19400     else
19401       OpFlag = X86II::MO_TLVP;
19402     SDLoc DL(Op);
19403     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
19404                                                 GA->getValueType(0),
19405                                                 GA->getOffset(), OpFlag);
19406     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
19407 
19408     // With PIC32, the address is actually $g + Offset.
19409     if (PIC32)
19410       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
19411                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
19412                            Offset);
19413 
19414     // Lowering the machine isd will make sure everything is in the right
19415     // location.
19416     SDValue Chain = DAG.getEntryNode();
19417     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
19418     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
19419     SDValue Args[] = { Chain, Offset };
19420     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
19421     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
19422                                DAG.getIntPtrConstant(0, DL, true),
19423                                Chain.getValue(1), DL);
19424 
19425     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
19426     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
19427     MFI.setAdjustsStack(true);
19428 
19429     // And our return value (tls address) is in the standard call return value
19430     // location.
19431     unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
19432     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
19433   }
19434 
19435   if (Subtarget.isOSWindows()) {
19436     // Just use the implicit TLS architecture
19437     // Need to generate something similar to:
19438     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
19439     //                                  ; from TEB
19440     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
19441     //   mov     rcx, qword [rdx+rcx*8]
19442     //   mov     eax, .tls$:tlsvar
19443     //   [rax+rcx] contains the address
19444     // Windows 64bit: gs:0x58
19445     // Windows 32bit: fs:__tls_array
19446 
19447     SDLoc dl(GA);
19448     SDValue Chain = DAG.getEntryNode();
19449 
19450     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
19451     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
19452     // use its literal value of 0x2C.
19453     Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
19454                                         ? Type::getInt8PtrTy(*DAG.getContext(),
19455                                                              256)
19456                                         : Type::getInt32PtrTy(*DAG.getContext(),
19457                                                               257));
19458 
19459     SDValue TlsArray = Subtarget.is64Bit()
19460                            ? DAG.getIntPtrConstant(0x58, dl)
19461                            : (Subtarget.isTargetWindowsGNU()
19462                                   ? DAG.getIntPtrConstant(0x2C, dl)
19463                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
19464 
19465     SDValue ThreadPointer =
19466         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
19467 
19468     SDValue res;
19469     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
19470       res = ThreadPointer;
19471     } else {
19472       // Load the _tls_index variable
19473       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
19474       if (Subtarget.is64Bit())
19475         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
19476                              MachinePointerInfo(), MVT::i32);
19477       else
19478         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
19479 
19480       const DataLayout &DL = DAG.getDataLayout();
19481       SDValue Scale =
19482           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
19483       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
19484 
19485       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
19486     }
19487 
19488     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
19489 
19490     // Get the offset of start of .tls section
19491     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
19492                                              GA->getValueType(0),
19493                                              GA->getOffset(), X86II::MO_SECREL);
19494     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
19495 
19496     // The address of the thread local variable is the add of the thread
19497     // pointer with the offset of the variable.
19498     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
19499   }
19500 
19501   llvm_unreachable("TLS not implemented for this target.");
19502 }
19503 
19504 /// Lower SRA_PARTS and friends, which return two i32 values
19505 /// and take a 2 x i32 value to shift plus a shift amount.
19506 /// TODO: Can this be moved to general expansion code?
19507 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
19508   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
19509   MVT VT = Op.getSimpleValueType();
19510   unsigned VTBits = VT.getSizeInBits();
19511   SDLoc dl(Op);
19512   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
19513   SDValue ShOpLo = Op.getOperand(0);
19514   SDValue ShOpHi = Op.getOperand(1);
19515   SDValue ShAmt  = Op.getOperand(2);
19516   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
19517   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's optimized away
19518   // during isel.
19519   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
19520                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
19521   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
19522                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
19523                        : DAG.getConstant(0, dl, VT);
19524 
19525   SDValue Tmp2, Tmp3;
19526   if (Op.getOpcode() == ISD::SHL_PARTS) {
19527     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
19528     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
19529   } else {
19530     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
19531     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
19532   }
19533 
19534   // If the shift amount is larger or equal than the width of a part we can't
19535   // rely on the results of shld/shrd. Insert a test and select the appropriate
19536   // values for large shift amounts.
19537   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
19538                                 DAG.getConstant(VTBits, dl, MVT::i8));
19539   SDValue Cond = DAG.getSetCC(dl, MVT::i8, AndNode,
19540                              DAG.getConstant(0, dl, MVT::i8), ISD::SETNE);
19541 
19542   SDValue Hi, Lo;
19543   if (Op.getOpcode() == ISD::SHL_PARTS) {
19544     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
19545     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
19546   } else {
19547     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
19548     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
19549   }
19550 
19551   return DAG.getMergeValues({ Lo, Hi }, dl);
19552 }
19553 
19554 static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
19555                                 SelectionDAG &DAG) {
19556   MVT VT = Op.getSimpleValueType();
19557   assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&
19558          "Unexpected funnel shift opcode!");
19559 
19560   SDLoc DL(Op);
19561   SDValue Op0 = Op.getOperand(0);
19562   SDValue Op1 = Op.getOperand(1);
19563   SDValue Amt = Op.getOperand(2);
19564 
19565   bool IsFSHR = Op.getOpcode() == ISD::FSHR;
19566 
19567   if (VT.isVector()) {
19568     assert(Subtarget.hasVBMI2() && "Expected VBMI2");
19569 
19570     if (IsFSHR)
19571       std::swap(Op0, Op1);
19572 
19573     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
19574     if (!Subtarget.hasVLX() && !VT.is512BitVector()) {
19575       Op0 = widenSubVector(Op0, false, Subtarget, DAG, DL, 512);
19576       Op1 = widenSubVector(Op1, false, Subtarget, DAG, DL, 512);
19577     }
19578 
19579     SDValue Funnel;
19580     APInt APIntShiftAmt;
19581     MVT ResultVT = Op0.getSimpleValueType();
19582     if (X86::isConstantSplat(Amt, APIntShiftAmt)) {
19583       uint64_t ShiftAmt = APIntShiftAmt.urem(VT.getScalarSizeInBits());
19584       Funnel =
19585           DAG.getNode(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, ResultVT, Op0,
19586                       Op1, DAG.getTargetConstant(ShiftAmt, DL, MVT::i8));
19587     } else {
19588       if (!Subtarget.hasVLX() && !VT.is512BitVector())
19589         Amt = widenSubVector(Amt, false, Subtarget, DAG, DL, 512);
19590       Funnel = DAG.getNode(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL,
19591                            ResultVT, Op0, Op1, Amt);
19592     }
19593     if (!Subtarget.hasVLX() && !VT.is512BitVector())
19594       Funnel = extractSubVector(Funnel, 0, DAG, DL, VT.getSizeInBits());
19595     return Funnel;
19596   }
19597   assert(
19598       (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
19599       "Unexpected funnel shift type!");
19600 
19601   // Expand slow SHLD/SHRD cases if we are not optimizing for size.
19602   bool OptForSize = DAG.shouldOptForSize();
19603   bool ExpandFunnel = !OptForSize && Subtarget.isSHLDSlow();
19604 
19605   // fshl(x,y,z) -> (((aext(x) << bw) | zext(y)) << (z & (bw-1))) >> bw.
19606   // fshr(x,y,z) -> (((aext(x) << bw) | zext(y)) >> (z & (bw-1))).
19607   if ((VT == MVT::i8 || (ExpandFunnel && VT == MVT::i16)) &&
19608       !isa<ConstantSDNode>(Amt)) {
19609     unsigned EltSizeInBits = VT.getScalarSizeInBits();
19610     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, Amt.getValueType());
19611     SDValue HiShift = DAG.getConstant(EltSizeInBits, DL, Amt.getValueType());
19612     Op0 = DAG.getAnyExtOrTrunc(Op0, DL, MVT::i32);
19613     Op1 = DAG.getZExtOrTrunc(Op1, DL, MVT::i32);
19614     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt, Mask);
19615     SDValue Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Op0, HiShift);
19616     Res = DAG.getNode(ISD::OR, DL, MVT::i32, Res, Op1);
19617     if (IsFSHR) {
19618       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, Amt);
19619     } else {
19620       Res = DAG.getNode(ISD::SHL, DL, MVT::i32, Res, Amt);
19621       Res = DAG.getNode(ISD::SRL, DL, MVT::i32, Res, HiShift);
19622     }
19623     return DAG.getZExtOrTrunc(Res, DL, VT);
19624   }
19625 
19626   if (VT == MVT::i8 || ExpandFunnel)
19627     return SDValue();
19628 
19629   // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
19630   if (VT == MVT::i16) {
19631     Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
19632                       DAG.getConstant(15, DL, Amt.getValueType()));
19633     unsigned FSHOp = (IsFSHR ? X86ISD::FSHR : X86ISD::FSHL);
19634     return DAG.getNode(FSHOp, DL, VT, Op0, Op1, Amt);
19635   }
19636 
19637   return Op;
19638 }
19639 
19640 // Try to use a packed vector operation to handle i64 on 32-bit targets when
19641 // AVX512DQ is enabled.
19642 static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
19643                                         const X86Subtarget &Subtarget) {
19644   assert((Op.getOpcode() == ISD::SINT_TO_FP ||
19645           Op.getOpcode() == ISD::STRICT_SINT_TO_FP ||
19646           Op.getOpcode() == ISD::STRICT_UINT_TO_FP ||
19647           Op.getOpcode() == ISD::UINT_TO_FP) &&
19648          "Unexpected opcode!");
19649   bool IsStrict = Op->isStrictFPOpcode();
19650   unsigned OpNo = IsStrict ? 1 : 0;
19651   SDValue Src = Op.getOperand(OpNo);
19652   MVT SrcVT = Src.getSimpleValueType();
19653   MVT VT = Op.getSimpleValueType();
19654 
19655    if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
19656        (VT != MVT::f32 && VT != MVT::f64))
19657     return SDValue();
19658 
19659   // Pack the i64 into a vector, do the operation and extract.
19660 
19661   // Using 256-bit to ensure result is 128-bits for f32 case.
19662   unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
19663   MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
19664   MVT VecVT = MVT::getVectorVT(VT, NumElts);
19665 
19666   SDLoc dl(Op);
19667   SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
19668   if (IsStrict) {
19669     SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, {VecVT, MVT::Other},
19670                                  {Op.getOperand(0), InVec});
19671     SDValue Chain = CvtVec.getValue(1);
19672     SDValue Value = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19673                                 DAG.getIntPtrConstant(0, dl));
19674     return DAG.getMergeValues({Value, Chain}, dl);
19675   }
19676 
19677   SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
19678 
19679   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
19680                      DAG.getIntPtrConstant(0, dl));
19681 }
19682 
19683 static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
19684                           const X86Subtarget &Subtarget) {
19685   switch (Opcode) {
19686     case ISD::SINT_TO_FP:
19687       // TODO: Handle wider types with AVX/AVX512.
19688       if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
19689         return false;
19690       // CVTDQ2PS or (V)CVTDQ2PD
19691       return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
19692 
19693     case ISD::UINT_TO_FP:
19694       // TODO: Handle wider types and i64 elements.
19695       if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
19696         return false;
19697       // VCVTUDQ2PS or VCVTUDQ2PD
19698       return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
19699 
19700     default:
19701       return false;
19702   }
19703 }
19704 
19705 /// Given a scalar cast operation that is extracted from a vector, try to
19706 /// vectorize the cast op followed by extraction. This will avoid an expensive
19707 /// round-trip between XMM and GPR.
19708 static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
19709                                       const X86Subtarget &Subtarget) {
19710   // TODO: This could be enhanced to handle smaller integer types by peeking
19711   // through an extend.
19712   SDValue Extract = Cast.getOperand(0);
19713   MVT DestVT = Cast.getSimpleValueType();
19714   if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19715       !isa<ConstantSDNode>(Extract.getOperand(1)))
19716     return SDValue();
19717 
19718   // See if we have a 128-bit vector cast op for this type of cast.
19719   SDValue VecOp = Extract.getOperand(0);
19720   MVT FromVT = VecOp.getSimpleValueType();
19721   unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
19722   MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
19723   MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
19724   if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
19725     return SDValue();
19726 
19727   // If we are extracting from a non-zero element, first shuffle the source
19728   // vector to allow extracting from element zero.
19729   SDLoc DL(Cast);
19730   if (!isNullConstant(Extract.getOperand(1))) {
19731     SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
19732     Mask[0] = Extract.getConstantOperandVal(1);
19733     VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
19734   }
19735   // If the source vector is wider than 128-bits, extract the low part. Do not
19736   // create an unnecessarily wide vector cast op.
19737   if (FromVT != Vec128VT)
19738     VecOp = extract128BitVector(VecOp, 0, DAG, DL);
19739 
19740   // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
19741   // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
19742   SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
19743   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
19744                      DAG.getIntPtrConstant(0, DL));
19745 }
19746 
19747 /// Given a scalar cast to FP with a cast to integer operand (almost an ftrunc),
19748 /// try to vectorize the cast ops. This will avoid an expensive round-trip
19749 /// between XMM and GPR.
19750 static SDValue lowerFPToIntToFP(SDValue CastToFP, SelectionDAG &DAG,
19751                                 const X86Subtarget &Subtarget) {
19752   // TODO: Allow FP_TO_UINT.
19753   SDValue CastToInt = CastToFP.getOperand(0);
19754   MVT VT = CastToFP.getSimpleValueType();
19755   if (CastToInt.getOpcode() != ISD::FP_TO_SINT || VT.isVector())
19756     return SDValue();
19757 
19758   MVT IntVT = CastToInt.getSimpleValueType();
19759   SDValue X = CastToInt.getOperand(0);
19760   MVT SrcVT = X.getSimpleValueType();
19761   if (SrcVT != MVT::f32 && SrcVT != MVT::f64)
19762     return SDValue();
19763 
19764   // See if we have 128-bit vector cast instructions for this type of cast.
19765   // We need cvttps2dq/cvttpd2dq and cvtdq2ps/cvtdq2pd.
19766   if (!Subtarget.hasSSE2() || (VT != MVT::f32 && VT != MVT::f64) ||
19767       IntVT != MVT::i32)
19768     return SDValue();
19769 
19770   unsigned SrcSize = SrcVT.getSizeInBits();
19771   unsigned IntSize = IntVT.getSizeInBits();
19772   unsigned VTSize = VT.getSizeInBits();
19773   MVT VecSrcVT = MVT::getVectorVT(SrcVT, 128 / SrcSize);
19774   MVT VecIntVT = MVT::getVectorVT(IntVT, 128 / IntSize);
19775   MVT VecVT = MVT::getVectorVT(VT, 128 / VTSize);
19776 
19777   // We need target-specific opcodes if this is v2f64 -> v4i32 -> v2f64.
19778   unsigned ToIntOpcode =
19779       SrcSize != IntSize ? X86ISD::CVTTP2SI : (unsigned)ISD::FP_TO_SINT;
19780   unsigned ToFPOpcode =
19781       IntSize != VTSize ? X86ISD::CVTSI2P : (unsigned)ISD::SINT_TO_FP;
19782 
19783   // sint_to_fp (fp_to_sint X) --> extelt (sint_to_fp (fp_to_sint (s2v X))), 0
19784   //
19785   // We are not defining the high elements (for example, zero them) because
19786   // that could nullify any performance advantage that we hoped to gain from
19787   // this vector op hack. We do not expect any adverse effects (like denorm
19788   // penalties) with cast ops.
19789   SDLoc DL(CastToFP);
19790   SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
19791   SDValue VecX = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecSrcVT, X);
19792   SDValue VCastToInt = DAG.getNode(ToIntOpcode, DL, VecIntVT, VecX);
19793   SDValue VCastToFP = DAG.getNode(ToFPOpcode, DL, VecVT, VCastToInt);
19794   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, VCastToFP, ZeroIdx);
19795 }
19796 
19797 static SDValue lowerINT_TO_FP_vXi64(SDValue Op, SelectionDAG &DAG,
19798                                     const X86Subtarget &Subtarget) {
19799   SDLoc DL(Op);
19800   bool IsStrict = Op->isStrictFPOpcode();
19801   MVT VT = Op->getSimpleValueType(0);
19802   SDValue Src = Op->getOperand(IsStrict ? 1 : 0);
19803 
19804   if (Subtarget.hasDQI()) {
19805     assert(!Subtarget.hasVLX() && "Unexpected features");
19806 
19807     assert((Src.getSimpleValueType() == MVT::v2i64 ||
19808             Src.getSimpleValueType() == MVT::v4i64) &&
19809            "Unsupported custom type");
19810 
19811     // With AVX512DQ, but not VLX we need to widen to get a 512-bit result type.
19812     assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v4f64) &&
19813            "Unexpected VT!");
19814     MVT WideVT = VT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
19815 
19816     // Need to concat with zero vector for strict fp to avoid spurious
19817     // exceptions.
19818     SDValue Tmp = IsStrict ? DAG.getConstant(0, DL, MVT::v8i64)
19819                            : DAG.getUNDEF(MVT::v8i64);
19820     Src = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i64, Tmp, Src,
19821                       DAG.getIntPtrConstant(0, DL));
19822     SDValue Res, Chain;
19823     if (IsStrict) {
19824       Res = DAG.getNode(Op.getOpcode(), DL, {WideVT, MVT::Other},
19825                         {Op->getOperand(0), Src});
19826       Chain = Res.getValue(1);
19827     } else {
19828       Res = DAG.getNode(Op.getOpcode(), DL, WideVT, Src);
19829     }
19830 
19831     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
19832                       DAG.getIntPtrConstant(0, DL));
19833 
19834     if (IsStrict)
19835       return DAG.getMergeValues({Res, Chain}, DL);
19836     return Res;
19837   }
19838 
19839   bool IsSigned = Op->getOpcode() == ISD::SINT_TO_FP ||
19840                   Op->getOpcode() == ISD::STRICT_SINT_TO_FP;
19841   if (VT != MVT::v4f32 || IsSigned)
19842     return SDValue();
19843 
19844   SDValue Zero = DAG.getConstant(0, DL, MVT::v4i64);
19845   SDValue One  = DAG.getConstant(1, DL, MVT::v4i64);
19846   SDValue Sign = DAG.getNode(ISD::OR, DL, MVT::v4i64,
19847                              DAG.getNode(ISD::SRL, DL, MVT::v4i64, Src, One),
19848                              DAG.getNode(ISD::AND, DL, MVT::v4i64, Src, One));
19849   SDValue IsNeg = DAG.getSetCC(DL, MVT::v4i64, Src, Zero, ISD::SETLT);
19850   SDValue SignSrc = DAG.getSelect(DL, MVT::v4i64, IsNeg, Sign, Src);
19851   SmallVector<SDValue, 4> SignCvts(4);
19852   SmallVector<SDValue, 4> Chains(4);
19853   for (int i = 0; i != 4; ++i) {
19854     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i64, SignSrc,
19855                               DAG.getIntPtrConstant(i, DL));
19856     if (IsStrict) {
19857       SignCvts[i] =
19858           DAG.getNode(ISD::STRICT_SINT_TO_FP, DL, {MVT::f32, MVT::Other},
19859                       {Op.getOperand(0), Elt});
19860       Chains[i] = SignCvts[i].getValue(1);
19861     } else {
19862       SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, DL, MVT::f32, Elt);
19863     }
19864   }
19865   SDValue SignCvt = DAG.getBuildVector(VT, DL, SignCvts);
19866 
19867   SDValue Slow, Chain;
19868   if (IsStrict) {
19869     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
19870     Slow = DAG.getNode(ISD::STRICT_FADD, DL, {MVT::v4f32, MVT::Other},
19871                        {Chain, SignCvt, SignCvt});
19872     Chain = Slow.getValue(1);
19873   } else {
19874     Slow = DAG.getNode(ISD::FADD, DL, MVT::v4f32, SignCvt, SignCvt);
19875   }
19876 
19877   IsNeg = DAG.getNode(ISD::TRUNCATE, DL, MVT::v4i32, IsNeg);
19878   SDValue Cvt = DAG.getSelect(DL, MVT::v4f32, IsNeg, Slow, SignCvt);
19879 
19880   if (IsStrict)
19881     return DAG.getMergeValues({Cvt, Chain}, DL);
19882 
19883   return Cvt;
19884 }
19885 
19886 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
19887                                            SelectionDAG &DAG) const {
19888   bool IsStrict = Op->isStrictFPOpcode();
19889   unsigned OpNo = IsStrict ? 1 : 0;
19890   SDValue Src = Op.getOperand(OpNo);
19891   SDValue Chain = IsStrict ? Op->getOperand(0) : DAG.getEntryNode();
19892   MVT SrcVT = Src.getSimpleValueType();
19893   MVT VT = Op.getSimpleValueType();
19894   SDLoc dl(Op);
19895 
19896   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
19897     return Extract;
19898 
19899   if (SDValue R = lowerFPToIntToFP(Op, DAG, Subtarget))
19900     return R;
19901 
19902   if (SrcVT.isVector()) {
19903     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
19904       // Note: Since v2f64 is a legal type. We don't need to zero extend the
19905       // source for strict FP.
19906       if (IsStrict)
19907         return DAG.getNode(
19908             X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
19909             {Chain, DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19910                                 DAG.getUNDEF(SrcVT))});
19911       return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
19912                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
19913                                      DAG.getUNDEF(SrcVT)));
19914     }
19915     if (SrcVT == MVT::v2i64 || SrcVT == MVT::v4i64)
19916       return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
19917 
19918     return SDValue();
19919   }
19920 
19921   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
19922          "Unknown SINT_TO_FP to lower!");
19923 
19924   bool UseSSEReg = isScalarFPTypeInSSEReg(VT);
19925 
19926   // These are really Legal; return the operand so the caller accepts it as
19927   // Legal.
19928   if (SrcVT == MVT::i32 && UseSSEReg)
19929     return Op;
19930   if (SrcVT == MVT::i64 && UseSSEReg && Subtarget.is64Bit())
19931     return Op;
19932 
19933   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
19934     return V;
19935 
19936   // SSE doesn't have an i16 conversion so we need to promote.
19937   if (SrcVT == MVT::i16 && (UseSSEReg || VT == MVT::f128)) {
19938     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i32, Src);
19939     if (IsStrict)
19940       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
19941                          {Chain, Ext});
19942 
19943     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Ext);
19944   }
19945 
19946   if (VT == MVT::f128)
19947     return SDValue();
19948 
19949   SDValue ValueToStore = Src;
19950   if (SrcVT == MVT::i64 && Subtarget.hasSSE2() && !Subtarget.is64Bit())
19951     // Bitcasting to f64 here allows us to do a single 64-bit store from
19952     // an SSE register, avoiding the store forwarding penalty that would come
19953     // with two 32-bit stores.
19954     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
19955 
19956   unsigned Size = SrcVT.getStoreSize();
19957   Align Alignment(Size);
19958   MachineFunction &MF = DAG.getMachineFunction();
19959   auto PtrVT = getPointerTy(MF.getDataLayout());
19960   int SSFI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false);
19961   MachinePointerInfo MPI =
19962       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
19963   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19964   Chain = DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, Alignment);
19965   std::pair<SDValue, SDValue> Tmp =
19966       BuildFILD(VT, SrcVT, dl, Chain, StackSlot, MPI, Alignment, DAG);
19967 
19968   if (IsStrict)
19969     return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
19970 
19971   return Tmp.first;
19972 }
19973 
19974 std::pair<SDValue, SDValue> X86TargetLowering::BuildFILD(
19975     EVT DstVT, EVT SrcVT, const SDLoc &DL, SDValue Chain, SDValue Pointer,
19976     MachinePointerInfo PtrInfo, Align Alignment, SelectionDAG &DAG) const {
19977   // Build the FILD
19978   SDVTList Tys;
19979   bool useSSE = isScalarFPTypeInSSEReg(DstVT);
19980   if (useSSE)
19981     Tys = DAG.getVTList(MVT::f80, MVT::Other);
19982   else
19983     Tys = DAG.getVTList(DstVT, MVT::Other);
19984 
19985   SDValue FILDOps[] = {Chain, Pointer};
19986   SDValue Result =
19987       DAG.getMemIntrinsicNode(X86ISD::FILD, DL, Tys, FILDOps, SrcVT, PtrInfo,
19988                               Alignment, MachineMemOperand::MOLoad);
19989   Chain = Result.getValue(1);
19990 
19991   if (useSSE) {
19992     MachineFunction &MF = DAG.getMachineFunction();
19993     unsigned SSFISize = DstVT.getStoreSize();
19994     int SSFI =
19995         MF.getFrameInfo().CreateStackObject(SSFISize, Align(SSFISize), false);
19996     auto PtrVT = getPointerTy(MF.getDataLayout());
19997     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
19998     Tys = DAG.getVTList(MVT::Other);
19999     SDValue FSTOps[] = {Chain, Result, StackSlot};
20000     MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
20001         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
20002         MachineMemOperand::MOStore, SSFISize, Align(SSFISize));
20003 
20004     Chain =
20005         DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps, DstVT, StoreMMO);
20006     Result = DAG.getLoad(
20007         DstVT, DL, Chain, StackSlot,
20008         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
20009     Chain = Result.getValue(1);
20010   }
20011 
20012   return { Result, Chain };
20013 }
20014 
20015 /// Horizontal vector math instructions may be slower than normal math with
20016 /// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
20017 /// implementation, and likely shuffle complexity of the alternate sequence.
20018 static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
20019                                   const X86Subtarget &Subtarget) {
20020   bool IsOptimizingSize = DAG.shouldOptForSize();
20021   bool HasFastHOps = Subtarget.hasFastHorizontalOps();
20022   return !IsSingleSource || IsOptimizingSize || HasFastHOps;
20023 }
20024 
20025 /// 64-bit unsigned integer to double expansion.
20026 static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
20027                                    const X86Subtarget &Subtarget) {
20028   // We can't use this algorithm for strict fp. It produces -0.0 instead of +0.0
20029   // when converting 0 when rounding toward negative infinity. Caller will
20030   // fall back to Expand for when i64 or is legal or use FILD in 32-bit mode.
20031   assert(!Op->isStrictFPOpcode() && "Expected non-strict uint_to_fp!");
20032   // This algorithm is not obvious. Here it is what we're trying to output:
20033   /*
20034      movq       %rax,  %xmm0
20035      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
20036      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
20037      #ifdef __SSE3__
20038        haddpd   %xmm0, %xmm0
20039      #else
20040        pshufd   $0x4e, %xmm0, %xmm1
20041        addpd    %xmm1, %xmm0
20042      #endif
20043   */
20044 
20045   SDLoc dl(Op);
20046   LLVMContext *Context = DAG.getContext();
20047 
20048   // Build some magic constants.
20049   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
20050   Constant *C0 = ConstantDataVector::get(*Context, CV0);
20051   auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20052   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, Align(16));
20053 
20054   SmallVector<Constant*,2> CV1;
20055   CV1.push_back(
20056     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20057                                       APInt(64, 0x4330000000000000ULL))));
20058   CV1.push_back(
20059     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
20060                                       APInt(64, 0x4530000000000000ULL))));
20061   Constant *C1 = ConstantVector::get(CV1);
20062   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, Align(16));
20063 
20064   // Load the 64-bit value into an XMM register.
20065   SDValue XR1 =
20066       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Op.getOperand(0));
20067   SDValue CLod0 = DAG.getLoad(
20068       MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
20069       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
20070   SDValue Unpck1 =
20071       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
20072 
20073   SDValue CLod1 = DAG.getLoad(
20074       MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
20075       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(16));
20076   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
20077   // TODO: Are there any fast-math-flags to propagate here?
20078   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
20079   SDValue Result;
20080 
20081   if (Subtarget.hasSSE3() &&
20082       shouldUseHorizontalOp(true, DAG, Subtarget)) {
20083     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
20084   } else {
20085     SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
20086     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
20087   }
20088   Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
20089                        DAG.getIntPtrConstant(0, dl));
20090   return Result;
20091 }
20092 
20093 /// 32-bit unsigned integer to float expansion.
20094 static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
20095                                    const X86Subtarget &Subtarget) {
20096   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20097   SDLoc dl(Op);
20098   // FP constant to bias correct the final result.
20099   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20100                                    MVT::f64);
20101 
20102   // Load the 32-bit value into an XMM register.
20103   SDValue Load =
20104       DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Op.getOperand(OpNo));
20105 
20106   // Zero out the upper parts of the register.
20107   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
20108 
20109   // Or the load with the bias.
20110   SDValue Or = DAG.getNode(
20111       ISD::OR, dl, MVT::v2i64,
20112       DAG.getBitcast(MVT::v2i64, Load),
20113       DAG.getBitcast(MVT::v2i64,
20114                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
20115   Or =
20116       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
20117                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
20118 
20119   if (Op.getNode()->isStrictFPOpcode()) {
20120     // Subtract the bias.
20121     // TODO: Are there any fast-math-flags to propagate here?
20122     SDValue Chain = Op.getOperand(0);
20123     SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
20124                               {Chain, Or, Bias});
20125 
20126     if (Op.getValueType() == Sub.getValueType())
20127       return Sub;
20128 
20129     // Handle final rounding.
20130     std::pair<SDValue, SDValue> ResultPair = DAG.getStrictFPExtendOrRound(
20131         Sub, Sub.getValue(1), dl, Op.getSimpleValueType());
20132 
20133     return DAG.getMergeValues({ResultPair.first, ResultPair.second}, dl);
20134   }
20135 
20136   // Subtract the bias.
20137   // TODO: Are there any fast-math-flags to propagate here?
20138   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
20139 
20140   // Handle final rounding.
20141   return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
20142 }
20143 
20144 static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
20145                                      const X86Subtarget &Subtarget,
20146                                      const SDLoc &DL) {
20147   if (Op.getSimpleValueType() != MVT::v2f64)
20148     return SDValue();
20149 
20150   bool IsStrict = Op->isStrictFPOpcode();
20151 
20152   SDValue N0 = Op.getOperand(IsStrict ? 1 : 0);
20153   assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type");
20154 
20155   if (Subtarget.hasAVX512()) {
20156     if (!Subtarget.hasVLX()) {
20157       // Let generic type legalization widen this.
20158       if (!IsStrict)
20159         return SDValue();
20160       // Otherwise pad the integer input with 0s and widen the operation.
20161       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20162                        DAG.getConstant(0, DL, MVT::v2i32));
20163       SDValue Res = DAG.getNode(Op->getOpcode(), DL, {MVT::v4f64, MVT::Other},
20164                                 {Op.getOperand(0), N0});
20165       SDValue Chain = Res.getValue(1);
20166       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2f64, Res,
20167                         DAG.getIntPtrConstant(0, DL));
20168       return DAG.getMergeValues({Res, Chain}, DL);
20169     }
20170 
20171     // Legalize to v4i32 type.
20172     N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
20173                      DAG.getUNDEF(MVT::v2i32));
20174     if (IsStrict)
20175       return DAG.getNode(X86ISD::STRICT_CVTUI2P, DL, {MVT::v2f64, MVT::Other},
20176                          {Op.getOperand(0), N0});
20177     return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
20178   }
20179 
20180   // Zero extend to 2i64, OR with the floating point representation of 2^52.
20181   // This gives us the floating point equivalent of 2^52 + the i32 integer
20182   // since double has 52-bits of mantissa. Then subtract 2^52 in floating
20183   // point leaving just our i32 integers in double format.
20184   SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v2i64, N0);
20185   SDValue VBias =
20186       DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), DL, MVT::v2f64);
20187   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v2i64, ZExtIn,
20188                            DAG.getBitcast(MVT::v2i64, VBias));
20189   Or = DAG.getBitcast(MVT::v2f64, Or);
20190 
20191   if (IsStrict)
20192     return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v2f64, MVT::Other},
20193                        {Op.getOperand(0), Or, VBias});
20194   return DAG.getNode(ISD::FSUB, DL, MVT::v2f64, Or, VBias);
20195 }
20196 
20197 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
20198                                      const X86Subtarget &Subtarget) {
20199   SDLoc DL(Op);
20200   bool IsStrict = Op->isStrictFPOpcode();
20201   SDValue V = Op->getOperand(IsStrict ? 1 : 0);
20202   MVT VecIntVT = V.getSimpleValueType();
20203   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
20204          "Unsupported custom type");
20205 
20206   if (Subtarget.hasAVX512()) {
20207     // With AVX512, but not VLX we need to widen to get a 512-bit result type.
20208     assert(!Subtarget.hasVLX() && "Unexpected features");
20209     MVT VT = Op->getSimpleValueType(0);
20210 
20211     // v8i32->v8f64 is legal with AVX512 so just return it.
20212     if (VT == MVT::v8f64)
20213       return Op;
20214 
20215     assert((VT == MVT::v4f32 || VT == MVT::v8f32 || VT == MVT::v4f64) &&
20216            "Unexpected VT!");
20217     MVT WideVT = VT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
20218     MVT WideIntVT = VT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
20219     // Need to concat with zero vector for strict fp to avoid spurious
20220     // exceptions.
20221     SDValue Tmp =
20222         IsStrict ? DAG.getConstant(0, DL, WideIntVT) : DAG.getUNDEF(WideIntVT);
20223     V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideIntVT, Tmp, V,
20224                     DAG.getIntPtrConstant(0, DL));
20225     SDValue Res, Chain;
20226     if (IsStrict) {
20227       Res = DAG.getNode(ISD::STRICT_UINT_TO_FP, DL, {WideVT, MVT::Other},
20228                         {Op->getOperand(0), V});
20229       Chain = Res.getValue(1);
20230     } else {
20231       Res = DAG.getNode(ISD::UINT_TO_FP, DL, WideVT, V);
20232     }
20233 
20234     Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
20235                       DAG.getIntPtrConstant(0, DL));
20236 
20237     if (IsStrict)
20238       return DAG.getMergeValues({Res, Chain}, DL);
20239     return Res;
20240   }
20241 
20242   if (Subtarget.hasAVX() && VecIntVT == MVT::v4i32 &&
20243       Op->getSimpleValueType(0) == MVT::v4f64) {
20244     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i64, V);
20245     Constant *Bias = ConstantFP::get(
20246         *DAG.getContext(),
20247         APFloat(APFloat::IEEEdouble(), APInt(64, 0x4330000000000000ULL)));
20248     auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
20249     SDValue CPIdx = DAG.getConstantPool(Bias, PtrVT, Align(8));
20250     SDVTList Tys = DAG.getVTList(MVT::v4f64, MVT::Other);
20251     SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
20252     SDValue VBias = DAG.getMemIntrinsicNode(
20253         X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::f64,
20254         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Align(8),
20255         MachineMemOperand::MOLoad);
20256 
20257     SDValue Or = DAG.getNode(ISD::OR, DL, MVT::v4i64, ZExtIn,
20258                              DAG.getBitcast(MVT::v4i64, VBias));
20259     Or = DAG.getBitcast(MVT::v4f64, Or);
20260 
20261     if (IsStrict)
20262       return DAG.getNode(ISD::STRICT_FSUB, DL, {MVT::v4f64, MVT::Other},
20263                          {Op.getOperand(0), Or, VBias});
20264     return DAG.getNode(ISD::FSUB, DL, MVT::v4f64, Or, VBias);
20265   }
20266 
20267   // The algorithm is the following:
20268   // #ifdef __SSE4_1__
20269   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20270   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20271   //                                 (uint4) 0x53000000, 0xaa);
20272   // #else
20273   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20274   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
20275   // #endif
20276   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20277   //     return (float4) lo + fhi;
20278 
20279   bool Is128 = VecIntVT == MVT::v4i32;
20280   MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
20281   // If we convert to something else than the supported type, e.g., to v4f64,
20282   // abort early.
20283   if (VecFloatVT != Op->getSimpleValueType(0))
20284     return SDValue();
20285 
20286   // In the #idef/#else code, we have in common:
20287   // - The vector of constants:
20288   // -- 0x4b000000
20289   // -- 0x53000000
20290   // - A shift:
20291   // -- v >> 16
20292 
20293   // Create the splat vector for 0x4b000000.
20294   SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
20295   // Create the splat vector for 0x53000000.
20296   SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
20297 
20298   // Create the right shift.
20299   SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
20300   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
20301 
20302   SDValue Low, High;
20303   if (Subtarget.hasSSE41()) {
20304     MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
20305     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
20306     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
20307     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
20308     // Low will be bitcasted right away, so do not bother bitcasting back to its
20309     // original type.
20310     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
20311                       VecCstLowBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20312     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
20313     //                                 (uint4) 0x53000000, 0xaa);
20314     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
20315     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
20316     // High will be bitcasted right away, so do not bother bitcasting back to
20317     // its original type.
20318     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
20319                        VecCstHighBitcast, DAG.getTargetConstant(0xaa, DL, MVT::i8));
20320   } else {
20321     SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
20322     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
20323     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
20324     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
20325 
20326     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
20327     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
20328   }
20329 
20330   // Create the vector constant for (0x1.0p39f + 0x1.0p23f).
20331   SDValue VecCstFSub = DAG.getConstantFP(
20332       APFloat(APFloat::IEEEsingle(), APInt(32, 0x53000080)), DL, VecFloatVT);
20333 
20334   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
20335   // NOTE: By using fsub of a positive constant instead of fadd of a negative
20336   // constant, we avoid reassociation in MachineCombiner when unsafe-fp-math is
20337   // enabled. See PR24512.
20338   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
20339   // TODO: Are there any fast-math-flags to propagate here?
20340   //     (float4) lo;
20341   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
20342   //     return (float4) lo + fhi;
20343   if (IsStrict) {
20344     SDValue FHigh = DAG.getNode(ISD::STRICT_FSUB, DL, {VecFloatVT, MVT::Other},
20345                                 {Op.getOperand(0), HighBitcast, VecCstFSub});
20346     return DAG.getNode(ISD::STRICT_FADD, DL, {VecFloatVT, MVT::Other},
20347                        {FHigh.getValue(1), LowBitcast, FHigh});
20348   }
20349 
20350   SDValue FHigh =
20351       DAG.getNode(ISD::FSUB, DL, VecFloatVT, HighBitcast, VecCstFSub);
20352   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
20353 }
20354 
20355 static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
20356                                    const X86Subtarget &Subtarget) {
20357   unsigned OpNo = Op.getNode()->isStrictFPOpcode() ? 1 : 0;
20358   SDValue N0 = Op.getOperand(OpNo);
20359   MVT SrcVT = N0.getSimpleValueType();
20360   SDLoc dl(Op);
20361 
20362   switch (SrcVT.SimpleTy) {
20363   default:
20364     llvm_unreachable("Custom UINT_TO_FP is not supported!");
20365   case MVT::v2i32:
20366     return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
20367   case MVT::v4i32:
20368   case MVT::v8i32:
20369     return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
20370   case MVT::v2i64:
20371   case MVT::v4i64:
20372     return lowerINT_TO_FP_vXi64(Op, DAG, Subtarget);
20373   }
20374 }
20375 
20376 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
20377                                            SelectionDAG &DAG) const {
20378   bool IsStrict = Op->isStrictFPOpcode();
20379   unsigned OpNo = IsStrict ? 1 : 0;
20380   SDValue Src = Op.getOperand(OpNo);
20381   SDLoc dl(Op);
20382   auto PtrVT = getPointerTy(DAG.getDataLayout());
20383   MVT SrcVT = Src.getSimpleValueType();
20384   MVT DstVT = Op->getSimpleValueType(0);
20385   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20386 
20387   if (DstVT == MVT::f128)
20388     return SDValue();
20389 
20390   if (DstVT.isVector())
20391     return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
20392 
20393   if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
20394     return Extract;
20395 
20396   if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
20397       (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
20398     // Conversions from unsigned i32 to f32/f64 are legal,
20399     // using VCVTUSI2SS/SD.  Same for i64 in 64-bit mode.
20400     return Op;
20401   }
20402 
20403   // Promote i32 to i64 and use a signed conversion on 64-bit targets.
20404   if (SrcVT == MVT::i32 && Subtarget.is64Bit()) {
20405     Src = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Src);
20406     if (IsStrict)
20407       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {DstVT, MVT::Other},
20408                          {Chain, Src});
20409     return DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
20410   }
20411 
20412   if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
20413     return V;
20414 
20415   // The transform for i64->f64 isn't correct for 0 when rounding to negative
20416   // infinity. It produces -0.0, so disable under strictfp.
20417   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64 && !IsStrict)
20418     return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
20419   if (SrcVT == MVT::i32 && X86ScalarSSEf64 && DstVT != MVT::f80)
20420     return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
20421   if (Subtarget.is64Bit() && SrcVT == MVT::i64 &&
20422       (DstVT == MVT::f32 || DstVT == MVT::f64))
20423     return SDValue();
20424 
20425   // Make a 64-bit buffer, and use it to build an FILD.
20426   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64, 8);
20427   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
20428   Align SlotAlign(8);
20429   MachinePointerInfo MPI =
20430     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI);
20431   if (SrcVT == MVT::i32) {
20432     SDValue OffsetSlot =
20433         DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
20434     SDValue Store1 = DAG.getStore(Chain, dl, Src, StackSlot, MPI, SlotAlign);
20435     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
20436                                   OffsetSlot, MPI.getWithOffset(4), SlotAlign);
20437     std::pair<SDValue, SDValue> Tmp =
20438         BuildFILD(DstVT, MVT::i64, dl, Store2, StackSlot, MPI, SlotAlign, DAG);
20439     if (IsStrict)
20440       return DAG.getMergeValues({Tmp.first, Tmp.second}, dl);
20441 
20442     return Tmp.first;
20443   }
20444 
20445   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
20446   SDValue ValueToStore = Src;
20447   if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit()) {
20448     // Bitcasting to f64 here allows us to do a single 64-bit store from
20449     // an SSE register, avoiding the store forwarding penalty that would come
20450     // with two 32-bit stores.
20451     ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
20452   }
20453   SDValue Store =
20454       DAG.getStore(Chain, dl, ValueToStore, StackSlot, MPI, SlotAlign);
20455   // For i64 source, we need to add the appropriate power of 2 if the input
20456   // was negative. We must be careful to do the computation in x87 extended
20457   // precision, not in SSE.
20458   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20459   SDValue Ops[] = { Store, StackSlot };
20460   SDValue Fild =
20461       DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, MVT::i64, MPI,
20462                               SlotAlign, MachineMemOperand::MOLoad);
20463   Chain = Fild.getValue(1);
20464 
20465 
20466   // Check whether the sign bit is set.
20467   SDValue SignSet = DAG.getSetCC(
20468       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
20469       Op.getOperand(OpNo), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
20470 
20471   // Build a 64 bit pair (FF, 0) in the constant pool, with FF in the hi bits.
20472   APInt FF(64, 0x5F80000000000000ULL);
20473   SDValue FudgePtr = DAG.getConstantPool(
20474       ConstantInt::get(*DAG.getContext(), FF), PtrVT);
20475   Align CPAlignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlign();
20476 
20477   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
20478   SDValue Zero = DAG.getIntPtrConstant(0, dl);
20479   SDValue Four = DAG.getIntPtrConstant(4, dl);
20480   SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Four, Zero);
20481   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
20482 
20483   // Load the value out, extending it from f32 to f80.
20484   SDValue Fudge = DAG.getExtLoad(
20485       ISD::EXTLOAD, dl, MVT::f80, Chain, FudgePtr,
20486       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
20487       CPAlignment);
20488   Chain = Fudge.getValue(1);
20489   // Extend everything to 80 bits to force it to be done on x87.
20490   // TODO: Are there any fast-math-flags to propagate here?
20491   if (IsStrict) {
20492     SDValue Add = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::f80, MVT::Other},
20493                               {Chain, Fild, Fudge});
20494     // STRICT_FP_ROUND can't handle equal types.
20495     if (DstVT == MVT::f80)
20496       return Add;
20497     return DAG.getNode(ISD::STRICT_FP_ROUND, dl, {DstVT, MVT::Other},
20498                        {Add.getValue(1), Add, DAG.getIntPtrConstant(0, dl)});
20499   }
20500   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
20501   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
20502                      DAG.getIntPtrConstant(0, dl));
20503 }
20504 
20505 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
20506 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
20507 // just return an SDValue().
20508 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
20509 // to i16, i32 or i64, and we lower it to a legal sequence and return the
20510 // result.
20511 SDValue
20512 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
20513                                    bool IsSigned, SDValue &Chain) const {
20514   bool IsStrict = Op->isStrictFPOpcode();
20515   SDLoc DL(Op);
20516 
20517   EVT DstTy = Op.getValueType();
20518   SDValue Value = Op.getOperand(IsStrict ? 1 : 0);
20519   EVT TheVT = Value.getValueType();
20520   auto PtrVT = getPointerTy(DAG.getDataLayout());
20521 
20522   if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
20523     // f16 must be promoted before using the lowering in this routine.
20524     // fp128 does not use this lowering.
20525     return SDValue();
20526   }
20527 
20528   // If using FIST to compute an unsigned i64, we'll need some fixup
20529   // to handle values above the maximum signed i64.  A FIST is always
20530   // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
20531   bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
20532 
20533   // FIXME: This does not generate an invalid exception if the input does not
20534   // fit in i32. PR44019
20535   if (!IsSigned && DstTy != MVT::i64) {
20536     // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
20537     // The low 32 bits of the fist result will have the correct uint32 result.
20538     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
20539     DstTy = MVT::i64;
20540   }
20541 
20542   assert(DstTy.getSimpleVT() <= MVT::i64 &&
20543          DstTy.getSimpleVT() >= MVT::i16 &&
20544          "Unknown FP_TO_INT to lower!");
20545 
20546   // We lower FP->int64 into FISTP64 followed by a load from a temporary
20547   // stack slot.
20548   MachineFunction &MF = DAG.getMachineFunction();
20549   unsigned MemSize = DstTy.getStoreSize();
20550   int SSFI =
20551       MF.getFrameInfo().CreateStackObject(MemSize, Align(MemSize), false);
20552   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
20553 
20554   Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
20555 
20556   SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
20557 
20558   if (UnsignedFixup) {
20559     //
20560     // Conversion to unsigned i64 is implemented with a select,
20561     // depending on whether the source value fits in the range
20562     // of a signed i64.  Let Thresh be the FP equivalent of
20563     // 0x8000000000000000ULL.
20564     //
20565     //  Adjust = (Value >= Thresh) ? 0x80000000 : 0;
20566     //  FltOfs = (Value >= Thresh) ? 0x80000000 : 0;
20567     //  FistSrc = (Value - FltOfs);
20568     //  Fist-to-mem64 FistSrc
20569     //  Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
20570     //  to XOR'ing the high 32 bits with Adjust.
20571     //
20572     // Being a power of 2, Thresh is exactly representable in all FP formats.
20573     // For X87 we'd like to use the smallest FP type for this constant, but
20574     // for DAG type consistency we have to match the FP operand type.
20575 
20576     APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
20577     LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
20578     bool LosesInfo = false;
20579     if (TheVT == MVT::f64)
20580       // The rounding mode is irrelevant as the conversion should be exact.
20581       Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
20582                               &LosesInfo);
20583     else if (TheVT == MVT::f80)
20584       Status = Thresh.convert(APFloat::x87DoubleExtended(),
20585                               APFloat::rmNearestTiesToEven, &LosesInfo);
20586 
20587     assert(Status == APFloat::opOK && !LosesInfo &&
20588            "FP conversion should have been exact");
20589 
20590     SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
20591 
20592     EVT ResVT = getSetCCResultType(DAG.getDataLayout(),
20593                                    *DAG.getContext(), TheVT);
20594     SDValue Cmp;
20595     if (IsStrict) {
20596       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE, Chain,
20597                          /*IsSignaling*/ true);
20598       Chain = Cmp.getValue(1);
20599     } else {
20600       Cmp = DAG.getSetCC(DL, ResVT, Value, ThreshVal, ISD::SETGE);
20601     }
20602 
20603     // Our preferred lowering of
20604     //
20605     // (Value >= Thresh) ? 0x8000000000000000ULL : 0
20606     //
20607     // is
20608     //
20609     // (Value >= Thresh) << 63
20610     //
20611     // but since we can get here after LegalOperations, DAGCombine might do the
20612     // wrong thing if we create a select. So, directly create the preferred
20613     // version.
20614     SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Cmp);
20615     SDValue Const63 = DAG.getConstant(63, DL, MVT::i8);
20616     Adjust = DAG.getNode(ISD::SHL, DL, MVT::i64, Zext, Const63);
20617 
20618     SDValue FltOfs = DAG.getSelect(DL, TheVT, Cmp, ThreshVal,
20619                                    DAG.getConstantFP(0.0, DL, TheVT));
20620 
20621     if (IsStrict) {
20622       Value = DAG.getNode(ISD::STRICT_FSUB, DL, { TheVT, MVT::Other},
20623                           { Chain, Value, FltOfs });
20624       Chain = Value.getValue(1);
20625     } else
20626       Value = DAG.getNode(ISD::FSUB, DL, TheVT, Value, FltOfs);
20627   }
20628 
20629   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
20630 
20631   // FIXME This causes a redundant load/store if the SSE-class value is already
20632   // in memory, such as if it is on the callstack.
20633   if (isScalarFPTypeInSSEReg(TheVT)) {
20634     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
20635     Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
20636     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
20637     SDValue Ops[] = { Chain, StackSlot };
20638 
20639     unsigned FLDSize = TheVT.getStoreSize();
20640     assert(FLDSize <= MemSize && "Stack slot not big enough");
20641     MachineMemOperand *MMO = MF.getMachineMemOperand(
20642         MPI, MachineMemOperand::MOLoad, FLDSize, Align(FLDSize));
20643     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
20644     Chain = Value.getValue(1);
20645   }
20646 
20647   // Build the FP_TO_INT*_IN_MEM
20648   MachineMemOperand *MMO = MF.getMachineMemOperand(
20649       MPI, MachineMemOperand::MOStore, MemSize, Align(MemSize));
20650   SDValue Ops[] = { Chain, Value, StackSlot };
20651   SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
20652                                          DAG.getVTList(MVT::Other),
20653                                          Ops, DstTy, MMO);
20654 
20655   SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
20656   Chain = Res.getValue(1);
20657 
20658   // If we need an unsigned fixup, XOR the result with adjust.
20659   if (UnsignedFixup)
20660     Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
20661 
20662   return Res;
20663 }
20664 
20665 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
20666                               const X86Subtarget &Subtarget) {
20667   MVT VT = Op.getSimpleValueType();
20668   SDValue In = Op.getOperand(0);
20669   MVT InVT = In.getSimpleValueType();
20670   SDLoc dl(Op);
20671   unsigned Opc = Op.getOpcode();
20672 
20673   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
20674   assert((Opc == ISD::ANY_EXTEND || Opc == ISD::ZERO_EXTEND) &&
20675          "Unexpected extension opcode");
20676   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
20677          "Expected same number of elements");
20678   assert((VT.getVectorElementType() == MVT::i16 ||
20679           VT.getVectorElementType() == MVT::i32 ||
20680           VT.getVectorElementType() == MVT::i64) &&
20681          "Unexpected element type");
20682   assert((InVT.getVectorElementType() == MVT::i8 ||
20683           InVT.getVectorElementType() == MVT::i16 ||
20684           InVT.getVectorElementType() == MVT::i32) &&
20685          "Unexpected element type");
20686 
20687   unsigned ExtendInVecOpc = getOpcode_EXTEND_VECTOR_INREG(Opc);
20688 
20689   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
20690     assert(InVT == MVT::v32i8 && "Unexpected VT!");
20691     return splitVectorIntUnary(Op, DAG);
20692   }
20693 
20694   if (Subtarget.hasInt256())
20695     return Op;
20696 
20697   // Optimize vectors in AVX mode:
20698   //
20699   //   v8i16 -> v8i32
20700   //   Use vpmovzwd for 4 lower elements  v8i16 -> v4i32.
20701   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
20702   //   Concat upper and lower parts.
20703   //
20704   //   v4i32 -> v4i64
20705   //   Use vpmovzdq for 4 lower elements  v4i32 -> v2i64.
20706   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
20707   //   Concat upper and lower parts.
20708   //
20709   MVT HalfVT = VT.getHalfNumVectorElementsVT();
20710   SDValue OpLo = DAG.getNode(ExtendInVecOpc, dl, HalfVT, In);
20711 
20712   // Short-circuit if we can determine that each 128-bit half is the same value.
20713   // Otherwise, this is difficult to match and optimize.
20714   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
20715     if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
20716       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
20717 
20718   SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
20719   SDValue Undef = DAG.getUNDEF(InVT);
20720   bool NeedZero = Opc == ISD::ZERO_EXTEND;
20721   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
20722   OpHi = DAG.getBitcast(HalfVT, OpHi);
20723 
20724   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
20725 }
20726 
20727 // Helper to split and extend a v16i1 mask to v16i8 or v16i16.
20728 static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
20729                                    const SDLoc &dl, SelectionDAG &DAG) {
20730   assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.");
20731   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20732                            DAG.getIntPtrConstant(0, dl));
20733   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
20734                            DAG.getIntPtrConstant(8, dl));
20735   Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
20736   Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
20737   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
20738   return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
20739 }
20740 
20741 static  SDValue LowerZERO_EXTEND_Mask(SDValue Op,
20742                                       const X86Subtarget &Subtarget,
20743                                       SelectionDAG &DAG) {
20744   MVT VT = Op->getSimpleValueType(0);
20745   SDValue In = Op->getOperand(0);
20746   MVT InVT = In.getSimpleValueType();
20747   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
20748   SDLoc DL(Op);
20749   unsigned NumElts = VT.getVectorNumElements();
20750 
20751   // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
20752   // avoids a constant pool load.
20753   if (VT.getVectorElementType() != MVT::i8) {
20754     SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
20755     return DAG.getNode(ISD::SRL, DL, VT, Extend,
20756                        DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
20757   }
20758 
20759   // Extend VT if BWI is not supported.
20760   MVT ExtVT = VT;
20761   if (!Subtarget.hasBWI()) {
20762     // If v16i32 is to be avoided, we'll need to split and concatenate.
20763     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20764       return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
20765 
20766     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20767   }
20768 
20769   // Widen to 512-bits if VLX is not supported.
20770   MVT WideVT = ExtVT;
20771   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20772     NumElts *= 512 / ExtVT.getSizeInBits();
20773     InVT = MVT::getVectorVT(MVT::i1, NumElts);
20774     In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
20775                      In, DAG.getIntPtrConstant(0, DL));
20776     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
20777                               NumElts);
20778   }
20779 
20780   SDValue One = DAG.getConstant(1, DL, WideVT);
20781   SDValue Zero = DAG.getConstant(0, DL, WideVT);
20782 
20783   SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
20784 
20785   // Truncate if we had to extend above.
20786   if (VT != ExtVT) {
20787     WideVT = MVT::getVectorVT(MVT::i8, NumElts);
20788     SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
20789   }
20790 
20791   // Extract back to 128/256-bit if we widened.
20792   if (WideVT != VT)
20793     SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
20794                               DAG.getIntPtrConstant(0, DL));
20795 
20796   return SelectedVal;
20797 }
20798 
20799 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20800                                 SelectionDAG &DAG) {
20801   SDValue In = Op.getOperand(0);
20802   MVT SVT = In.getSimpleValueType();
20803 
20804   if (SVT.getVectorElementType() == MVT::i1)
20805     return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
20806 
20807   assert(Subtarget.hasAVX() && "Expected AVX support");
20808   return LowerAVXExtend(Op, DAG, Subtarget);
20809 }
20810 
20811 /// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
20812 /// It makes use of the fact that vectors with enough leading sign/zero bits
20813 /// prevent the PACKSS/PACKUS from saturating the results.
20814 /// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
20815 /// within each 128-bit lane.
20816 static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
20817                                       const SDLoc &DL, SelectionDAG &DAG,
20818                                       const X86Subtarget &Subtarget) {
20819   assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
20820          "Unexpected PACK opcode");
20821   assert(DstVT.isVector() && "VT not a vector?");
20822 
20823   // Requires SSE2 for PACKSS (SSE41 PACKUSDW is handled below).
20824   if (!Subtarget.hasSSE2())
20825     return SDValue();
20826 
20827   EVT SrcVT = In.getValueType();
20828 
20829   // No truncation required, we might get here due to recursive calls.
20830   if (SrcVT == DstVT)
20831     return In;
20832 
20833   // We only support vector truncation to 64bits or greater from a
20834   // 128bits or greater source.
20835   unsigned DstSizeInBits = DstVT.getSizeInBits();
20836   unsigned SrcSizeInBits = SrcVT.getSizeInBits();
20837   if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
20838     return SDValue();
20839 
20840   unsigned NumElems = SrcVT.getVectorNumElements();
20841   if (!isPowerOf2_32(NumElems))
20842     return SDValue();
20843 
20844   LLVMContext &Ctx = *DAG.getContext();
20845   assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation");
20846   assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation");
20847 
20848   EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
20849 
20850   // Pack to the largest type possible:
20851   // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
20852   EVT InVT = MVT::i16, OutVT = MVT::i8;
20853   if (SrcVT.getScalarSizeInBits() > 16 &&
20854       (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
20855     InVT = MVT::i32;
20856     OutVT = MVT::i16;
20857   }
20858 
20859   // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
20860   if (SrcVT.is128BitVector()) {
20861     InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
20862     OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
20863     In = DAG.getBitcast(InVT, In);
20864     SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, DAG.getUNDEF(InVT));
20865     Res = extractSubVector(Res, 0, DAG, DL, 64);
20866     return DAG.getBitcast(DstVT, Res);
20867   }
20868 
20869   // Split lower/upper subvectors.
20870   SDValue Lo, Hi;
20871   std::tie(Lo, Hi) = splitVector(In, DAG, DL);
20872 
20873   unsigned SubSizeInBits = SrcSizeInBits / 2;
20874   InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
20875   OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
20876 
20877   // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
20878   if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
20879     Lo = DAG.getBitcast(InVT, Lo);
20880     Hi = DAG.getBitcast(InVT, Hi);
20881     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20882     return DAG.getBitcast(DstVT, Res);
20883   }
20884 
20885   // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
20886   // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
20887   if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
20888     Lo = DAG.getBitcast(InVT, Lo);
20889     Hi = DAG.getBitcast(InVT, Hi);
20890     SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
20891 
20892     // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
20893     // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
20894     // Scale shuffle mask to avoid bitcasts and help ComputeNumSignBits.
20895     SmallVector<int, 64> Mask;
20896     int Scale = 64 / OutVT.getScalarSizeInBits();
20897     narrowShuffleMaskElts(Scale, { 0, 2, 1, 3 }, Mask);
20898     Res = DAG.getVectorShuffle(OutVT, DL, Res, Res, Mask);
20899 
20900     if (DstVT.is256BitVector())
20901       return DAG.getBitcast(DstVT, Res);
20902 
20903     // If 512bit -> 128bit truncate another stage.
20904     EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
20905     Res = DAG.getBitcast(PackedVT, Res);
20906     return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20907   }
20908 
20909   // Recursively pack lower/upper subvectors, concat result and pack again.
20910   assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater");
20911   EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems / 2);
20912   Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
20913   Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
20914 
20915   PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
20916   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
20917   return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
20918 }
20919 
20920 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
20921                                   const X86Subtarget &Subtarget) {
20922 
20923   SDLoc DL(Op);
20924   MVT VT = Op.getSimpleValueType();
20925   SDValue In = Op.getOperand(0);
20926   MVT InVT = In.getSimpleValueType();
20927 
20928   assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.");
20929 
20930   // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
20931   unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
20932   if (InVT.getScalarSizeInBits() <= 16) {
20933     if (Subtarget.hasBWI()) {
20934       // legal, will go to VPMOVB2M, VPMOVW2M
20935       if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20936         // We need to shift to get the lsb into sign position.
20937         // Shift packed bytes not supported natively, bitcast to word
20938         MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
20939         In = DAG.getNode(ISD::SHL, DL, ExtVT,
20940                          DAG.getBitcast(ExtVT, In),
20941                          DAG.getConstant(ShiftInx, DL, ExtVT));
20942         In = DAG.getBitcast(InVT, In);
20943       }
20944       return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
20945                           In, ISD::SETGT);
20946     }
20947     // Use TESTD/Q, extended vector to packed dword/qword.
20948     assert((InVT.is256BitVector() || InVT.is128BitVector()) &&
20949            "Unexpected vector type.");
20950     unsigned NumElts = InVT.getVectorNumElements();
20951     assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements");
20952     // We need to change to a wider element type that we have support for.
20953     // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
20954     // For 16 element vectors we extend to v16i32 unless we are explicitly
20955     // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
20956     // we need to split into two 8 element vectors which we can extend to v8i32,
20957     // truncate and concat the results. There's an additional complication if
20958     // the original type is v16i8. In that case we can't split the v16i8
20959     // directly, so we need to shuffle high elements to low and use
20960     // sign_extend_vector_inreg.
20961     if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
20962       SDValue Lo, Hi;
20963       if (InVT == MVT::v16i8) {
20964         Lo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, In);
20965         Hi = DAG.getVectorShuffle(
20966             InVT, DL, In, In,
20967             {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
20968         Hi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, MVT::v8i32, Hi);
20969       } else {
20970         assert(InVT == MVT::v16i16 && "Unexpected VT!");
20971         Lo = extract128BitVector(In, 0, DAG, DL);
20972         Hi = extract128BitVector(In, 8, DAG, DL);
20973       }
20974       // We're split now, just emit two truncates and a concat. The two
20975       // truncates will trigger legalization to come back to this function.
20976       Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
20977       Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
20978       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20979     }
20980     // We either have 8 elements or we're allowed to use 512-bit vectors.
20981     // If we have VLX, we want to use the narrowest vector that can get the
20982     // job done so we use vXi32.
20983     MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
20984     MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
20985     In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
20986     InVT = ExtVT;
20987     ShiftInx = InVT.getScalarSizeInBits() - 1;
20988   }
20989 
20990   if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
20991     // We need to shift to get the lsb into sign position.
20992     In = DAG.getNode(ISD::SHL, DL, InVT, In,
20993                      DAG.getConstant(ShiftInx, DL, InVT));
20994   }
20995   // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
20996   if (Subtarget.hasDQI())
20997     return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
20998   return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
20999 }
21000 
21001 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
21002   SDLoc DL(Op);
21003   MVT VT = Op.getSimpleValueType();
21004   SDValue In = Op.getOperand(0);
21005   MVT InVT = In.getSimpleValueType();
21006   unsigned InNumEltBits = InVT.getScalarSizeInBits();
21007 
21008   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
21009          "Invalid TRUNCATE operation");
21010 
21011   // If we're called by the type legalizer, handle a few cases.
21012   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21013   if (!TLI.isTypeLegal(InVT)) {
21014     if ((InVT == MVT::v8i64 || InVT == MVT::v16i32 || InVT == MVT::v16i64) &&
21015         VT.is128BitVector()) {
21016       assert((InVT == MVT::v16i64 || Subtarget.hasVLX()) &&
21017              "Unexpected subtarget!");
21018       // The default behavior is to truncate one step, concatenate, and then
21019       // truncate the remainder. We'd rather produce two 64-bit results and
21020       // concatenate those.
21021       SDValue Lo, Hi;
21022       std::tie(Lo, Hi) = DAG.SplitVector(In, DL);
21023 
21024       EVT LoVT, HiVT;
21025       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
21026 
21027       Lo = DAG.getNode(ISD::TRUNCATE, DL, LoVT, Lo);
21028       Hi = DAG.getNode(ISD::TRUNCATE, DL, HiVT, Hi);
21029       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
21030     }
21031 
21032     // Otherwise let default legalization handle it.
21033     return SDValue();
21034   }
21035 
21036   if (VT.getVectorElementType() == MVT::i1)
21037     return LowerTruncateVecI1(Op, DAG, Subtarget);
21038 
21039   // vpmovqb/w/d, vpmovdb/w, vpmovwb
21040   if (Subtarget.hasAVX512()) {
21041     if (InVT == MVT::v32i16 && !Subtarget.hasBWI()) {
21042       assert(VT == MVT::v32i8 && "Unexpected VT!");
21043       return splitVectorIntUnary(Op, DAG);
21044     }
21045 
21046     // word to byte only under BWI. Otherwise we have to promoted to v16i32
21047     // and then truncate that. But we should only do that if we haven't been
21048     // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
21049     // handled by isel patterns.
21050     if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
21051         Subtarget.canExtendTo512DQ())
21052       return Op;
21053   }
21054 
21055   unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
21056   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
21057 
21058   // Truncate with PACKUS if we are truncating a vector with leading zero bits
21059   // that extend all the way to the packed/truncated value.
21060   // Pre-SSE41 we can only use PACKUSWB.
21061   KnownBits Known = DAG.computeKnownBits(In);
21062   if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
21063     if (SDValue V =
21064             truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
21065       return V;
21066 
21067   // Truncate with PACKSS if we are truncating a vector with sign-bits that
21068   // extend all the way to the packed/truncated value.
21069   if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
21070     if (SDValue V =
21071             truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
21072       return V;
21073 
21074   // Handle truncation of V256 to V128 using shuffles.
21075   assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!");
21076 
21077   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
21078     In = DAG.getBitcast(MVT::v8i32, In);
21079 
21080     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
21081     if (Subtarget.hasInt256()) {
21082       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
21083       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
21084       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
21085                          DAG.getIntPtrConstant(0, DL));
21086     }
21087 
21088     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
21089                                DAG.getIntPtrConstant(0, DL));
21090     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
21091                                DAG.getIntPtrConstant(4, DL));
21092     static const int ShufMask[] = {0, 2, 4, 6};
21093     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
21094   }
21095 
21096   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
21097     In = DAG.getBitcast(MVT::v32i8, In);
21098 
21099     // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
21100     if (Subtarget.hasInt256()) {
21101       // The PSHUFB mask:
21102       static const int ShufMask1[] = { 0,  1,  4,  5,  8,  9, 12, 13,
21103                                       -1, -1, -1, -1, -1, -1, -1, -1,
21104                                       16, 17, 20, 21, 24, 25, 28, 29,
21105                                       -1, -1, -1, -1, -1, -1, -1, -1 };
21106       In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
21107       In = DAG.getBitcast(MVT::v4i64, In);
21108 
21109       static const int ShufMask2[] = {0, 2, -1, -1};
21110       In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
21111       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16,
21112                          DAG.getBitcast(MVT::v16i16, In),
21113                          DAG.getIntPtrConstant(0, DL));
21114     }
21115 
21116     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, In,
21117                                DAG.getIntPtrConstant(0, DL));
21118     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v16i8, In,
21119                                DAG.getIntPtrConstant(16, DL));
21120 
21121     // The PSHUFB mask:
21122     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
21123                                    -1, -1, -1, -1, -1, -1, -1, -1};
21124 
21125     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
21126     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
21127 
21128     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
21129     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
21130 
21131     // The MOVLHPS Mask:
21132     static const int ShufMask2[] = {0, 1, 4, 5};
21133     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
21134     return DAG.getBitcast(MVT::v8i16, res);
21135   }
21136 
21137   if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
21138     // Use an AND to zero uppper bits for PACKUS.
21139     In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
21140 
21141     SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
21142                                DAG.getIntPtrConstant(0, DL));
21143     SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
21144                                DAG.getIntPtrConstant(8, DL));
21145     return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
21146   }
21147 
21148   llvm_unreachable("All 256->128 cases should have been handled above!");
21149 }
21150 
21151 SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
21152   bool IsStrict = Op->isStrictFPOpcode();
21153   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
21154                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
21155   MVT VT = Op->getSimpleValueType(0);
21156   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21157   MVT SrcVT = Src.getSimpleValueType();
21158   SDLoc dl(Op);
21159 
21160   if (VT.isVector()) {
21161     if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
21162       MVT ResVT = MVT::v4i32;
21163       MVT TruncVT = MVT::v4i1;
21164       unsigned Opc;
21165       if (IsStrict)
21166         Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
21167       else
21168         Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21169 
21170       if (!IsSigned && !Subtarget.hasVLX()) {
21171         assert(Subtarget.useAVX512Regs() && "Unexpected features!");
21172         // Widen to 512-bits.
21173         ResVT = MVT::v8i32;
21174         TruncVT = MVT::v8i1;
21175         Opc = Op.getOpcode();
21176         // Need to concat with zero vector for strict fp to avoid spurious
21177         // exceptions.
21178         // TODO: Should we just do this for non-strict as well?
21179         SDValue Tmp = IsStrict ? DAG.getConstantFP(0.0, dl, MVT::v8f64)
21180                                : DAG.getUNDEF(MVT::v8f64);
21181         Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64, Tmp, Src,
21182                           DAG.getIntPtrConstant(0, dl));
21183       }
21184       SDValue Res, Chain;
21185       if (IsStrict) {
21186         Res =
21187             DAG.getNode(Opc, dl, {ResVT, MVT::Other}, {Op->getOperand(0), Src});
21188         Chain = Res.getValue(1);
21189       } else {
21190         Res = DAG.getNode(Opc, dl, ResVT, Src);
21191       }
21192 
21193       Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
21194       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
21195                         DAG.getIntPtrConstant(0, dl));
21196       if (IsStrict)
21197         return DAG.getMergeValues({Res, Chain}, dl);
21198       return Res;
21199     }
21200 
21201     // v8f64->v8i32 is legal, but we need v8i32 to be custom for v8f32.
21202     if (VT == MVT::v8i32 && SrcVT == MVT::v8f64) {
21203       assert(!IsSigned && "Expected unsigned conversion!");
21204       assert(Subtarget.useAVX512Regs() && "Requires avx512f");
21205       return Op;
21206     }
21207 
21208     // Widen vXi32 fp_to_uint with avx512f to 512-bit source.
21209     if ((VT == MVT::v4i32 || VT == MVT::v8i32) &&
21210         (SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v8f32)) {
21211       assert(!IsSigned && "Expected unsigned conversion!");
21212       assert(Subtarget.useAVX512Regs() && !Subtarget.hasVLX() &&
21213              "Unexpected features!");
21214       MVT WideVT = SrcVT == MVT::v4f64 ? MVT::v8f64 : MVT::v16f32;
21215       MVT ResVT = SrcVT == MVT::v4f64 ? MVT::v8i32 : MVT::v16i32;
21216       // Need to concat with zero vector for strict fp to avoid spurious
21217       // exceptions.
21218       // TODO: Should we just do this for non-strict as well?
21219       SDValue Tmp =
21220           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21221       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21222                         DAG.getIntPtrConstant(0, dl));
21223 
21224       SDValue Res, Chain;
21225       if (IsStrict) {
21226         Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, dl, {ResVT, MVT::Other},
21227                           {Op->getOperand(0), Src});
21228         Chain = Res.getValue(1);
21229       } else {
21230         Res = DAG.getNode(ISD::FP_TO_UINT, dl, ResVT, Src);
21231       }
21232 
21233       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21234                         DAG.getIntPtrConstant(0, dl));
21235 
21236       if (IsStrict)
21237         return DAG.getMergeValues({Res, Chain}, dl);
21238       return Res;
21239     }
21240 
21241     // Widen vXi64 fp_to_uint/fp_to_sint with avx512dq to 512-bit source.
21242     if ((VT == MVT::v2i64 || VT == MVT::v4i64) &&
21243         (SrcVT == MVT::v2f64 || SrcVT == MVT::v4f64 || SrcVT == MVT::v4f32)) {
21244       assert(Subtarget.useAVX512Regs() && Subtarget.hasDQI() &&
21245              !Subtarget.hasVLX() && "Unexpected features!");
21246       MVT WideVT = SrcVT == MVT::v4f32 ? MVT::v8f32 : MVT::v8f64;
21247       // Need to concat with zero vector for strict fp to avoid spurious
21248       // exceptions.
21249       // TODO: Should we just do this for non-strict as well?
21250       SDValue Tmp =
21251           IsStrict ? DAG.getConstantFP(0.0, dl, WideVT) : DAG.getUNDEF(WideVT);
21252       Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVT, Tmp, Src,
21253                         DAG.getIntPtrConstant(0, dl));
21254 
21255       SDValue Res, Chain;
21256       if (IsStrict) {
21257         Res = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
21258                           {Op->getOperand(0), Src});
21259         Chain = Res.getValue(1);
21260       } else {
21261         Res = DAG.getNode(Op.getOpcode(), dl, MVT::v8i64, Src);
21262       }
21263 
21264       Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
21265                         DAG.getIntPtrConstant(0, dl));
21266 
21267       if (IsStrict)
21268         return DAG.getMergeValues({Res, Chain}, dl);
21269       return Res;
21270     }
21271 
21272     if (VT == MVT::v2i64 && SrcVT  == MVT::v2f32) {
21273       if (!Subtarget.hasVLX()) {
21274         // Non-strict nodes without VLX can we widened to v4f32->v4i64 by type
21275         // legalizer and then widened again by vector op legalization.
21276         if (!IsStrict)
21277           return SDValue();
21278 
21279         SDValue Zero = DAG.getConstantFP(0.0, dl, MVT::v2f32);
21280         SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8f32,
21281                                   {Src, Zero, Zero, Zero});
21282         Tmp = DAG.getNode(Op.getOpcode(), dl, {MVT::v8i64, MVT::Other},
21283                           {Op->getOperand(0), Tmp});
21284         SDValue Chain = Tmp.getValue(1);
21285         Tmp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Tmp,
21286                           DAG.getIntPtrConstant(0, dl));
21287         if (IsStrict)
21288           return DAG.getMergeValues({Tmp, Chain}, dl);
21289         return Tmp;
21290       }
21291 
21292       assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL");
21293       SDValue Tmp = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
21294                                 DAG.getUNDEF(MVT::v2f32));
21295       if (IsStrict) {
21296         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI
21297                                 : X86ISD::STRICT_CVTTP2UI;
21298         return DAG.getNode(Opc, dl, {VT, MVT::Other}, {Op->getOperand(0), Tmp});
21299       }
21300       unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
21301       return DAG.getNode(Opc, dl, VT, Tmp);
21302     }
21303 
21304     return SDValue();
21305   }
21306 
21307   assert(!VT.isVector());
21308 
21309   bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
21310 
21311   if (!IsSigned && UseSSEReg) {
21312     // Conversions from f32/f64 with AVX512 should be legal.
21313     if (Subtarget.hasAVX512())
21314       return Op;
21315 
21316     // Use default expansion for i64.
21317     if (VT == MVT::i64)
21318       return SDValue();
21319 
21320     assert(VT == MVT::i32 && "Unexpected VT!");
21321 
21322     // Promote i32 to i64 and use a signed operation on 64-bit targets.
21323     // FIXME: This does not generate an invalid exception if the input does not
21324     // fit in i32. PR44019
21325     if (Subtarget.is64Bit()) {
21326       SDValue Res, Chain;
21327       if (IsStrict) {
21328         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i64, MVT::Other},
21329                           { Op.getOperand(0), Src });
21330         Chain = Res.getValue(1);
21331       } else
21332         Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i64, Src);
21333 
21334       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21335       if (IsStrict)
21336         return DAG.getMergeValues({ Res, Chain }, dl);
21337       return Res;
21338     }
21339 
21340     // Use default expansion for SSE1/2 targets without SSE3. With SSE3 we can
21341     // use fisttp which will be handled later.
21342     if (!Subtarget.hasSSE3())
21343       return SDValue();
21344   }
21345 
21346   // Promote i16 to i32 if we can use a SSE operation or the type is f128.
21347   // FIXME: This does not generate an invalid exception if the input does not
21348   // fit in i16. PR44019
21349   if (VT == MVT::i16 && (UseSSEReg || SrcVT == MVT::f128)) {
21350     assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!");
21351     SDValue Res, Chain;
21352     if (IsStrict) {
21353       Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { MVT::i32, MVT::Other},
21354                         { Op.getOperand(0), Src });
21355       Chain = Res.getValue(1);
21356     } else
21357       Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
21358 
21359     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
21360     if (IsStrict)
21361       return DAG.getMergeValues({ Res, Chain }, dl);
21362     return Res;
21363   }
21364 
21365   // If this is a FP_TO_SINT using SSEReg we're done.
21366   if (UseSSEReg && IsSigned)
21367     return Op;
21368 
21369   // fp128 needs to use a libcall.
21370   if (SrcVT == MVT::f128) {
21371     RTLIB::Libcall LC;
21372     if (IsSigned)
21373       LC = RTLIB::getFPTOSINT(SrcVT, VT);
21374     else
21375       LC = RTLIB::getFPTOUINT(SrcVT, VT);
21376 
21377     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
21378     MakeLibCallOptions CallOptions;
21379     std::pair<SDValue, SDValue> Tmp = makeLibCall(DAG, LC, VT, Src, CallOptions,
21380                                                   SDLoc(Op), Chain);
21381 
21382     if (IsStrict)
21383       return DAG.getMergeValues({ Tmp.first, Tmp.second }, dl);
21384 
21385     return Tmp.first;
21386   }
21387 
21388   // Fall back to X87.
21389   SDValue Chain;
21390   if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned, Chain)) {
21391     if (IsStrict)
21392       return DAG.getMergeValues({V, Chain}, dl);
21393     return V;
21394   }
21395 
21396   llvm_unreachable("Expected FP_TO_INTHelper to handle all remaining cases.");
21397 }
21398 
21399 SDValue X86TargetLowering::LowerLRINT_LLRINT(SDValue Op,
21400                                              SelectionDAG &DAG) const {
21401   SDValue Src = Op.getOperand(0);
21402   MVT SrcVT = Src.getSimpleValueType();
21403 
21404   // If the source is in an SSE register, the node is Legal.
21405   if (isScalarFPTypeInSSEReg(SrcVT))
21406     return Op;
21407 
21408   return LRINT_LLRINTHelper(Op.getNode(), DAG);
21409 }
21410 
21411 SDValue X86TargetLowering::LRINT_LLRINTHelper(SDNode *N,
21412                                               SelectionDAG &DAG) const {
21413   EVT DstVT = N->getValueType(0);
21414   SDValue Src = N->getOperand(0);
21415   EVT SrcVT = Src.getValueType();
21416 
21417   if (SrcVT != MVT::f32 && SrcVT != MVT::f64 && SrcVT != MVT::f80) {
21418     // f16 must be promoted before using the lowering in this routine.
21419     // fp128 does not use this lowering.
21420     return SDValue();
21421   }
21422 
21423   SDLoc DL(N);
21424   SDValue Chain = DAG.getEntryNode();
21425 
21426   bool UseSSE = isScalarFPTypeInSSEReg(SrcVT);
21427 
21428   // If we're converting from SSE, the stack slot needs to hold both types.
21429   // Otherwise it only needs to hold the DstVT.
21430   EVT OtherVT = UseSSE ? SrcVT : DstVT;
21431   SDValue StackPtr = DAG.CreateStackTemporary(DstVT, OtherVT);
21432   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
21433   MachinePointerInfo MPI =
21434       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
21435 
21436   if (UseSSE) {
21437     assert(DstVT == MVT::i64 && "Invalid LRINT/LLRINT to lower!");
21438     Chain = DAG.getStore(Chain, DL, Src, StackPtr, MPI);
21439     SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
21440     SDValue Ops[] = { Chain, StackPtr };
21441 
21442     Src = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, SrcVT, MPI,
21443                                   /*Align*/ None, MachineMemOperand::MOLoad);
21444     Chain = Src.getValue(1);
21445   }
21446 
21447   SDValue StoreOps[] = { Chain, Src, StackPtr };
21448   Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, DL, DAG.getVTList(MVT::Other),
21449                                   StoreOps, DstVT, MPI, /*Align*/ None,
21450                                   MachineMemOperand::MOStore);
21451 
21452   return DAG.getLoad(DstVT, DL, Chain, StackPtr, MPI);
21453 }
21454 
21455 SDValue
21456 X86TargetLowering::LowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) const {
21457   // This is based on the TargetLowering::expandFP_TO_INT_SAT implementation,
21458   // but making use of X86 specifics to produce better instruction sequences.
21459   SDNode *Node = Op.getNode();
21460   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
21461   unsigned FpToIntOpcode = IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT;
21462   SDLoc dl(SDValue(Node, 0));
21463   SDValue Src = Node->getOperand(0);
21464 
21465   // There are three types involved here: SrcVT is the source floating point
21466   // type, DstVT is the type of the result, and TmpVT is the result of the
21467   // intermediate FP_TO_*INT operation we'll use (which may be a promotion of
21468   // DstVT).
21469   EVT SrcVT = Src.getValueType();
21470   EVT DstVT = Node->getValueType(0);
21471   EVT TmpVT = DstVT;
21472 
21473   // This code is only for floats and doubles. Fall back to generic code for
21474   // anything else.
21475   if (!isScalarFPTypeInSSEReg(SrcVT))
21476     return SDValue();
21477 
21478   unsigned SatWidth = Node->getConstantOperandVal(1);
21479   unsigned DstWidth = DstVT.getScalarSizeInBits();
21480   unsigned TmpWidth = TmpVT.getScalarSizeInBits();
21481   assert(SatWidth <= DstWidth && SatWidth <= TmpWidth &&
21482          "Expected saturation width smaller than result width");
21483 
21484   // Promote result of FP_TO_*INT to at least 32 bits.
21485   if (TmpWidth < 32) {
21486     TmpVT = MVT::i32;
21487     TmpWidth = 32;
21488   }
21489 
21490   // Promote conversions to unsigned 32-bit to 64-bit, because it will allow
21491   // us to use a native signed conversion instead.
21492   if (SatWidth == 32 && !IsSigned && Subtarget.is64Bit()) {
21493     TmpVT = MVT::i64;
21494     TmpWidth = 64;
21495   }
21496 
21497   // If the saturation width is smaller than the size of the temporary result,
21498   // we can always use signed conversion, which is native.
21499   if (SatWidth < TmpWidth)
21500     FpToIntOpcode = ISD::FP_TO_SINT;
21501 
21502   // Determine minimum and maximum integer values and their corresponding
21503   // floating-point values.
21504   APInt MinInt, MaxInt;
21505   if (IsSigned) {
21506     MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
21507     MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
21508   } else {
21509     MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
21510     MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
21511   }
21512 
21513   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
21514   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
21515 
21516   APFloat::opStatus MinStatus = MinFloat.convertFromAPInt(
21517     MinInt, IsSigned, APFloat::rmTowardZero);
21518   APFloat::opStatus MaxStatus = MaxFloat.convertFromAPInt(
21519     MaxInt, IsSigned, APFloat::rmTowardZero);
21520   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact)
21521                           && !(MaxStatus & APFloat::opStatus::opInexact);
21522 
21523   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
21524   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
21525 
21526   // If the integer bounds are exactly representable as floats, emit a
21527   // min+max+fptoi sequence. Otherwise use comparisons and selects.
21528   if (AreExactFloatBounds) {
21529     if (DstVT != TmpVT) {
21530       // Clamp by MinFloat from below. If Src is NaN, propagate NaN.
21531       SDValue MinClamped = DAG.getNode(
21532         X86ISD::FMAX, dl, SrcVT, MinFloatNode, Src);
21533       // Clamp by MaxFloat from above. If Src is NaN, propagate NaN.
21534       SDValue BothClamped = DAG.getNode(
21535         X86ISD::FMIN, dl, SrcVT, MaxFloatNode, MinClamped);
21536       // Convert clamped value to integer.
21537       SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, BothClamped);
21538 
21539       // NaN will become INDVAL, with the top bit set and the rest zero.
21540       // Truncation will discard the top bit, resulting in zero.
21541       return DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21542     }
21543 
21544     // Clamp by MinFloat from below. If Src is NaN, the result is MinFloat.
21545     SDValue MinClamped = DAG.getNode(
21546       X86ISD::FMAX, dl, SrcVT, Src, MinFloatNode);
21547     // Clamp by MaxFloat from above. NaN cannot occur.
21548     SDValue BothClamped = DAG.getNode(
21549       X86ISD::FMINC, dl, SrcVT, MinClamped, MaxFloatNode);
21550     // Convert clamped value to integer.
21551     SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, DstVT, BothClamped);
21552 
21553     if (!IsSigned) {
21554       // In the unsigned case we're done, because we mapped NaN to MinFloat,
21555       // which is zero.
21556       return FpToInt;
21557     }
21558 
21559     // Otherwise, select zero if Src is NaN.
21560     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21561     return DAG.getSelectCC(
21562       dl, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
21563   }
21564 
21565   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
21566   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
21567 
21568   // Result of direct conversion, which may be selected away.
21569   SDValue FpToInt = DAG.getNode(FpToIntOpcode, dl, TmpVT, Src);
21570 
21571   if (DstVT != TmpVT) {
21572     // NaN will become INDVAL, with the top bit set and the rest zero.
21573     // Truncation will discard the top bit, resulting in zero.
21574     FpToInt = DAG.getNode(ISD::TRUNCATE, dl, DstVT, FpToInt);
21575   }
21576 
21577   SDValue Select = FpToInt;
21578   // For signed conversions where we saturate to the same size as the
21579   // result type of the fptoi instructions, INDVAL coincides with integer
21580   // minimum, so we don't need to explicitly check it.
21581   if (!IsSigned || SatWidth != TmpVT.getScalarSizeInBits()) {
21582     // If Src ULT MinFloat, select MinInt. In particular, this also selects
21583     // MinInt if Src is NaN.
21584     Select = DAG.getSelectCC(
21585       dl, Src, MinFloatNode, MinIntNode, Select, ISD::CondCode::SETULT);
21586   }
21587 
21588   // If Src OGT MaxFloat, select MaxInt.
21589   Select = DAG.getSelectCC(
21590     dl, Src, MaxFloatNode, MaxIntNode, Select, ISD::CondCode::SETOGT);
21591 
21592   // In the unsigned case we are done, because we mapped NaN to MinInt, which
21593   // is already zero. The promoted case was already handled above.
21594   if (!IsSigned || DstVT != TmpVT) {
21595     return Select;
21596   }
21597 
21598   // Otherwise, select 0 if Src is NaN.
21599   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
21600   return DAG.getSelectCC(
21601     dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
21602 }
21603 
21604 SDValue X86TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
21605   bool IsStrict = Op->isStrictFPOpcode();
21606 
21607   SDLoc DL(Op);
21608   MVT VT = Op.getSimpleValueType();
21609   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21610   MVT SVT = In.getSimpleValueType();
21611 
21612   if (VT == MVT::f128)
21613     return SDValue();
21614 
21615   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
21616 
21617   SDValue Res =
21618       DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32, In, DAG.getUNDEF(SVT));
21619   if (IsStrict)
21620     return DAG.getNode(X86ISD::STRICT_VFPEXT, DL, {VT, MVT::Other},
21621                        {Op->getOperand(0), Res});
21622   return DAG.getNode(X86ISD::VFPEXT, DL, VT, Res);
21623 }
21624 
21625 SDValue X86TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
21626   bool IsStrict = Op->isStrictFPOpcode();
21627   SDValue In = Op.getOperand(IsStrict ? 1 : 0);
21628   // It's legal except when f128 is involved
21629   if (In.getSimpleValueType() != MVT::f128)
21630     return Op;
21631 
21632   return SDValue();
21633 }
21634 
21635 static SDValue LowerFP16_TO_FP(SDValue Op, SelectionDAG &DAG) {
21636   bool IsStrict = Op->isStrictFPOpcode();
21637   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21638   assert(Src.getValueType() == MVT::i16 && Op.getValueType() == MVT::f32 &&
21639          "Unexpected VT!");
21640 
21641   SDLoc dl(Op);
21642   SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16,
21643                             DAG.getConstant(0, dl, MVT::v8i16), Src,
21644                             DAG.getIntPtrConstant(0, dl));
21645 
21646   SDValue Chain;
21647   if (IsStrict) {
21648     Res = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {MVT::v4f32, MVT::Other},
21649                       {Op.getOperand(0), Res});
21650     Chain = Res.getValue(1);
21651   } else {
21652     Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
21653   }
21654 
21655   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
21656                     DAG.getIntPtrConstant(0, dl));
21657 
21658   if (IsStrict)
21659     return DAG.getMergeValues({Res, Chain}, dl);
21660 
21661   return Res;
21662 }
21663 
21664 static SDValue LowerFP_TO_FP16(SDValue Op, SelectionDAG &DAG) {
21665   bool IsStrict = Op->isStrictFPOpcode();
21666   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
21667   assert(Src.getValueType() == MVT::f32 && Op.getValueType() == MVT::i16 &&
21668          "Unexpected VT!");
21669 
21670   SDLoc dl(Op);
21671   SDValue Res, Chain;
21672   if (IsStrict) {
21673     Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4f32,
21674                       DAG.getConstantFP(0, dl, MVT::v4f32), Src,
21675                       DAG.getIntPtrConstant(0, dl));
21676     Res = DAG.getNode(
21677         X86ISD::STRICT_CVTPS2PH, dl, {MVT::v8i16, MVT::Other},
21678         {Op.getOperand(0), Res, DAG.getTargetConstant(4, dl, MVT::i32)});
21679     Chain = Res.getValue(1);
21680   } else {
21681     // FIXME: Should we use zeros for upper elements for non-strict?
21682     Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, Src);
21683     Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
21684                       DAG.getTargetConstant(4, dl, MVT::i32));
21685   }
21686 
21687   Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Res,
21688                     DAG.getIntPtrConstant(0, dl));
21689 
21690   if (IsStrict)
21691     return DAG.getMergeValues({Res, Chain}, dl);
21692 
21693   return Res;
21694 }
21695 
21696 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21697 /// vector operation in place of the typical scalar operation.
21698 static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
21699                                          const X86Subtarget &Subtarget) {
21700   // If both operands have other uses, this is probably not profitable.
21701   SDValue LHS = Op.getOperand(0);
21702   SDValue RHS = Op.getOperand(1);
21703   if (!LHS.hasOneUse() && !RHS.hasOneUse())
21704     return Op;
21705 
21706   // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
21707   bool IsFP = Op.getSimpleValueType().isFloatingPoint();
21708   if (IsFP && !Subtarget.hasSSE3())
21709     return Op;
21710   if (!IsFP && !Subtarget.hasSSSE3())
21711     return Op;
21712 
21713   // Extract from a common vector.
21714   if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21715       RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
21716       LHS.getOperand(0) != RHS.getOperand(0) ||
21717       !isa<ConstantSDNode>(LHS.getOperand(1)) ||
21718       !isa<ConstantSDNode>(RHS.getOperand(1)) ||
21719       !shouldUseHorizontalOp(true, DAG, Subtarget))
21720     return Op;
21721 
21722   // Allow commuted 'hadd' ops.
21723   // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
21724   unsigned HOpcode;
21725   switch (Op.getOpcode()) {
21726     case ISD::ADD: HOpcode = X86ISD::HADD; break;
21727     case ISD::SUB: HOpcode = X86ISD::HSUB; break;
21728     case ISD::FADD: HOpcode = X86ISD::FHADD; break;
21729     case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
21730     default:
21731       llvm_unreachable("Trying to lower unsupported opcode to horizontal op");
21732   }
21733   unsigned LExtIndex = LHS.getConstantOperandVal(1);
21734   unsigned RExtIndex = RHS.getConstantOperandVal(1);
21735   if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
21736       (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
21737     std::swap(LExtIndex, RExtIndex);
21738 
21739   if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
21740     return Op;
21741 
21742   SDValue X = LHS.getOperand(0);
21743   EVT VecVT = X.getValueType();
21744   unsigned BitWidth = VecVT.getSizeInBits();
21745   unsigned NumLanes = BitWidth / 128;
21746   unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
21747   assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
21748          "Not expecting illegal vector widths here");
21749 
21750   // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
21751   // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
21752   SDLoc DL(Op);
21753   if (BitWidth == 256 || BitWidth == 512) {
21754     unsigned LaneIdx = LExtIndex / NumEltsPerLane;
21755     X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
21756     LExtIndex %= NumEltsPerLane;
21757   }
21758 
21759   // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
21760   // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
21761   // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
21762   // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
21763   SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
21764   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
21765                      DAG.getIntPtrConstant(LExtIndex / 2, DL));
21766 }
21767 
21768 /// Depending on uarch and/or optimizing for size, we might prefer to use a
21769 /// vector operation in place of the typical scalar operation.
21770 SDValue X86TargetLowering::lowerFaddFsub(SDValue Op, SelectionDAG &DAG) const {
21771   assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&
21772          "Only expecting float/double");
21773   return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
21774 }
21775 
21776 /// ISD::FROUND is defined to round to nearest with ties rounding away from 0.
21777 /// This mode isn't supported in hardware on X86. But as long as we aren't
21778 /// compiling with trapping math, we can emulate this with
21779 /// floor(X + copysign(nextafter(0.5, 0.0), X)).
21780 static SDValue LowerFROUND(SDValue Op, SelectionDAG &DAG) {
21781   SDValue N0 = Op.getOperand(0);
21782   SDLoc dl(Op);
21783   MVT VT = Op.getSimpleValueType();
21784 
21785   // N0 += copysign(nextafter(0.5, 0.0), N0)
21786   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21787   bool Ignored;
21788   APFloat Point5Pred = APFloat(0.5f);
21789   Point5Pred.convert(Sem, APFloat::rmNearestTiesToEven, &Ignored);
21790   Point5Pred.next(/*nextDown*/true);
21791 
21792   SDValue Adder = DAG.getNode(ISD::FCOPYSIGN, dl, VT,
21793                               DAG.getConstantFP(Point5Pred, dl, VT), N0);
21794   N0 = DAG.getNode(ISD::FADD, dl, VT, N0, Adder);
21795 
21796   // Truncate the result to remove fraction.
21797   return DAG.getNode(ISD::FTRUNC, dl, VT, N0);
21798 }
21799 
21800 /// The only differences between FABS and FNEG are the mask and the logic op.
21801 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
21802 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
21803   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
21804          "Wrong opcode for lowering FABS or FNEG.");
21805 
21806   bool IsFABS = (Op.getOpcode() == ISD::FABS);
21807 
21808   // If this is a FABS and it has an FNEG user, bail out to fold the combination
21809   // into an FNABS. We'll lower the FABS after that if it is still in use.
21810   if (IsFABS)
21811     for (SDNode *User : Op->uses())
21812       if (User->getOpcode() == ISD::FNEG)
21813         return Op;
21814 
21815   SDLoc dl(Op);
21816   MVT VT = Op.getSimpleValueType();
21817 
21818   bool IsF128 = (VT == MVT::f128);
21819   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
21820           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
21821           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
21822          "Unexpected type in LowerFABSorFNEG");
21823 
21824   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
21825   // decide if we should generate a 16-byte constant mask when we only need 4 or
21826   // 8 bytes for the scalar case.
21827 
21828   // There are no scalar bitwise logical SSE/AVX instructions, so we
21829   // generate a 16-byte vector constant and logic op even for the scalar case.
21830   // Using a 16-byte mask allows folding the load of the mask with
21831   // the logic op, so it can save (~4 bytes) on code size.
21832   bool IsFakeVector = !VT.isVector() && !IsF128;
21833   MVT LogicVT = VT;
21834   if (IsFakeVector)
21835     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
21836 
21837   unsigned EltBits = VT.getScalarSizeInBits();
21838   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
21839   APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
21840                            APInt::getSignMask(EltBits);
21841   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21842   SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
21843 
21844   SDValue Op0 = Op.getOperand(0);
21845   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
21846   unsigned LogicOp = IsFABS  ? X86ISD::FAND :
21847                      IsFNABS ? X86ISD::FOR  :
21848                                X86ISD::FXOR;
21849   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
21850 
21851   if (VT.isVector() || IsF128)
21852     return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
21853 
21854   // For the scalar case extend to a 128-bit vector, perform the logic op,
21855   // and extract the scalar result back out.
21856   Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
21857   SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
21858   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
21859                      DAG.getIntPtrConstant(0, dl));
21860 }
21861 
21862 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
21863   SDValue Mag = Op.getOperand(0);
21864   SDValue Sign = Op.getOperand(1);
21865   SDLoc dl(Op);
21866 
21867   // If the sign operand is smaller, extend it first.
21868   MVT VT = Op.getSimpleValueType();
21869   if (Sign.getSimpleValueType().bitsLT(VT))
21870     Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
21871 
21872   // And if it is bigger, shrink it first.
21873   if (Sign.getSimpleValueType().bitsGT(VT))
21874     Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(1, dl));
21875 
21876   // At this point the operands and the result should have the same
21877   // type, and that won't be f80 since that is not custom lowered.
21878   bool IsF128 = (VT == MVT::f128);
21879   assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||
21880           VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
21881           VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&
21882          "Unexpected type in LowerFCOPYSIGN");
21883 
21884   const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
21885 
21886   // Perform all scalar logic operations as 16-byte vectors because there are no
21887   // scalar FP logic instructions in SSE.
21888   // TODO: This isn't necessary. If we used scalar types, we might avoid some
21889   // unnecessary splats, but we might miss load folding opportunities. Should
21890   // this decision be based on OptimizeForSize?
21891   bool IsFakeVector = !VT.isVector() && !IsF128;
21892   MVT LogicVT = VT;
21893   if (IsFakeVector)
21894     LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
21895 
21896   // The mask constants are automatically splatted for vector types.
21897   unsigned EltSizeInBits = VT.getScalarSizeInBits();
21898   SDValue SignMask = DAG.getConstantFP(
21899       APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
21900   SDValue MagMask = DAG.getConstantFP(
21901       APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
21902 
21903   // First, clear all bits but the sign bit from the second operand (sign).
21904   if (IsFakeVector)
21905     Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
21906   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
21907 
21908   // Next, clear the sign bit from the first operand (magnitude).
21909   // TODO: If we had general constant folding for FP logic ops, this check
21910   // wouldn't be necessary.
21911   SDValue MagBits;
21912   if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
21913     APFloat APF = Op0CN->getValueAPF();
21914     APF.clearSign();
21915     MagBits = DAG.getConstantFP(APF, dl, LogicVT);
21916   } else {
21917     // If the magnitude operand wasn't a constant, we need to AND out the sign.
21918     if (IsFakeVector)
21919       Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
21920     MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
21921   }
21922 
21923   // OR the magnitude value with the sign bit.
21924   SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
21925   return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
21926                                           DAG.getIntPtrConstant(0, dl));
21927 }
21928 
21929 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
21930   SDValue N0 = Op.getOperand(0);
21931   SDLoc dl(Op);
21932   MVT VT = Op.getSimpleValueType();
21933 
21934   MVT OpVT = N0.getSimpleValueType();
21935   assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&
21936          "Unexpected type for FGETSIGN");
21937 
21938   // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
21939   MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
21940   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
21941   Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
21942   Res = DAG.getZExtOrTrunc(Res, dl, VT);
21943   Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
21944   return Res;
21945 }
21946 
21947 /// Helper for creating a X86ISD::SETCC node.
21948 static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
21949                         SelectionDAG &DAG) {
21950   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
21951                      DAG.getTargetConstant(Cond, dl, MVT::i8), EFLAGS);
21952 }
21953 
21954 /// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
21955 /// style scalarized (associative) reduction patterns. Partial reductions
21956 /// are supported when the pointer SrcMask is non-null.
21957 /// TODO - move this to SelectionDAG?
21958 static bool matchScalarReduction(SDValue Op, ISD::NodeType BinOp,
21959                                  SmallVectorImpl<SDValue> &SrcOps,
21960                                  SmallVectorImpl<APInt> *SrcMask = nullptr) {
21961   SmallVector<SDValue, 8> Opnds;
21962   DenseMap<SDValue, APInt> SrcOpMap;
21963   EVT VT = MVT::Other;
21964 
21965   // Recognize a special case where a vector is casted into wide integer to
21966   // test all 0s.
21967   assert(Op.getOpcode() == unsigned(BinOp) &&
21968          "Unexpected bit reduction opcode");
21969   Opnds.push_back(Op.getOperand(0));
21970   Opnds.push_back(Op.getOperand(1));
21971 
21972   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
21973     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
21974     // BFS traverse all BinOp operands.
21975     if (I->getOpcode() == unsigned(BinOp)) {
21976       Opnds.push_back(I->getOperand(0));
21977       Opnds.push_back(I->getOperand(1));
21978       // Re-evaluate the number of nodes to be traversed.
21979       e += 2; // 2 more nodes (LHS and RHS) are pushed.
21980       continue;
21981     }
21982 
21983     // Quit if a non-EXTRACT_VECTOR_ELT
21984     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21985       return false;
21986 
21987     // Quit if without a constant index.
21988     auto *Idx = dyn_cast<ConstantSDNode>(I->getOperand(1));
21989     if (!Idx)
21990       return false;
21991 
21992     SDValue Src = I->getOperand(0);
21993     DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
21994     if (M == SrcOpMap.end()) {
21995       VT = Src.getValueType();
21996       // Quit if not the same type.
21997       if (!SrcOpMap.empty() && VT != SrcOpMap.begin()->first.getValueType())
21998         return false;
21999       unsigned NumElts = VT.getVectorNumElements();
22000       APInt EltCount = APInt::getNullValue(NumElts);
22001       M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
22002       SrcOps.push_back(Src);
22003     }
22004 
22005     // Quit if element already used.
22006     unsigned CIdx = Idx->getZExtValue();
22007     if (M->second[CIdx])
22008       return false;
22009     M->second.setBit(CIdx);
22010   }
22011 
22012   if (SrcMask) {
22013     // Collect the source partial masks.
22014     for (SDValue &SrcOp : SrcOps)
22015       SrcMask->push_back(SrcOpMap[SrcOp]);
22016   } else {
22017     // Quit if not all elements are used.
22018     for (DenseMap<SDValue, APInt>::const_iterator I = SrcOpMap.begin(),
22019                                                   E = SrcOpMap.end();
22020          I != E; ++I) {
22021       if (!I->second.isAllOnesValue())
22022         return false;
22023     }
22024   }
22025 
22026   return true;
22027 }
22028 
22029 // Helper function for comparing all bits of a vector against zero.
22030 static SDValue LowerVectorAllZero(const SDLoc &DL, SDValue V, ISD::CondCode CC,
22031                                   const APInt &Mask,
22032                                   const X86Subtarget &Subtarget,
22033                                   SelectionDAG &DAG, X86::CondCode &X86CC) {
22034   EVT VT = V.getValueType();
22035   unsigned ScalarSize = VT.getScalarSizeInBits();
22036   if (Mask.getBitWidth() != ScalarSize) {
22037     assert(ScalarSize == 1 && "Element Mask vs Vector bitwidth mismatch");
22038     return SDValue();
22039   }
22040 
22041   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22042   X86CC = (CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE);
22043 
22044   auto MaskBits = [&](SDValue Src) {
22045     if (Mask.isAllOnesValue())
22046       return Src;
22047     EVT SrcVT = Src.getValueType();
22048     SDValue MaskValue = DAG.getConstant(Mask, DL, SrcVT);
22049     return DAG.getNode(ISD::AND, DL, SrcVT, Src, MaskValue);
22050   };
22051 
22052   // For sub-128-bit vector, cast to (legal) integer and compare with zero.
22053   if (VT.getSizeInBits() < 128) {
22054     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
22055     if (!DAG.getTargetLoweringInfo().isTypeLegal(IntVT))
22056       return SDValue();
22057     return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
22058                        DAG.getBitcast(IntVT, MaskBits(V)),
22059                        DAG.getConstant(0, DL, IntVT));
22060   }
22061 
22062   // Quit if not splittable to 128/256-bit vector.
22063   if (!isPowerOf2_32(VT.getSizeInBits()))
22064     return SDValue();
22065 
22066   // Split down to 128/256-bit vector.
22067   unsigned TestSize = Subtarget.hasAVX() ? 256 : 128;
22068   while (VT.getSizeInBits() > TestSize) {
22069     auto Split = DAG.SplitVector(V, DL);
22070     VT = Split.first.getValueType();
22071     V = DAG.getNode(ISD::OR, DL, VT, Split.first, Split.second);
22072   }
22073 
22074   bool UsePTEST = Subtarget.hasSSE41();
22075   if (UsePTEST) {
22076     MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
22077     V = DAG.getBitcast(TestVT, MaskBits(V));
22078     return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, V, V);
22079   }
22080 
22081   // Without PTEST, a masked v2i64 or-reduction is not faster than
22082   // scalarization.
22083   if (!Mask.isAllOnesValue() && VT.getScalarSizeInBits() > 32)
22084       return SDValue();
22085 
22086   V = DAG.getBitcast(MVT::v16i8, MaskBits(V));
22087   V = DAG.getNode(X86ISD::PCMPEQ, DL, MVT::v16i8, V,
22088                   getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
22089   V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
22090   return DAG.getNode(X86ISD::CMP, DL, MVT::i32, V,
22091                      DAG.getConstant(0xFFFF, DL, MVT::i32));
22092 }
22093 
22094 // Check whether an OR'd reduction tree is PTEST-able, or if we can fallback to
22095 // CMP(MOVMSK(PCMPEQB(X,0))).
22096 static SDValue MatchVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
22097                                       const SDLoc &DL,
22098                                       const X86Subtarget &Subtarget,
22099                                       SelectionDAG &DAG, SDValue &X86CC) {
22100   assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Unsupported ISD::CondCode");
22101 
22102   if (!Subtarget.hasSSE2() || !Op->hasOneUse())
22103     return SDValue();
22104 
22105   // Check whether we're masking/truncating an OR-reduction result, in which
22106   // case track the masked bits.
22107   APInt Mask = APInt::getAllOnesValue(Op.getScalarValueSizeInBits());
22108   switch (Op.getOpcode()) {
22109   case ISD::TRUNCATE: {
22110     SDValue Src = Op.getOperand(0);
22111     Mask = APInt::getLowBitsSet(Src.getScalarValueSizeInBits(),
22112                                 Op.getScalarValueSizeInBits());
22113     Op = Src;
22114     break;
22115   }
22116   case ISD::AND: {
22117     if (auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22118       Mask = Cst->getAPIntValue();
22119       Op = Op.getOperand(0);
22120     }
22121     break;
22122   }
22123   }
22124 
22125   SmallVector<SDValue, 8> VecIns;
22126   if (Op.getOpcode() == ISD::OR && matchScalarReduction(Op, ISD::OR, VecIns)) {
22127     EVT VT = VecIns[0].getValueType();
22128     assert(llvm::all_of(VecIns,
22129                         [VT](SDValue V) { return VT == V.getValueType(); }) &&
22130            "Reduction source vector mismatch");
22131 
22132     // Quit if less than 128-bits or not splittable to 128/256-bit vector.
22133     if (VT.getSizeInBits() < 128 || !isPowerOf2_32(VT.getSizeInBits()))
22134       return SDValue();
22135 
22136     // If more than one full vector is evaluated, OR them first before PTEST.
22137     for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1;
22138          Slot += 2, e += 1) {
22139       // Each iteration will OR 2 nodes and append the result until there is
22140       // only 1 node left, i.e. the final OR'd value of all vectors.
22141       SDValue LHS = VecIns[Slot];
22142       SDValue RHS = VecIns[Slot + 1];
22143       VecIns.push_back(DAG.getNode(ISD::OR, DL, VT, LHS, RHS));
22144     }
22145 
22146     X86::CondCode CCode;
22147     if (SDValue V = LowerVectorAllZero(DL, VecIns.back(), CC, Mask, Subtarget,
22148                                        DAG, CCode)) {
22149       X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
22150       return V;
22151     }
22152   }
22153 
22154   if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
22155     ISD::NodeType BinOp;
22156     if (SDValue Match =
22157             DAG.matchBinOpReduction(Op.getNode(), BinOp, {ISD::OR})) {
22158       X86::CondCode CCode;
22159       if (SDValue V =
22160               LowerVectorAllZero(DL, Match, CC, Mask, Subtarget, DAG, CCode)) {
22161         X86CC = DAG.getTargetConstant(CCode, DL, MVT::i8);
22162         return V;
22163       }
22164     }
22165   }
22166 
22167   return SDValue();
22168 }
22169 
22170 /// return true if \c Op has a use that doesn't just read flags.
22171 static bool hasNonFlagsUse(SDValue Op) {
22172   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
22173        ++UI) {
22174     SDNode *User = *UI;
22175     unsigned UOpNo = UI.getOperandNo();
22176     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
22177       // Look pass truncate.
22178       UOpNo = User->use_begin().getOperandNo();
22179       User = *User->use_begin();
22180     }
22181 
22182     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
22183         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
22184       return true;
22185   }
22186   return false;
22187 }
22188 
22189 // Transform to an x86-specific ALU node with flags if there is a chance of
22190 // using an RMW op or only the flags are used. Otherwise, leave
22191 // the node alone and emit a 'cmp' or 'test' instruction.
22192 static bool isProfitableToUseFlagOp(SDValue Op) {
22193   for (SDNode *U : Op->uses())
22194     if (U->getOpcode() != ISD::CopyToReg &&
22195         U->getOpcode() != ISD::SETCC &&
22196         U->getOpcode() != ISD::STORE)
22197       return false;
22198 
22199   return true;
22200 }
22201 
22202 /// Emit nodes that will be selected as "test Op0,Op0", or something
22203 /// equivalent.
22204 static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
22205                         SelectionDAG &DAG, const X86Subtarget &Subtarget) {
22206   // CF and OF aren't always set the way we want. Determine which
22207   // of these we need.
22208   bool NeedCF = false;
22209   bool NeedOF = false;
22210   switch (X86CC) {
22211   default: break;
22212   case X86::COND_A: case X86::COND_AE:
22213   case X86::COND_B: case X86::COND_BE:
22214     NeedCF = true;
22215     break;
22216   case X86::COND_G: case X86::COND_GE:
22217   case X86::COND_L: case X86::COND_LE:
22218   case X86::COND_O: case X86::COND_NO: {
22219     // Check if we really need to set the
22220     // Overflow flag. If NoSignedWrap is present
22221     // that is not actually needed.
22222     switch (Op->getOpcode()) {
22223     case ISD::ADD:
22224     case ISD::SUB:
22225     case ISD::MUL:
22226     case ISD::SHL:
22227       if (Op.getNode()->getFlags().hasNoSignedWrap())
22228         break;
22229       LLVM_FALLTHROUGH;
22230     default:
22231       NeedOF = true;
22232       break;
22233     }
22234     break;
22235   }
22236   }
22237   // See if we can use the EFLAGS value from the operand instead of
22238   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
22239   // we prove that the arithmetic won't overflow, we can't use OF or CF.
22240   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
22241     // Emit a CMP with 0, which is the TEST pattern.
22242     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22243                        DAG.getConstant(0, dl, Op.getValueType()));
22244   }
22245   unsigned Opcode = 0;
22246   unsigned NumOperands = 0;
22247 
22248   SDValue ArithOp = Op;
22249 
22250   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
22251   // which may be the result of a CAST.  We use the variable 'Op', which is the
22252   // non-casted variable when we check for possible users.
22253   switch (ArithOp.getOpcode()) {
22254   case ISD::AND:
22255     // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
22256     // because a TEST instruction will be better.
22257     if (!hasNonFlagsUse(Op))
22258       break;
22259 
22260     LLVM_FALLTHROUGH;
22261   case ISD::ADD:
22262   case ISD::SUB:
22263   case ISD::OR:
22264   case ISD::XOR:
22265     if (!isProfitableToUseFlagOp(Op))
22266       break;
22267 
22268     // Otherwise use a regular EFLAGS-setting instruction.
22269     switch (ArithOp.getOpcode()) {
22270     default: llvm_unreachable("unexpected operator!");
22271     case ISD::ADD: Opcode = X86ISD::ADD; break;
22272     case ISD::SUB: Opcode = X86ISD::SUB; break;
22273     case ISD::XOR: Opcode = X86ISD::XOR; break;
22274     case ISD::AND: Opcode = X86ISD::AND; break;
22275     case ISD::OR:  Opcode = X86ISD::OR;  break;
22276     }
22277 
22278     NumOperands = 2;
22279     break;
22280   case X86ISD::ADD:
22281   case X86ISD::SUB:
22282   case X86ISD::OR:
22283   case X86ISD::XOR:
22284   case X86ISD::AND:
22285     return SDValue(Op.getNode(), 1);
22286   case ISD::SSUBO:
22287   case ISD::USUBO: {
22288     // /USUBO/SSUBO will become a X86ISD::SUB and we can use its Z flag.
22289     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22290     return DAG.getNode(X86ISD::SUB, dl, VTs, Op->getOperand(0),
22291                        Op->getOperand(1)).getValue(1);
22292   }
22293   default:
22294     break;
22295   }
22296 
22297   if (Opcode == 0) {
22298     // Emit a CMP with 0, which is the TEST pattern.
22299     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
22300                        DAG.getConstant(0, dl, Op.getValueType()));
22301   }
22302   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
22303   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
22304 
22305   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
22306   DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
22307   return SDValue(New.getNode(), 1);
22308 }
22309 
22310 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
22311 /// equivalent.
22312 static SDValue EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
22313                        const SDLoc &dl, SelectionDAG &DAG,
22314                        const X86Subtarget &Subtarget) {
22315   if (isNullConstant(Op1))
22316     return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
22317 
22318   EVT CmpVT = Op0.getValueType();
22319 
22320   assert((CmpVT == MVT::i8 || CmpVT == MVT::i16 ||
22321           CmpVT == MVT::i32 || CmpVT == MVT::i64) && "Unexpected VT!");
22322 
22323   // Only promote the compare up to I32 if it is a 16 bit operation
22324   // with an immediate.  16 bit immediates are to be avoided.
22325   if (CmpVT == MVT::i16 && !Subtarget.isAtom() &&
22326       !DAG.getMachineFunction().getFunction().hasMinSize()) {
22327     ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
22328     ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
22329     // Don't do this if the immediate can fit in 8-bits.
22330     if ((COp0 && !COp0->getAPIntValue().isSignedIntN(8)) ||
22331         (COp1 && !COp1->getAPIntValue().isSignedIntN(8))) {
22332       unsigned ExtendOp =
22333           isX86CCSigned(X86CC) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
22334       if (X86CC == X86::COND_E || X86CC == X86::COND_NE) {
22335         // For equality comparisons try to use SIGN_EXTEND if the input was
22336         // truncate from something with enough sign bits.
22337         if (Op0.getOpcode() == ISD::TRUNCATE) {
22338           SDValue In = Op0.getOperand(0);
22339           unsigned EffBits =
22340               In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
22341           if (EffBits <= 16)
22342             ExtendOp = ISD::SIGN_EXTEND;
22343         } else if (Op1.getOpcode() == ISD::TRUNCATE) {
22344           SDValue In = Op1.getOperand(0);
22345           unsigned EffBits =
22346               In.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(In) + 1;
22347           if (EffBits <= 16)
22348             ExtendOp = ISD::SIGN_EXTEND;
22349         }
22350       }
22351 
22352       CmpVT = MVT::i32;
22353       Op0 = DAG.getNode(ExtendOp, dl, CmpVT, Op0);
22354       Op1 = DAG.getNode(ExtendOp, dl, CmpVT, Op1);
22355     }
22356   }
22357 
22358   // Try to shrink i64 compares if the input has enough zero bits.
22359   // FIXME: Do this for non-constant compares for constant on LHS?
22360   if (CmpVT == MVT::i64 && isa<ConstantSDNode>(Op1) && !isX86CCSigned(X86CC) &&
22361       Op0.hasOneUse() && // Hacky way to not break CSE opportunities with sub.
22362       cast<ConstantSDNode>(Op1)->getAPIntValue().getActiveBits() <= 32 &&
22363       DAG.MaskedValueIsZero(Op0, APInt::getHighBitsSet(64, 32))) {
22364     CmpVT = MVT::i32;
22365     Op0 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op0);
22366     Op1 = DAG.getNode(ISD::TRUNCATE, dl, CmpVT, Op1);
22367   }
22368 
22369   // 0-x == y --> x+y == 0
22370   // 0-x != y --> x+y != 0
22371   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op0.getOperand(0)) &&
22372       Op0.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
22373     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22374     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(1), Op1);
22375     return Add.getValue(1);
22376   }
22377 
22378   // x == 0-y --> x+y == 0
22379   // x != 0-y --> x+y != 0
22380   if (Op1.getOpcode() == ISD::SUB && isNullConstant(Op1.getOperand(0)) &&
22381       Op1.hasOneUse() && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
22382     SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22383     SDValue Add = DAG.getNode(X86ISD::ADD, dl, VTs, Op0, Op1.getOperand(1));
22384     return Add.getValue(1);
22385   }
22386 
22387   // Use SUB instead of CMP to enable CSE between SUB and CMP.
22388   SDVTList VTs = DAG.getVTList(CmpVT, MVT::i32);
22389   SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
22390   return Sub.getValue(1);
22391 }
22392 
22393 /// Check if replacement of SQRT with RSQRT should be disabled.
22394 bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
22395   EVT VT = Op.getValueType();
22396 
22397   // We never want to use both SQRT and RSQRT instructions for the same input.
22398   if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
22399     return false;
22400 
22401   if (VT.isVector())
22402     return Subtarget.hasFastVectorFSQRT();
22403   return Subtarget.hasFastScalarFSQRT();
22404 }
22405 
22406 /// The minimum architected relative accuracy is 2^-12. We need one
22407 /// Newton-Raphson step to have a good float result (24 bits of precision).
22408 SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
22409                                            SelectionDAG &DAG, int Enabled,
22410                                            int &RefinementSteps,
22411                                            bool &UseOneConstNR,
22412                                            bool Reciprocal) const {
22413   EVT VT = Op.getValueType();
22414 
22415   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
22416   // It is likely not profitable to do this for f64 because a double-precision
22417   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
22418   // instructions: convert to single, rsqrtss, convert back to double, refine
22419   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
22420   // along with FMA, this could be a throughput win.
22421   // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
22422   // after legalize types.
22423   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
22424       (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
22425       (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
22426       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
22427       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
22428     if (RefinementSteps == ReciprocalEstimate::Unspecified)
22429       RefinementSteps = 1;
22430 
22431     UseOneConstNR = false;
22432     // There is no FSQRT for 512-bits, but there is RSQRT14.
22433     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
22434     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
22435   }
22436   return SDValue();
22437 }
22438 
22439 /// The minimum architected relative accuracy is 2^-12. We need one
22440 /// Newton-Raphson step to have a good float result (24 bits of precision).
22441 SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
22442                                             int Enabled,
22443                                             int &RefinementSteps) const {
22444   EVT VT = Op.getValueType();
22445 
22446   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
22447   // It is likely not profitable to do this for f64 because a double-precision
22448   // reciprocal estimate with refinement on x86 prior to FMA requires
22449   // 15 instructions: convert to single, rcpss, convert back to double, refine
22450   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
22451   // along with FMA, this could be a throughput win.
22452 
22453   if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
22454       (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
22455       (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
22456       (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
22457     // Enable estimate codegen with 1 refinement step for vector division.
22458     // Scalar division estimates are disabled because they break too much
22459     // real-world code. These defaults are intended to match GCC behavior.
22460     if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
22461       return SDValue();
22462 
22463     if (RefinementSteps == ReciprocalEstimate::Unspecified)
22464       RefinementSteps = 1;
22465 
22466     // There is no FSQRT for 512-bits, but there is RCP14.
22467     unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
22468     return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
22469   }
22470   return SDValue();
22471 }
22472 
22473 /// If we have at least two divisions that use the same divisor, convert to
22474 /// multiplication by a reciprocal. This may need to be adjusted for a given
22475 /// CPU if a division's cost is not at least twice the cost of a multiplication.
22476 /// This is because we still need one division to calculate the reciprocal and
22477 /// then we need two multiplies by that reciprocal as replacements for the
22478 /// original divisions.
22479 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
22480   return 2;
22481 }
22482 
22483 SDValue
22484 X86TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
22485                                  SelectionDAG &DAG,
22486                                  SmallVectorImpl<SDNode *> &Created) const {
22487   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
22488   if (isIntDivCheap(N->getValueType(0), Attr))
22489     return SDValue(N,0); // Lower SDIV as SDIV
22490 
22491   assert((Divisor.isPowerOf2() || (-Divisor).isPowerOf2()) &&
22492          "Unexpected divisor!");
22493 
22494   // Only perform this transform if CMOV is supported otherwise the select
22495   // below will become a branch.
22496   if (!Subtarget.hasCMov())
22497     return SDValue();
22498 
22499   // fold (sdiv X, pow2)
22500   EVT VT = N->getValueType(0);
22501   // FIXME: Support i8.
22502   if (VT != MVT::i16 && VT != MVT::i32 &&
22503       !(Subtarget.is64Bit() && VT == MVT::i64))
22504     return SDValue();
22505 
22506   unsigned Lg2 = Divisor.countTrailingZeros();
22507 
22508   // If the divisor is 2 or -2, the default expansion is better.
22509   if (Lg2 == 1)
22510     return SDValue();
22511 
22512   SDLoc DL(N);
22513   SDValue N0 = N->getOperand(0);
22514   SDValue Zero = DAG.getConstant(0, DL, VT);
22515   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
22516   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
22517 
22518   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
22519   SDValue Cmp = DAG.getSetCC(DL, MVT::i8, N0, Zero, ISD::SETLT);
22520   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
22521   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
22522 
22523   Created.push_back(Cmp.getNode());
22524   Created.push_back(Add.getNode());
22525   Created.push_back(CMov.getNode());
22526 
22527   // Divide by pow2.
22528   SDValue SRA =
22529       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, MVT::i8));
22530 
22531   // If we're dividing by a positive value, we're done.  Otherwise, we must
22532   // negate the result.
22533   if (Divisor.isNonNegative())
22534     return SRA;
22535 
22536   Created.push_back(SRA.getNode());
22537   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
22538 }
22539 
22540 /// Result of 'and' is compared against zero. Change to a BT node if possible.
22541 /// Returns the BT node and the condition code needed to use it.
22542 static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
22543                             const SDLoc &dl, SelectionDAG &DAG,
22544                             SDValue &X86CC) {
22545   assert(And.getOpcode() == ISD::AND && "Expected AND node!");
22546   SDValue Op0 = And.getOperand(0);
22547   SDValue Op1 = And.getOperand(1);
22548   if (Op0.getOpcode() == ISD::TRUNCATE)
22549     Op0 = Op0.getOperand(0);
22550   if (Op1.getOpcode() == ISD::TRUNCATE)
22551     Op1 = Op1.getOperand(0);
22552 
22553   SDValue Src, BitNo;
22554   if (Op1.getOpcode() == ISD::SHL)
22555     std::swap(Op0, Op1);
22556   if (Op0.getOpcode() == ISD::SHL) {
22557     if (isOneConstant(Op0.getOperand(0))) {
22558       // If we looked past a truncate, check that it's only truncating away
22559       // known zeros.
22560       unsigned BitWidth = Op0.getValueSizeInBits();
22561       unsigned AndBitWidth = And.getValueSizeInBits();
22562       if (BitWidth > AndBitWidth) {
22563         KnownBits Known = DAG.computeKnownBits(Op0);
22564         if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
22565           return SDValue();
22566       }
22567       Src = Op1;
22568       BitNo = Op0.getOperand(1);
22569     }
22570   } else if (Op1.getOpcode() == ISD::Constant) {
22571     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
22572     uint64_t AndRHSVal = AndRHS->getZExtValue();
22573     SDValue AndLHS = Op0;
22574 
22575     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
22576       Src = AndLHS.getOperand(0);
22577       BitNo = AndLHS.getOperand(1);
22578     } else {
22579       // Use BT if the immediate can't be encoded in a TEST instruction or we
22580       // are optimizing for size and the immedaite won't fit in a byte.
22581       bool OptForSize = DAG.shouldOptForSize();
22582       if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
22583           isPowerOf2_64(AndRHSVal)) {
22584         Src = AndLHS;
22585         BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
22586                                 Src.getValueType());
22587       }
22588     }
22589   }
22590 
22591   // No patterns found, give up.
22592   if (!Src.getNode())
22593     return SDValue();
22594 
22595   // If Src is i8, promote it to i32 with any_extend.  There is no i8 BT
22596   // instruction.  Since the shift amount is in-range-or-undefined, we know
22597   // that doing a bittest on the i32 value is ok.  We extend to i32 because
22598   // the encoding for the i16 version is larger than the i32 version.
22599   // Also promote i16 to i32 for performance / code size reason.
22600   if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
22601     Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
22602 
22603   // See if we can use the 32-bit instruction instead of the 64-bit one for a
22604   // shorter encoding. Since the former takes the modulo 32 of BitNo and the
22605   // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
22606   // known to be zero.
22607   if (Src.getValueType() == MVT::i64 &&
22608       DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
22609     Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
22610 
22611   // If the operand types disagree, extend the shift amount to match.  Since
22612   // BT ignores high bits (like shifts) we can use anyextend.
22613   if (Src.getValueType() != BitNo.getValueType())
22614     BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
22615 
22616   X86CC = DAG.getTargetConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
22617                                 dl, MVT::i8);
22618   return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
22619 }
22620 
22621 /// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
22622 /// CMPs.
22623 static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
22624                                    SDValue &Op1, bool &IsAlwaysSignaling) {
22625   unsigned SSECC;
22626   bool Swap = false;
22627 
22628   // SSE Condition code mapping:
22629   //  0 - EQ
22630   //  1 - LT
22631   //  2 - LE
22632   //  3 - UNORD
22633   //  4 - NEQ
22634   //  5 - NLT
22635   //  6 - NLE
22636   //  7 - ORD
22637   switch (SetCCOpcode) {
22638   default: llvm_unreachable("Unexpected SETCC condition");
22639   case ISD::SETOEQ:
22640   case ISD::SETEQ:  SSECC = 0; break;
22641   case ISD::SETOGT:
22642   case ISD::SETGT:  Swap = true; LLVM_FALLTHROUGH;
22643   case ISD::SETLT:
22644   case ISD::SETOLT: SSECC = 1; break;
22645   case ISD::SETOGE:
22646   case ISD::SETGE:  Swap = true; LLVM_FALLTHROUGH;
22647   case ISD::SETLE:
22648   case ISD::SETOLE: SSECC = 2; break;
22649   case ISD::SETUO:  SSECC = 3; break;
22650   case ISD::SETUNE:
22651   case ISD::SETNE:  SSECC = 4; break;
22652   case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
22653   case ISD::SETUGE: SSECC = 5; break;
22654   case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
22655   case ISD::SETUGT: SSECC = 6; break;
22656   case ISD::SETO:   SSECC = 7; break;
22657   case ISD::SETUEQ: SSECC = 8; break;
22658   case ISD::SETONE: SSECC = 12; break;
22659   }
22660   if (Swap)
22661     std::swap(Op0, Op1);
22662 
22663   switch (SetCCOpcode) {
22664   default:
22665     IsAlwaysSignaling = true;
22666     break;
22667   case ISD::SETEQ:
22668   case ISD::SETOEQ:
22669   case ISD::SETUEQ:
22670   case ISD::SETNE:
22671   case ISD::SETONE:
22672   case ISD::SETUNE:
22673   case ISD::SETO:
22674   case ISD::SETUO:
22675     IsAlwaysSignaling = false;
22676     break;
22677   }
22678 
22679   return SSECC;
22680 }
22681 
22682 /// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
22683 /// concatenate the result back.
22684 static SDValue splitIntVSETCC(SDValue Op, SelectionDAG &DAG) {
22685   EVT VT = Op.getValueType();
22686 
22687   assert(Op.getOpcode() == ISD::SETCC && "Unsupported operation");
22688   assert(Op.getOperand(0).getValueType().isInteger() &&
22689          VT == Op.getOperand(0).getValueType() && "Unsupported VTs!");
22690 
22691   SDLoc dl(Op);
22692   SDValue CC = Op.getOperand(2);
22693 
22694   // Extract the LHS Lo/Hi vectors
22695   SDValue LHS1, LHS2;
22696   std::tie(LHS1, LHS2) = splitVector(Op.getOperand(0), DAG, dl);
22697 
22698   // Extract the RHS Lo/Hi vectors
22699   SDValue RHS1, RHS2;
22700   std::tie(RHS1, RHS2) = splitVector(Op.getOperand(1), DAG, dl);
22701 
22702   // Issue the operation on the smaller types and concatenate the result back
22703   EVT LoVT, HiVT;
22704   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
22705   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
22706                      DAG.getNode(ISD::SETCC, dl, LoVT, LHS1, RHS1, CC),
22707                      DAG.getNode(ISD::SETCC, dl, HiVT, LHS2, RHS2, CC));
22708 }
22709 
22710 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
22711 
22712   SDValue Op0 = Op.getOperand(0);
22713   SDValue Op1 = Op.getOperand(1);
22714   SDValue CC = Op.getOperand(2);
22715   MVT VT = Op.getSimpleValueType();
22716   SDLoc dl(Op);
22717 
22718   assert(VT.getVectorElementType() == MVT::i1 &&
22719          "Cannot set masked compare for this operation");
22720 
22721   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
22722 
22723   // Prefer SETGT over SETLT.
22724   if (SetCCOpcode == ISD::SETLT) {
22725     SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
22726     std::swap(Op0, Op1);
22727   }
22728 
22729   return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
22730 }
22731 
22732 /// Given a buildvector constant, return a new vector constant with each element
22733 /// incremented or decremented. If incrementing or decrementing would result in
22734 /// unsigned overflow or underflow or this is not a simple vector constant,
22735 /// return an empty value.
22736 static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
22737   auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
22738   if (!BV)
22739     return SDValue();
22740 
22741   MVT VT = V.getSimpleValueType();
22742   MVT EltVT = VT.getVectorElementType();
22743   unsigned NumElts = VT.getVectorNumElements();
22744   SmallVector<SDValue, 8> NewVecC;
22745   SDLoc DL(V);
22746   for (unsigned i = 0; i < NumElts; ++i) {
22747     auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
22748     if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
22749       return SDValue();
22750 
22751     // Avoid overflow/underflow.
22752     const APInt &EltC = Elt->getAPIntValue();
22753     if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isNullValue()))
22754       return SDValue();
22755 
22756     NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
22757   }
22758 
22759   return DAG.getBuildVector(VT, DL, NewVecC);
22760 }
22761 
22762 /// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
22763 /// Op0 u<= Op1:
22764 ///   t = psubus Op0, Op1
22765 ///   pcmpeq t, <0..0>
22766 static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
22767                                     ISD::CondCode Cond, const SDLoc &dl,
22768                                     const X86Subtarget &Subtarget,
22769                                     SelectionDAG &DAG) {
22770   if (!Subtarget.hasSSE2())
22771     return SDValue();
22772 
22773   MVT VET = VT.getVectorElementType();
22774   if (VET != MVT::i8 && VET != MVT::i16)
22775     return SDValue();
22776 
22777   switch (Cond) {
22778   default:
22779     return SDValue();
22780   case ISD::SETULT: {
22781     // If the comparison is against a constant we can turn this into a
22782     // setule.  With psubus, setule does not require a swap.  This is
22783     // beneficial because the constant in the register is no longer
22784     // destructed as the destination so it can be hoisted out of a loop.
22785     // Only do this pre-AVX since vpcmp* is no longer destructive.
22786     if (Subtarget.hasAVX())
22787       return SDValue();
22788     SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false);
22789     if (!ULEOp1)
22790       return SDValue();
22791     Op1 = ULEOp1;
22792     break;
22793   }
22794   case ISD::SETUGT: {
22795     // If the comparison is against a constant, we can turn this into a setuge.
22796     // This is beneficial because materializing a constant 0 for the PCMPEQ is
22797     // probably cheaper than XOR+PCMPGT using 2 different vector constants:
22798     // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
22799     SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true);
22800     if (!UGEOp1)
22801       return SDValue();
22802     Op1 = Op0;
22803     Op0 = UGEOp1;
22804     break;
22805   }
22806   // Psubus is better than flip-sign because it requires no inversion.
22807   case ISD::SETUGE:
22808     std::swap(Op0, Op1);
22809     break;
22810   case ISD::SETULE:
22811     break;
22812   }
22813 
22814   SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
22815   return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
22816                      DAG.getConstant(0, dl, VT));
22817 }
22818 
22819 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
22820                            SelectionDAG &DAG) {
22821   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
22822                   Op.getOpcode() == ISD::STRICT_FSETCCS;
22823   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
22824   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
22825   SDValue CC = Op.getOperand(IsStrict ? 3 : 2);
22826   MVT VT = Op->getSimpleValueType(0);
22827   ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
22828   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
22829   SDLoc dl(Op);
22830 
22831   if (isFP) {
22832 #ifndef NDEBUG
22833     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
22834     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
22835 #endif
22836 
22837     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
22838     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
22839 
22840     // If we have a strict compare with a vXi1 result and the input is 128/256
22841     // bits we can't use a masked compare unless we have VLX. If we use a wider
22842     // compare like we do for non-strict, we might trigger spurious exceptions
22843     // from the upper elements. Instead emit a AVX compare and convert to mask.
22844     unsigned Opc;
22845     if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1 &&
22846         (!IsStrict || Subtarget.hasVLX() ||
22847          Op0.getSimpleValueType().is512BitVector())) {
22848       assert(VT.getVectorNumElements() <= 16);
22849       Opc = IsStrict ? X86ISD::STRICT_CMPM : X86ISD::CMPM;
22850     } else {
22851       Opc = IsStrict ? X86ISD::STRICT_CMPP : X86ISD::CMPP;
22852       // The SSE/AVX packed FP comparison nodes are defined with a
22853       // floating-point vector result that matches the operand type. This allows
22854       // them to work with an SSE1 target (integer vector types are not legal).
22855       VT = Op0.getSimpleValueType();
22856     }
22857 
22858     SDValue Cmp;
22859     bool IsAlwaysSignaling;
22860     unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1, IsAlwaysSignaling);
22861     if (!Subtarget.hasAVX()) {
22862       // TODO: We could use following steps to handle a quiet compare with
22863       // signaling encodings.
22864       // 1. Get ordered masks from a quiet ISD::SETO
22865       // 2. Use the masks to mask potential unordered elements in operand A, B
22866       // 3. Get the compare results of masked A, B
22867       // 4. Calculating final result using the mask and result from 3
22868       // But currently, we just fall back to scalar operations.
22869       if (IsStrict && IsAlwaysSignaling && !IsSignaling)
22870         return SDValue();
22871 
22872       // Insert an extra signaling instruction to raise exception.
22873       if (IsStrict && !IsAlwaysSignaling && IsSignaling) {
22874         SDValue SignalCmp = DAG.getNode(
22875             Opc, dl, {VT, MVT::Other},
22876             {Chain, Op0, Op1, DAG.getTargetConstant(1, dl, MVT::i8)}); // LT_OS
22877         // FIXME: It seems we need to update the flags of all new strict nodes.
22878         // Otherwise, mayRaiseFPException in MI will return false due to
22879         // NoFPExcept = false by default. However, I didn't find it in other
22880         // patches.
22881         SignalCmp->setFlags(Op->getFlags());
22882         Chain = SignalCmp.getValue(1);
22883       }
22884 
22885       // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
22886       // emit two comparisons and a logic op to tie them together.
22887       if (SSECC >= 8) {
22888         // LLVM predicate is SETUEQ or SETONE.
22889         unsigned CC0, CC1;
22890         unsigned CombineOpc;
22891         if (Cond == ISD::SETUEQ) {
22892           CC0 = 3; // UNORD
22893           CC1 = 0; // EQ
22894           CombineOpc = X86ISD::FOR;
22895         } else {
22896           assert(Cond == ISD::SETONE);
22897           CC0 = 7; // ORD
22898           CC1 = 4; // NEQ
22899           CombineOpc = X86ISD::FAND;
22900         }
22901 
22902         SDValue Cmp0, Cmp1;
22903         if (IsStrict) {
22904           Cmp0 = DAG.getNode(
22905               Opc, dl, {VT, MVT::Other},
22906               {Chain, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8)});
22907           Cmp1 = DAG.getNode(
22908               Opc, dl, {VT, MVT::Other},
22909               {Chain, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8)});
22910           Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Cmp0.getValue(1),
22911                               Cmp1.getValue(1));
22912         } else {
22913           Cmp0 = DAG.getNode(
22914               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC0, dl, MVT::i8));
22915           Cmp1 = DAG.getNode(
22916               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(CC1, dl, MVT::i8));
22917         }
22918         Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
22919       } else {
22920         if (IsStrict) {
22921           Cmp = DAG.getNode(
22922               Opc, dl, {VT, MVT::Other},
22923               {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
22924           Chain = Cmp.getValue(1);
22925         } else
22926           Cmp = DAG.getNode(
22927               Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
22928       }
22929     } else {
22930       // Handle all other FP comparisons here.
22931       if (IsStrict) {
22932         // Make a flip on already signaling CCs before setting bit 4 of AVX CC.
22933         SSECC |= (IsAlwaysSignaling ^ IsSignaling) << 4;
22934         Cmp = DAG.getNode(
22935             Opc, dl, {VT, MVT::Other},
22936             {Chain, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8)});
22937         Chain = Cmp.getValue(1);
22938       } else
22939         Cmp = DAG.getNode(
22940             Opc, dl, VT, Op0, Op1, DAG.getTargetConstant(SSECC, dl, MVT::i8));
22941     }
22942 
22943     if (VT.getFixedSizeInBits() >
22944         Op.getSimpleValueType().getFixedSizeInBits()) {
22945       // We emitted a compare with an XMM/YMM result. Finish converting to a
22946       // mask register using a vptestm.
22947       EVT CastVT = EVT(VT).changeVectorElementTypeToInteger();
22948       Cmp = DAG.getBitcast(CastVT, Cmp);
22949       Cmp = DAG.getSetCC(dl, Op.getSimpleValueType(), Cmp,
22950                          DAG.getConstant(0, dl, CastVT), ISD::SETNE);
22951     } else {
22952       // If this is SSE/AVX CMPP, bitcast the result back to integer to match
22953       // the result type of SETCC. The bitcast is expected to be optimized
22954       // away during combining/isel.
22955       Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
22956     }
22957 
22958     if (IsStrict)
22959       return DAG.getMergeValues({Cmp, Chain}, dl);
22960 
22961     return Cmp;
22962   }
22963 
22964   assert(!IsStrict && "Strict SETCC only handles FP operands.");
22965 
22966   MVT VTOp0 = Op0.getSimpleValueType();
22967   (void)VTOp0;
22968   assert(VTOp0 == Op1.getSimpleValueType() &&
22969          "Expected operands with same type!");
22970   assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
22971          "Invalid number of packed elements for source and destination!");
22972 
22973   // The non-AVX512 code below works under the assumption that source and
22974   // destination types are the same.
22975   assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&
22976          "Value types for source and destination must be the same!");
22977 
22978   // The result is boolean, but operands are int/float
22979   if (VT.getVectorElementType() == MVT::i1) {
22980     // In AVX-512 architecture setcc returns mask with i1 elements,
22981     // But there is no compare instruction for i8 and i16 elements in KNL.
22982     assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&
22983            "Unexpected operand type");
22984     return LowerIntVSETCC_AVX512(Op, DAG);
22985   }
22986 
22987   // Lower using XOP integer comparisons.
22988   if (VT.is128BitVector() && Subtarget.hasXOP()) {
22989     // Translate compare code to XOP PCOM compare mode.
22990     unsigned CmpMode = 0;
22991     switch (Cond) {
22992     default: llvm_unreachable("Unexpected SETCC condition");
22993     case ISD::SETULT:
22994     case ISD::SETLT: CmpMode = 0x00; break;
22995     case ISD::SETULE:
22996     case ISD::SETLE: CmpMode = 0x01; break;
22997     case ISD::SETUGT:
22998     case ISD::SETGT: CmpMode = 0x02; break;
22999     case ISD::SETUGE:
23000     case ISD::SETGE: CmpMode = 0x03; break;
23001     case ISD::SETEQ: CmpMode = 0x04; break;
23002     case ISD::SETNE: CmpMode = 0x05; break;
23003     }
23004 
23005     // Are we comparing unsigned or signed integers?
23006     unsigned Opc =
23007         ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
23008 
23009     return DAG.getNode(Opc, dl, VT, Op0, Op1,
23010                        DAG.getTargetConstant(CmpMode, dl, MVT::i8));
23011   }
23012 
23013   // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
23014   // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
23015   if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
23016     SDValue BC0 = peekThroughBitcasts(Op0);
23017     if (BC0.getOpcode() == ISD::AND) {
23018       APInt UndefElts;
23019       SmallVector<APInt, 64> EltBits;
23020       if (getTargetConstantBitsFromNode(BC0.getOperand(1),
23021                                         VT.getScalarSizeInBits(), UndefElts,
23022                                         EltBits, false, false)) {
23023         if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
23024           Cond = ISD::SETEQ;
23025           Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
23026         }
23027       }
23028     }
23029   }
23030 
23031   // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
23032   if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
23033       Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
23034     ConstantSDNode *C1 = isConstOrConstSplat(Op1);
23035     if (C1 && C1->getAPIntValue().isPowerOf2()) {
23036       unsigned BitWidth = VT.getScalarSizeInBits();
23037       unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
23038 
23039       SDValue Result = Op0.getOperand(0);
23040       Result = DAG.getNode(ISD::SHL, dl, VT, Result,
23041                            DAG.getConstant(ShiftAmt, dl, VT));
23042       Result = DAG.getNode(ISD::SRA, dl, VT, Result,
23043                            DAG.getConstant(BitWidth - 1, dl, VT));
23044       return Result;
23045     }
23046   }
23047 
23048   // Break 256-bit integer vector compare into smaller ones.
23049   if (VT.is256BitVector() && !Subtarget.hasInt256())
23050     return splitIntVSETCC(Op, DAG);
23051 
23052   if (VT == MVT::v32i16 || VT == MVT::v64i8) {
23053     assert(!Subtarget.hasBWI() && "Unexpected VT with AVX512BW!");
23054     return splitIntVSETCC(Op, DAG);
23055   }
23056 
23057   // If this is a SETNE against the signed minimum value, change it to SETGT.
23058   // If this is a SETNE against the signed maximum value, change it to SETLT.
23059   // which will be swapped to SETGT.
23060   // Otherwise we use PCMPEQ+invert.
23061   APInt ConstValue;
23062   if (Cond == ISD::SETNE &&
23063       ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
23064     if (ConstValue.isMinSignedValue())
23065       Cond = ISD::SETGT;
23066     else if (ConstValue.isMaxSignedValue())
23067       Cond = ISD::SETLT;
23068   }
23069 
23070   // If both operands are known non-negative, then an unsigned compare is the
23071   // same as a signed compare and there's no need to flip signbits.
23072   // TODO: We could check for more general simplifications here since we're
23073   // computing known bits.
23074   bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
23075                    !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
23076 
23077   // Special case: Use min/max operations for unsigned compares.
23078   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23079   if (ISD::isUnsignedIntSetCC(Cond) &&
23080       (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
23081       TLI.isOperationLegal(ISD::UMIN, VT)) {
23082     // If we have a constant operand, increment/decrement it and change the
23083     // condition to avoid an invert.
23084     if (Cond == ISD::SETUGT) {
23085       // X > C --> X >= (C+1) --> X == umax(X, C+1)
23086       if (SDValue UGTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/true)) {
23087         Op1 = UGTOp1;
23088         Cond = ISD::SETUGE;
23089       }
23090     }
23091     if (Cond == ISD::SETULT) {
23092       // X < C --> X <= (C-1) --> X == umin(X, C-1)
23093       if (SDValue ULTOp1 = incDecVectorConstant(Op1, DAG, /*IsInc*/false)) {
23094         Op1 = ULTOp1;
23095         Cond = ISD::SETULE;
23096       }
23097     }
23098     bool Invert = false;
23099     unsigned Opc;
23100     switch (Cond) {
23101     default: llvm_unreachable("Unexpected condition code");
23102     case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH;
23103     case ISD::SETULE: Opc = ISD::UMIN; break;
23104     case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH;
23105     case ISD::SETUGE: Opc = ISD::UMAX; break;
23106     }
23107 
23108     SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23109     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
23110 
23111     // If the logical-not of the result is required, perform that now.
23112     if (Invert)
23113       Result = DAG.getNOT(dl, Result, VT);
23114 
23115     return Result;
23116   }
23117 
23118   // Try to use SUBUS and PCMPEQ.
23119   if (FlipSigns)
23120     if (SDValue V =
23121             LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
23122       return V;
23123 
23124   // We are handling one of the integer comparisons here. Since SSE only has
23125   // GT and EQ comparisons for integer, swapping operands and multiple
23126   // operations may be required for some comparisons.
23127   unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
23128                                                             : X86ISD::PCMPGT;
23129   bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
23130               Cond == ISD::SETGE || Cond == ISD::SETUGE;
23131   bool Invert = Cond == ISD::SETNE ||
23132                 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
23133 
23134   if (Swap)
23135     std::swap(Op0, Op1);
23136 
23137   // Check that the operation in question is available (most are plain SSE2,
23138   // but PCMPGTQ and PCMPEQQ have different requirements).
23139   if (VT == MVT::v2i64) {
23140     if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
23141       assert(Subtarget.hasSSE2() && "Don't know how to lower!");
23142 
23143       // Special case for sign bit test. We can use a v4i32 PCMPGT and shuffle
23144       // the odd elements over the even elements.
23145       if (!FlipSigns && !Invert && ISD::isBuildVectorAllZeros(Op0.getNode())) {
23146         Op0 = DAG.getConstant(0, dl, MVT::v4i32);
23147         Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23148 
23149         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23150         static const int MaskHi[] = { 1, 1, 3, 3 };
23151         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23152 
23153         return DAG.getBitcast(VT, Result);
23154       }
23155 
23156       if (!FlipSigns && !Invert && ISD::isBuildVectorAllOnes(Op1.getNode())) {
23157         Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23158         Op1 = DAG.getConstant(-1, dl, MVT::v4i32);
23159 
23160         SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23161         static const int MaskHi[] = { 1, 1, 3, 3 };
23162         SDValue Result = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23163 
23164         return DAG.getBitcast(VT, Result);
23165       }
23166 
23167       // Since SSE has no unsigned integer comparisons, we need to flip the sign
23168       // bits of the inputs before performing those operations. The lower
23169       // compare is always unsigned.
23170       SDValue SB;
23171       if (FlipSigns) {
23172         SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
23173       } else {
23174         SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
23175       }
23176       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
23177       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
23178 
23179       // Cast everything to the right type.
23180       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23181       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23182 
23183       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
23184       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
23185       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
23186 
23187       // Create masks for only the low parts/high parts of the 64 bit integers.
23188       static const int MaskHi[] = { 1, 1, 3, 3 };
23189       static const int MaskLo[] = { 0, 0, 2, 2 };
23190       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
23191       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
23192       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
23193 
23194       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
23195       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
23196 
23197       if (Invert)
23198         Result = DAG.getNOT(dl, Result, MVT::v4i32);
23199 
23200       return DAG.getBitcast(VT, Result);
23201     }
23202 
23203     if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
23204       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
23205       // pcmpeqd + pshufd + pand.
23206       assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!");
23207 
23208       // First cast everything to the right type.
23209       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
23210       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
23211 
23212       // Do the compare.
23213       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
23214 
23215       // Make sure the lower and upper halves are both all-ones.
23216       static const int Mask[] = { 1, 0, 3, 2 };
23217       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
23218       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
23219 
23220       if (Invert)
23221         Result = DAG.getNOT(dl, Result, MVT::v4i32);
23222 
23223       return DAG.getBitcast(VT, Result);
23224     }
23225   }
23226 
23227   // Since SSE has no unsigned integer comparisons, we need to flip the sign
23228   // bits of the inputs before performing those operations.
23229   if (FlipSigns) {
23230     MVT EltVT = VT.getVectorElementType();
23231     SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
23232                                  VT);
23233     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
23234     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
23235   }
23236 
23237   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
23238 
23239   // If the logical-not of the result is required, perform that now.
23240   if (Invert)
23241     Result = DAG.getNOT(dl, Result, VT);
23242 
23243   return Result;
23244 }
23245 
23246 // Try to select this as a KORTEST+SETCC or KTEST+SETCC if possible.
23247 static SDValue EmitAVX512Test(SDValue Op0, SDValue Op1, ISD::CondCode CC,
23248                               const SDLoc &dl, SelectionDAG &DAG,
23249                               const X86Subtarget &Subtarget,
23250                               SDValue &X86CC) {
23251   // Only support equality comparisons.
23252   if (CC != ISD::SETEQ && CC != ISD::SETNE)
23253     return SDValue();
23254 
23255   // Must be a bitcast from vXi1.
23256   if (Op0.getOpcode() != ISD::BITCAST)
23257     return SDValue();
23258 
23259   Op0 = Op0.getOperand(0);
23260   MVT VT = Op0.getSimpleValueType();
23261   if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
23262       !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
23263       !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
23264     return SDValue();
23265 
23266   X86::CondCode X86Cond;
23267   if (isNullConstant(Op1)) {
23268     X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
23269   } else if (isAllOnesConstant(Op1)) {
23270     // C flag is set for all ones.
23271     X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
23272   } else
23273     return SDValue();
23274 
23275   // If the input is an AND, we can combine it's operands into the KTEST.
23276   bool KTestable = false;
23277   if (Subtarget.hasDQI() && (VT == MVT::v8i1 || VT == MVT::v16i1))
23278     KTestable = true;
23279   if (Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1))
23280     KTestable = true;
23281   if (!isNullConstant(Op1))
23282     KTestable = false;
23283   if (KTestable && Op0.getOpcode() == ISD::AND && Op0.hasOneUse()) {
23284     SDValue LHS = Op0.getOperand(0);
23285     SDValue RHS = Op0.getOperand(1);
23286     X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23287     return DAG.getNode(X86ISD::KTEST, dl, MVT::i32, LHS, RHS);
23288   }
23289 
23290   // If the input is an OR, we can combine it's operands into the KORTEST.
23291   SDValue LHS = Op0;
23292   SDValue RHS = Op0;
23293   if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
23294     LHS = Op0.getOperand(0);
23295     RHS = Op0.getOperand(1);
23296   }
23297 
23298   X86CC = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
23299   return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
23300 }
23301 
23302 /// Emit flags for the given setcc condition and operands. Also returns the
23303 /// corresponding X86 condition code constant in X86CC.
23304 SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
23305                                              ISD::CondCode CC, const SDLoc &dl,
23306                                              SelectionDAG &DAG,
23307                                              SDValue &X86CC) const {
23308   // Optimize to BT if possible.
23309   // Lower (X & (1 << N)) == 0 to BT(X, N).
23310   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
23311   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
23312   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
23313       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
23314     if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
23315       return BT;
23316   }
23317 
23318   // Try to use PTEST/PMOVMSKB for a tree ORs equality compared with 0.
23319   // TODO: We could do AND tree with all 1s as well by using the C flag.
23320   if (isNullConstant(Op1) && (CC == ISD::SETEQ || CC == ISD::SETNE))
23321     if (SDValue CmpZ =
23322             MatchVectorAllZeroTest(Op0, CC, dl, Subtarget, DAG, X86CC))
23323       return CmpZ;
23324 
23325   // Try to lower using KORTEST or KTEST.
23326   if (SDValue Test = EmitAVX512Test(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
23327     return Test;
23328 
23329   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
23330   // these.
23331   if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
23332       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
23333     // If the input is a setcc, then reuse the input setcc or use a new one with
23334     // the inverted condition.
23335     if (Op0.getOpcode() == X86ISD::SETCC) {
23336       bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
23337 
23338       X86CC = Op0.getOperand(0);
23339       if (Invert) {
23340         X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
23341         CCode = X86::GetOppositeBranchCondition(CCode);
23342         X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
23343       }
23344 
23345       return Op0.getOperand(1);
23346     }
23347   }
23348 
23349   // Try to use the carry flag from the add in place of an separate CMP for:
23350   // (seteq (add X, -1), -1). Similar for setne.
23351   if (isAllOnesConstant(Op1) && Op0.getOpcode() == ISD::ADD &&
23352       Op0.getOperand(1) == Op1 && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
23353     if (isProfitableToUseFlagOp(Op0)) {
23354       SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
23355 
23356       SDValue New = DAG.getNode(X86ISD::ADD, dl, VTs, Op0.getOperand(0),
23357                                 Op0.getOperand(1));
23358       DAG.ReplaceAllUsesOfValueWith(SDValue(Op0.getNode(), 0), New);
23359       X86::CondCode CCode = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
23360       X86CC = DAG.getTargetConstant(CCode, dl, MVT::i8);
23361       return SDValue(New.getNode(), 1);
23362     }
23363   }
23364 
23365   X86::CondCode CondCode =
23366       TranslateX86CC(CC, dl, /*IsFP*/ false, Op0, Op1, DAG);
23367   assert(CondCode != X86::COND_INVALID && "Unexpected condition code!");
23368 
23369   SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG, Subtarget);
23370   X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
23371   return EFLAGS;
23372 }
23373 
23374 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
23375 
23376   bool IsStrict = Op.getOpcode() == ISD::STRICT_FSETCC ||
23377                   Op.getOpcode() == ISD::STRICT_FSETCCS;
23378   MVT VT = Op->getSimpleValueType(0);
23379 
23380   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
23381 
23382   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
23383   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
23384   SDValue Op0 = Op.getOperand(IsStrict ? 1 : 0);
23385   SDValue Op1 = Op.getOperand(IsStrict ? 2 : 1);
23386   SDLoc dl(Op);
23387   ISD::CondCode CC =
23388       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
23389 
23390   // Handle f128 first, since one possible outcome is a normal integer
23391   // comparison which gets handled by emitFlagsForSetcc.
23392   if (Op0.getValueType() == MVT::f128) {
23393     softenSetCCOperands(DAG, MVT::f128, Op0, Op1, CC, dl, Op0, Op1, Chain,
23394                         Op.getOpcode() == ISD::STRICT_FSETCCS);
23395 
23396     // If softenSetCCOperands returned a scalar, use it.
23397     if (!Op1.getNode()) {
23398       assert(Op0.getValueType() == Op.getValueType() &&
23399              "Unexpected setcc expansion!");
23400       if (IsStrict)
23401         return DAG.getMergeValues({Op0, Chain}, dl);
23402       return Op0;
23403     }
23404   }
23405 
23406   if (Op0.getSimpleValueType().isInteger()) {
23407     SDValue X86CC;
23408     SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
23409     SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
23410     return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
23411   }
23412 
23413   // Handle floating point.
23414   X86::CondCode CondCode = TranslateX86CC(CC, dl, /*IsFP*/ true, Op0, Op1, DAG);
23415   if (CondCode == X86::COND_INVALID)
23416     return SDValue();
23417 
23418   SDValue EFLAGS;
23419   if (IsStrict) {
23420     bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
23421     EFLAGS =
23422         DAG.getNode(IsSignaling ? X86ISD::STRICT_FCMPS : X86ISD::STRICT_FCMP,
23423                     dl, {MVT::i32, MVT::Other}, {Chain, Op0, Op1});
23424     Chain = EFLAGS.getValue(1);
23425   } else {
23426     EFLAGS = DAG.getNode(X86ISD::FCMP, dl, MVT::i32, Op0, Op1);
23427   }
23428 
23429   SDValue X86CC = DAG.getTargetConstant(CondCode, dl, MVT::i8);
23430   SDValue Res = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
23431   return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
23432 }
23433 
23434 SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
23435   SDValue LHS = Op.getOperand(0);
23436   SDValue RHS = Op.getOperand(1);
23437   SDValue Carry = Op.getOperand(2);
23438   SDValue Cond = Op.getOperand(3);
23439   SDLoc DL(Op);
23440 
23441   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
23442   X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
23443 
23444   // Recreate the carry if needed.
23445   EVT CarryVT = Carry.getValueType();
23446   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
23447                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
23448 
23449   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
23450   SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
23451   return getSETCC(CC, Cmp.getValue(1), DL, DAG);
23452 }
23453 
23454 // This function returns three things: the arithmetic computation itself
23455 // (Value), an EFLAGS result (Overflow), and a condition code (Cond).  The
23456 // flag and the condition code define the case in which the arithmetic
23457 // computation overflows.
23458 static std::pair<SDValue, SDValue>
23459 getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
23460   assert(Op.getResNo() == 0 && "Unexpected result number!");
23461   SDValue Value, Overflow;
23462   SDValue LHS = Op.getOperand(0);
23463   SDValue RHS = Op.getOperand(1);
23464   unsigned BaseOp = 0;
23465   SDLoc DL(Op);
23466   switch (Op.getOpcode()) {
23467   default: llvm_unreachable("Unknown ovf instruction!");
23468   case ISD::SADDO:
23469     BaseOp = X86ISD::ADD;
23470     Cond = X86::COND_O;
23471     break;
23472   case ISD::UADDO:
23473     BaseOp = X86ISD::ADD;
23474     Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
23475     break;
23476   case ISD::SSUBO:
23477     BaseOp = X86ISD::SUB;
23478     Cond = X86::COND_O;
23479     break;
23480   case ISD::USUBO:
23481     BaseOp = X86ISD::SUB;
23482     Cond = X86::COND_B;
23483     break;
23484   case ISD::SMULO:
23485     BaseOp = X86ISD::SMUL;
23486     Cond = X86::COND_O;
23487     break;
23488   case ISD::UMULO:
23489     BaseOp = X86ISD::UMUL;
23490     Cond = X86::COND_O;
23491     break;
23492   }
23493 
23494   if (BaseOp) {
23495     // Also sets EFLAGS.
23496     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23497     Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
23498     Overflow = Value.getValue(1);
23499   }
23500 
23501   return std::make_pair(Value, Overflow);
23502 }
23503 
23504 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
23505   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
23506   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
23507   // looks for this combo and may remove the "setcc" instruction if the "setcc"
23508   // has only one use.
23509   SDLoc DL(Op);
23510   X86::CondCode Cond;
23511   SDValue Value, Overflow;
23512   std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
23513 
23514   SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
23515   assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!");
23516   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
23517 }
23518 
23519 /// Return true if opcode is a X86 logical comparison.
23520 static bool isX86LogicalCmp(SDValue Op) {
23521   unsigned Opc = Op.getOpcode();
23522   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
23523       Opc == X86ISD::FCMP)
23524     return true;
23525   if (Op.getResNo() == 1 &&
23526       (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
23527        Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
23528        Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
23529     return true;
23530 
23531   return false;
23532 }
23533 
23534 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
23535   if (V.getOpcode() != ISD::TRUNCATE)
23536     return false;
23537 
23538   SDValue VOp0 = V.getOperand(0);
23539   unsigned InBits = VOp0.getValueSizeInBits();
23540   unsigned Bits = V.getValueSizeInBits();
23541   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
23542 }
23543 
23544 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
23545   bool AddTest = true;
23546   SDValue Cond  = Op.getOperand(0);
23547   SDValue Op1 = Op.getOperand(1);
23548   SDValue Op2 = Op.getOperand(2);
23549   SDLoc DL(Op);
23550   MVT VT = Op1.getSimpleValueType();
23551   SDValue CC;
23552 
23553   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
23554   // are available or VBLENDV if AVX is available.
23555   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
23556   if (Cond.getOpcode() == ISD::SETCC && isScalarFPTypeInSSEReg(VT) &&
23557       VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
23558     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
23559     bool IsAlwaysSignaling;
23560     unsigned SSECC =
23561         translateX86FSETCC(cast<CondCodeSDNode>(Cond.getOperand(2))->get(),
23562                            CondOp0, CondOp1, IsAlwaysSignaling);
23563 
23564     if (Subtarget.hasAVX512()) {
23565       SDValue Cmp =
23566           DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0, CondOp1,
23567                       DAG.getTargetConstant(SSECC, DL, MVT::i8));
23568       assert(!VT.isVector() && "Not a scalar type?");
23569       return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23570     }
23571 
23572     if (SSECC < 8 || Subtarget.hasAVX()) {
23573       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
23574                                 DAG.getTargetConstant(SSECC, DL, MVT::i8));
23575 
23576       // If we have AVX, we can use a variable vector select (VBLENDV) instead
23577       // of 3 logic instructions for size savings and potentially speed.
23578       // Unfortunately, there is no scalar form of VBLENDV.
23579 
23580       // If either operand is a +0.0 constant, don't try this. We can expect to
23581       // optimize away at least one of the logic instructions later in that
23582       // case, so that sequence would be faster than a variable blend.
23583 
23584       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
23585       // uses XMM0 as the selection register. That may need just as many
23586       // instructions as the AND/ANDN/OR sequence due to register moves, so
23587       // don't bother.
23588       if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
23589           !isNullFPConstant(Op2)) {
23590         // Convert to vectors, do a VSELECT, and convert back to scalar.
23591         // All of the conversions should be optimized away.
23592         MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
23593         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
23594         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
23595         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
23596 
23597         MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
23598         VCmp = DAG.getBitcast(VCmpVT, VCmp);
23599 
23600         SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
23601 
23602         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
23603                            VSel, DAG.getIntPtrConstant(0, DL));
23604       }
23605       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
23606       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
23607       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
23608     }
23609   }
23610 
23611   // AVX512 fallback is to lower selects of scalar floats to masked moves.
23612   if (isScalarFPTypeInSSEReg(VT) && Subtarget.hasAVX512()) {
23613     SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
23614     return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
23615   }
23616 
23617   if (Cond.getOpcode() == ISD::SETCC) {
23618     if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
23619       Cond = NewCond;
23620       // If the condition was updated, it's possible that the operands of the
23621       // select were also updated (for example, EmitTest has a RAUW). Refresh
23622       // the local references to the select operands in case they got stale.
23623       Op1 = Op.getOperand(1);
23624       Op2 = Op.getOperand(2);
23625     }
23626   }
23627 
23628   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
23629   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
23630   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
23631   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
23632   // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
23633   // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
23634   if (Cond.getOpcode() == X86ISD::SETCC &&
23635       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
23636       isNullConstant(Cond.getOperand(1).getOperand(1))) {
23637     SDValue Cmp = Cond.getOperand(1);
23638     SDValue CmpOp0 = Cmp.getOperand(0);
23639     unsigned CondCode = Cond.getConstantOperandVal(0);
23640 
23641     // Special handling for __builtin_ffs(X) - 1 pattern which looks like
23642     // (select (seteq X, 0), -1, (cttz_zero_undef X)). Disable the special
23643     // handle to keep the CMP with 0. This should be removed by
23644     // optimizeCompareInst by using the flags from the BSR/TZCNT used for the
23645     // cttz_zero_undef.
23646     auto MatchFFSMinus1 = [&](SDValue Op1, SDValue Op2) {
23647       return (Op1.getOpcode() == ISD::CTTZ_ZERO_UNDEF && Op1.hasOneUse() &&
23648               Op1.getOperand(0) == CmpOp0 && isAllOnesConstant(Op2));
23649     };
23650     if (Subtarget.hasCMov() && (VT == MVT::i32 || VT == MVT::i64) &&
23651         ((CondCode == X86::COND_NE && MatchFFSMinus1(Op1, Op2)) ||
23652          (CondCode == X86::COND_E && MatchFFSMinus1(Op2, Op1)))) {
23653       // Keep Cmp.
23654     } else if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
23655         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
23656       SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
23657 
23658       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
23659       SDVTList CmpVTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
23660 
23661       // Apply further optimizations for special cases
23662       // (select (x != 0), -1, 0) -> neg & sbb
23663       // (select (x == 0), 0, -1) -> neg & sbb
23664       if (isNullConstant(Y) &&
23665           (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
23666         SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
23667         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, CmpVTs, Zero, CmpOp0);
23668         Zero = DAG.getConstant(0, DL, Op.getValueType());
23669         return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Neg.getValue(1));
23670       }
23671 
23672       Cmp = DAG.getNode(X86ISD::SUB, DL, CmpVTs,
23673                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
23674 
23675       SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
23676       SDValue Res =   // Res = 0 or -1.
23677         DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp.getValue(1));
23678 
23679       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
23680         Res = DAG.getNOT(DL, Res, Res.getValueType());
23681 
23682       return DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
23683     } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
23684                Cmp.getOperand(0).getOpcode() == ISD::AND &&
23685                isOneConstant(Cmp.getOperand(0).getOperand(1))) {
23686       SDValue Src1, Src2;
23687       // true if Op2 is XOR or OR operator and one of its operands
23688       // is equal to Op1
23689       // ( a , a op b) || ( b , a op b)
23690       auto isOrXorPattern = [&]() {
23691         if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
23692             (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
23693           Src1 =
23694               Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
23695           Src2 = Op1;
23696           return true;
23697         }
23698         return false;
23699       };
23700 
23701       if (isOrXorPattern()) {
23702         SDValue Neg;
23703         unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
23704         // we need mask of all zeros or ones with same size of the other
23705         // operands.
23706         if (CmpSz > VT.getSizeInBits())
23707           Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
23708         else if (CmpSz < VT.getSizeInBits())
23709           Neg = DAG.getNode(ISD::AND, DL, VT,
23710               DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
23711               DAG.getConstant(1, DL, VT));
23712         else
23713           Neg = CmpOp0;
23714         SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
23715                                    Neg); // -(and (x, 0x1))
23716         SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
23717         return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2);  // And Op y
23718       }
23719     }
23720   }
23721 
23722   // Look past (and (setcc_carry (cmp ...)), 1).
23723   if (Cond.getOpcode() == ISD::AND &&
23724       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
23725       isOneConstant(Cond.getOperand(1)))
23726     Cond = Cond.getOperand(0);
23727 
23728   // If condition flag is set by a X86ISD::CMP, then use it as the condition
23729   // setting operand in place of the X86ISD::SETCC.
23730   unsigned CondOpcode = Cond.getOpcode();
23731   if (CondOpcode == X86ISD::SETCC ||
23732       CondOpcode == X86ISD::SETCC_CARRY) {
23733     CC = Cond.getOperand(0);
23734 
23735     SDValue Cmp = Cond.getOperand(1);
23736     bool IllegalFPCMov = false;
23737     if (VT.isFloatingPoint() && !VT.isVector() &&
23738         !isScalarFPTypeInSSEReg(VT) && Subtarget.hasCMov())  // FPStack?
23739       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
23740 
23741     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
23742         Cmp.getOpcode() == X86ISD::BT) { // FIXME
23743       Cond = Cmp;
23744       AddTest = false;
23745     }
23746   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
23747              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
23748              CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
23749     SDValue Value;
23750     X86::CondCode X86Cond;
23751     std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
23752 
23753     CC = DAG.getTargetConstant(X86Cond, DL, MVT::i8);
23754     AddTest = false;
23755   }
23756 
23757   if (AddTest) {
23758     // Look past the truncate if the high bits are known zero.
23759     if (isTruncWithZeroHighBitsInput(Cond, DAG))
23760       Cond = Cond.getOperand(0);
23761 
23762     // We know the result of AND is compared against zero. Try to match
23763     // it to BT.
23764     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
23765       SDValue BTCC;
23766       if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
23767         CC = BTCC;
23768         Cond = BT;
23769         AddTest = false;
23770       }
23771     }
23772   }
23773 
23774   if (AddTest) {
23775     CC = DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8);
23776     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG, Subtarget);
23777   }
23778 
23779   // a <  b ? -1 :  0 -> RES = ~setcc_carry
23780   // a <  b ?  0 : -1 -> RES = setcc_carry
23781   // a >= b ? -1 :  0 -> RES = setcc_carry
23782   // a >= b ?  0 : -1 -> RES = ~setcc_carry
23783   if (Cond.getOpcode() == X86ISD::SUB) {
23784     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
23785 
23786     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
23787         (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
23788         (isNullConstant(Op1) || isNullConstant(Op2))) {
23789       SDValue Res =
23790           DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
23791                       DAG.getTargetConstant(X86::COND_B, DL, MVT::i8), Cond);
23792       if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
23793         return DAG.getNOT(DL, Res, Res.getValueType());
23794       return Res;
23795     }
23796   }
23797 
23798   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
23799   // widen the cmov and push the truncate through. This avoids introducing a new
23800   // branch during isel and doesn't add any extensions.
23801   if (Op.getValueType() == MVT::i8 &&
23802       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
23803     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
23804     if (T1.getValueType() == T2.getValueType() &&
23805         // Exclude CopyFromReg to avoid partial register stalls.
23806         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
23807       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
23808                                  CC, Cond);
23809       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
23810     }
23811   }
23812 
23813   // Or finally, promote i8 cmovs if we have CMOV,
23814   //                 or i16 cmovs if it won't prevent folding a load.
23815   // FIXME: we should not limit promotion of i8 case to only when the CMOV is
23816   //        legal, but EmitLoweredSelect() can not deal with these extensions
23817   //        being inserted between two CMOV's. (in i16 case too TBN)
23818   //        https://bugs.llvm.org/show_bug.cgi?id=40974
23819   if ((Op.getValueType() == MVT::i8 && Subtarget.hasCMov()) ||
23820       (Op.getValueType() == MVT::i16 && !MayFoldLoad(Op1) &&
23821        !MayFoldLoad(Op2))) {
23822     Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
23823     Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
23824     SDValue Ops[] = { Op2, Op1, CC, Cond };
23825     SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
23826     return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
23827   }
23828 
23829   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
23830   // condition is true.
23831   SDValue Ops[] = { Op2, Op1, CC, Cond };
23832   return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
23833 }
23834 
23835 static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
23836                                      const X86Subtarget &Subtarget,
23837                                      SelectionDAG &DAG) {
23838   MVT VT = Op->getSimpleValueType(0);
23839   SDValue In = Op->getOperand(0);
23840   MVT InVT = In.getSimpleValueType();
23841   assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!");
23842   MVT VTElt = VT.getVectorElementType();
23843   SDLoc dl(Op);
23844 
23845   unsigned NumElts = VT.getVectorNumElements();
23846 
23847   // Extend VT if the scalar type is i8/i16 and BWI is not supported.
23848   MVT ExtVT = VT;
23849   if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
23850     // If v16i32 is to be avoided, we'll need to split and concatenate.
23851     if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
23852       return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
23853 
23854     ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
23855   }
23856 
23857   // Widen to 512-bits if VLX is not supported.
23858   MVT WideVT = ExtVT;
23859   if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
23860     NumElts *= 512 / ExtVT.getSizeInBits();
23861     InVT = MVT::getVectorVT(MVT::i1, NumElts);
23862     In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
23863                      In, DAG.getIntPtrConstant(0, dl));
23864     WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
23865   }
23866 
23867   SDValue V;
23868   MVT WideEltVT = WideVT.getVectorElementType();
23869   if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
23870       (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
23871     V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
23872   } else {
23873     SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
23874     SDValue Zero = DAG.getConstant(0, dl, WideVT);
23875     V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
23876   }
23877 
23878   // Truncate if we had to extend i16/i8 above.
23879   if (VT != ExtVT) {
23880     WideVT = MVT::getVectorVT(VTElt, NumElts);
23881     V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
23882   }
23883 
23884   // Extract back to 128/256-bit if we widened.
23885   if (WideVT != VT)
23886     V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
23887                     DAG.getIntPtrConstant(0, dl));
23888 
23889   return V;
23890 }
23891 
23892 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
23893                                SelectionDAG &DAG) {
23894   SDValue In = Op->getOperand(0);
23895   MVT InVT = In.getSimpleValueType();
23896 
23897   if (InVT.getVectorElementType() == MVT::i1)
23898     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
23899 
23900   assert(Subtarget.hasAVX() && "Expected AVX support");
23901   return LowerAVXExtend(Op, DAG, Subtarget);
23902 }
23903 
23904 // Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
23905 // For sign extend this needs to handle all vector sizes and SSE4.1 and
23906 // non-SSE4.1 targets. For zero extend this should only handle inputs of
23907 // MVT::v64i8 when BWI is not supported, but AVX512 is.
23908 static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
23909                                         const X86Subtarget &Subtarget,
23910                                         SelectionDAG &DAG) {
23911   SDValue In = Op->getOperand(0);
23912   MVT VT = Op->getSimpleValueType(0);
23913   MVT InVT = In.getSimpleValueType();
23914 
23915   MVT SVT = VT.getVectorElementType();
23916   MVT InSVT = InVT.getVectorElementType();
23917   assert(SVT.getFixedSizeInBits() > InSVT.getFixedSizeInBits());
23918 
23919   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
23920     return SDValue();
23921   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
23922     return SDValue();
23923   if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
23924       !(VT.is256BitVector() && Subtarget.hasAVX()) &&
23925       !(VT.is512BitVector() && Subtarget.hasAVX512()))
23926     return SDValue();
23927 
23928   SDLoc dl(Op);
23929   unsigned Opc = Op.getOpcode();
23930   unsigned NumElts = VT.getVectorNumElements();
23931 
23932   // For 256-bit vectors, we only need the lower (128-bit) half of the input.
23933   // For 512-bit vectors, we need 128-bits or 256-bits.
23934   if (InVT.getSizeInBits() > 128) {
23935     // Input needs to be at least the same number of elements as output, and
23936     // at least 128-bits.
23937     int InSize = InSVT.getSizeInBits() * NumElts;
23938     In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
23939     InVT = In.getSimpleValueType();
23940   }
23941 
23942   // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
23943   // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
23944   // need to be handled here for 256/512-bit results.
23945   if (Subtarget.hasInt256()) {
23946     assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension");
23947 
23948     if (InVT.getVectorNumElements() != NumElts)
23949       return DAG.getNode(Op.getOpcode(), dl, VT, In);
23950 
23951     // FIXME: Apparently we create inreg operations that could be regular
23952     // extends.
23953     unsigned ExtOpc =
23954         Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
23955                                              : ISD::ZERO_EXTEND;
23956     return DAG.getNode(ExtOpc, dl, VT, In);
23957   }
23958 
23959   // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
23960   if (Subtarget.hasAVX()) {
23961     assert(VT.is256BitVector() && "256-bit vector expected");
23962     MVT HalfVT = VT.getHalfNumVectorElementsVT();
23963     int HalfNumElts = HalfVT.getVectorNumElements();
23964 
23965     unsigned NumSrcElts = InVT.getVectorNumElements();
23966     SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
23967     for (int i = 0; i != HalfNumElts; ++i)
23968       HiMask[i] = HalfNumElts + i;
23969 
23970     SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
23971     SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
23972     Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
23973     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
23974   }
23975 
23976   // We should only get here for sign extend.
23977   assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!");
23978   assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs");
23979 
23980   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
23981   SDValue Curr = In;
23982   SDValue SignExt = Curr;
23983 
23984   // As SRAI is only available on i16/i32 types, we expand only up to i32
23985   // and handle i64 separately.
23986   if (InVT != MVT::v4i32) {
23987     MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
23988 
23989     unsigned DestWidth = DestVT.getScalarSizeInBits();
23990     unsigned Scale = DestWidth / InSVT.getSizeInBits();
23991 
23992     unsigned InNumElts = InVT.getVectorNumElements();
23993     unsigned DestElts = DestVT.getVectorNumElements();
23994 
23995     // Build a shuffle mask that takes each input element and places it in the
23996     // MSBs of the new element size.
23997     SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
23998     for (unsigned i = 0; i != DestElts; ++i)
23999       Mask[i * Scale + (Scale - 1)] = i;
24000 
24001     Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
24002     Curr = DAG.getBitcast(DestVT, Curr);
24003 
24004     unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
24005     SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
24006                           DAG.getTargetConstant(SignExtShift, dl, MVT::i8));
24007   }
24008 
24009   if (VT == MVT::v2i64) {
24010     assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT");
24011     SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
24012     SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
24013     SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
24014     SignExt = DAG.getBitcast(VT, SignExt);
24015   }
24016 
24017   return SignExt;
24018 }
24019 
24020 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
24021                                 SelectionDAG &DAG) {
24022   MVT VT = Op->getSimpleValueType(0);
24023   SDValue In = Op->getOperand(0);
24024   MVT InVT = In.getSimpleValueType();
24025   SDLoc dl(Op);
24026 
24027   if (InVT.getVectorElementType() == MVT::i1)
24028     return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
24029 
24030   assert(VT.isVector() && InVT.isVector() && "Expected vector type");
24031   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
24032          "Expected same number of elements");
24033   assert((VT.getVectorElementType() == MVT::i16 ||
24034           VT.getVectorElementType() == MVT::i32 ||
24035           VT.getVectorElementType() == MVT::i64) &&
24036          "Unexpected element type");
24037   assert((InVT.getVectorElementType() == MVT::i8 ||
24038           InVT.getVectorElementType() == MVT::i16 ||
24039           InVT.getVectorElementType() == MVT::i32) &&
24040          "Unexpected element type");
24041 
24042   if (VT == MVT::v32i16 && !Subtarget.hasBWI()) {
24043     assert(InVT == MVT::v32i8 && "Unexpected VT!");
24044     return splitVectorIntUnary(Op, DAG);
24045   }
24046 
24047   if (Subtarget.hasInt256())
24048     return Op;
24049 
24050   // Optimize vectors in AVX mode
24051   // Sign extend  v8i16 to v8i32 and
24052   //              v4i32 to v4i64
24053   //
24054   // Divide input vector into two parts
24055   // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
24056   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
24057   // concat the vectors to original VT
24058   MVT HalfVT = VT.getHalfNumVectorElementsVT();
24059   SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
24060 
24061   unsigned NumElems = InVT.getVectorNumElements();
24062   SmallVector<int,8> ShufMask(NumElems, -1);
24063   for (unsigned i = 0; i != NumElems/2; ++i)
24064     ShufMask[i] = i + NumElems/2;
24065 
24066   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
24067   OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
24068 
24069   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
24070 }
24071 
24072 /// Change a vector store into a pair of half-size vector stores.
24073 static SDValue splitVectorStore(StoreSDNode *Store, SelectionDAG &DAG) {
24074   SDValue StoredVal = Store->getValue();
24075   assert((StoredVal.getValueType().is256BitVector() ||
24076           StoredVal.getValueType().is512BitVector()) &&
24077          "Expecting 256/512-bit op");
24078 
24079   // Splitting volatile memory ops is not allowed unless the operation was not
24080   // legal to begin with. Assume the input store is legal (this transform is
24081   // only used for targets with AVX). Note: It is possible that we have an
24082   // illegal type like v2i128, and so we could allow splitting a volatile store
24083   // in that case if that is important.
24084   if (!Store->isSimple())
24085     return SDValue();
24086 
24087   SDLoc DL(Store);
24088   SDValue Value0, Value1;
24089   std::tie(Value0, Value1) = splitVector(StoredVal, DAG, DL);
24090   unsigned HalfOffset = Value0.getValueType().getStoreSize();
24091   SDValue Ptr0 = Store->getBasePtr();
24092   SDValue Ptr1 =
24093       DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(HalfOffset), DL);
24094   SDValue Ch0 =
24095       DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
24096                    Store->getOriginalAlign(),
24097                    Store->getMemOperand()->getFlags());
24098   SDValue Ch1 = DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
24099                              Store->getPointerInfo().getWithOffset(HalfOffset),
24100                              Store->getOriginalAlign(),
24101                              Store->getMemOperand()->getFlags());
24102   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
24103 }
24104 
24105 /// Scalarize a vector store, bitcasting to TargetVT to determine the scalar
24106 /// type.
24107 static SDValue scalarizeVectorStore(StoreSDNode *Store, MVT StoreVT,
24108                                     SelectionDAG &DAG) {
24109   SDValue StoredVal = Store->getValue();
24110   assert(StoreVT.is128BitVector() &&
24111          StoredVal.getValueType().is128BitVector() && "Expecting 128-bit op");
24112   StoredVal = DAG.getBitcast(StoreVT, StoredVal);
24113 
24114   // Splitting volatile memory ops is not allowed unless the operation was not
24115   // legal to begin with. We are assuming the input op is legal (this transform
24116   // is only used for targets with AVX).
24117   if (!Store->isSimple())
24118     return SDValue();
24119 
24120   MVT StoreSVT = StoreVT.getScalarType();
24121   unsigned NumElems = StoreVT.getVectorNumElements();
24122   unsigned ScalarSize = StoreSVT.getStoreSize();
24123 
24124   SDLoc DL(Store);
24125   SmallVector<SDValue, 4> Stores;
24126   for (unsigned i = 0; i != NumElems; ++i) {
24127     unsigned Offset = i * ScalarSize;
24128     SDValue Ptr = DAG.getMemBasePlusOffset(Store->getBasePtr(),
24129                                            TypeSize::Fixed(Offset), DL);
24130     SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreSVT, StoredVal,
24131                               DAG.getIntPtrConstant(i, DL));
24132     SDValue Ch = DAG.getStore(Store->getChain(), DL, Scl, Ptr,
24133                               Store->getPointerInfo().getWithOffset(Offset),
24134                               Store->getOriginalAlign(),
24135                               Store->getMemOperand()->getFlags());
24136     Stores.push_back(Ch);
24137   }
24138   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
24139 }
24140 
24141 static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
24142                           SelectionDAG &DAG) {
24143   StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
24144   SDLoc dl(St);
24145   SDValue StoredVal = St->getValue();
24146 
24147   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
24148   if (StoredVal.getValueType().isVector() &&
24149       StoredVal.getValueType().getVectorElementType() == MVT::i1) {
24150     unsigned NumElts = StoredVal.getValueType().getVectorNumElements();
24151     assert(NumElts <= 8 && "Unexpected VT");
24152     assert(!St->isTruncatingStore() && "Expected non-truncating store");
24153     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
24154            "Expected AVX512F without AVX512DQI");
24155 
24156     // We must pad with zeros to ensure we store zeroes to any unused bits.
24157     StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
24158                             DAG.getUNDEF(MVT::v16i1), StoredVal,
24159                             DAG.getIntPtrConstant(0, dl));
24160     StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
24161     StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
24162     // Make sure we store zeros in the extra bits.
24163     if (NumElts < 8)
24164       StoredVal = DAG.getZeroExtendInReg(
24165           StoredVal, dl, EVT::getIntegerVT(*DAG.getContext(), NumElts));
24166 
24167     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
24168                         St->getPointerInfo(), St->getOriginalAlign(),
24169                         St->getMemOperand()->getFlags());
24170   }
24171 
24172   if (St->isTruncatingStore())
24173     return SDValue();
24174 
24175   // If this is a 256-bit store of concatenated ops, we are better off splitting
24176   // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
24177   // and each half can execute independently. Some cores would split the op into
24178   // halves anyway, so the concat (vinsertf128) is purely an extra op.
24179   MVT StoreVT = StoredVal.getSimpleValueType();
24180   if (StoreVT.is256BitVector() ||
24181       ((StoreVT == MVT::v32i16 || StoreVT == MVT::v64i8) &&
24182        !Subtarget.hasBWI())) {
24183     SmallVector<SDValue, 4> CatOps;
24184     if (StoredVal.hasOneUse() && collectConcatOps(StoredVal.getNode(), CatOps))
24185       return splitVectorStore(St, DAG);
24186     return SDValue();
24187   }
24188 
24189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24190   assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&
24191          "Unexpected VT");
24192   assert(TLI.getTypeAction(*DAG.getContext(), StoreVT) ==
24193              TargetLowering::TypeWidenVector && "Unexpected type action!");
24194 
24195   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), StoreVT);
24196   StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
24197                           DAG.getUNDEF(StoreVT));
24198 
24199   if (Subtarget.hasSSE2()) {
24200     // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
24201     // and store it.
24202     MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
24203     MVT CastVT = MVT::getVectorVT(StVT, 2);
24204     StoredVal = DAG.getBitcast(CastVT, StoredVal);
24205     StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
24206                             DAG.getIntPtrConstant(0, dl));
24207 
24208     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
24209                         St->getPointerInfo(), St->getOriginalAlign(),
24210                         St->getMemOperand()->getFlags());
24211   }
24212   assert(Subtarget.hasSSE1() && "Expected SSE");
24213   SDVTList Tys = DAG.getVTList(MVT::Other);
24214   SDValue Ops[] = {St->getChain(), StoredVal, St->getBasePtr()};
24215   return DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops, MVT::i64,
24216                                  St->getMemOperand());
24217 }
24218 
24219 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
24220 // may emit an illegal shuffle but the expansion is still better than scalar
24221 // code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
24222 // we'll emit a shuffle and a arithmetic shift.
24223 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
24224 // TODO: It is possible to support ZExt by zeroing the undef values during
24225 // the shuffle phase or after the shuffle.
24226 static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
24227                                  SelectionDAG &DAG) {
24228   MVT RegVT = Op.getSimpleValueType();
24229   assert(RegVT.isVector() && "We only custom lower vector loads.");
24230   assert(RegVT.isInteger() &&
24231          "We only custom lower integer vector loads.");
24232 
24233   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
24234   SDLoc dl(Ld);
24235 
24236   // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
24237   if (RegVT.getVectorElementType() == MVT::i1) {
24238     assert(EVT(RegVT) == Ld->getMemoryVT() && "Expected non-extending load");
24239     assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT");
24240     assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
24241            "Expected AVX512F without AVX512DQI");
24242 
24243     SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
24244                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
24245                                 Ld->getMemOperand()->getFlags());
24246 
24247     // Replace chain users with the new chain.
24248     assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!");
24249 
24250     SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
24251     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
24252                       DAG.getBitcast(MVT::v16i1, Val),
24253                       DAG.getIntPtrConstant(0, dl));
24254     return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
24255   }
24256 
24257   return SDValue();
24258 }
24259 
24260 /// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
24261 /// each of which has no other use apart from the AND / OR.
24262 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
24263   Opc = Op.getOpcode();
24264   if (Opc != ISD::OR && Opc != ISD::AND)
24265     return false;
24266   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
24267           Op.getOperand(0).hasOneUse() &&
24268           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
24269           Op.getOperand(1).hasOneUse());
24270 }
24271 
24272 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
24273   SDValue Chain = Op.getOperand(0);
24274   SDValue Cond  = Op.getOperand(1);
24275   SDValue Dest  = Op.getOperand(2);
24276   SDLoc dl(Op);
24277 
24278   if (Cond.getOpcode() == ISD::SETCC &&
24279       Cond.getOperand(0).getValueType() != MVT::f128) {
24280     SDValue LHS = Cond.getOperand(0);
24281     SDValue RHS = Cond.getOperand(1);
24282     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24283 
24284     // Special case for
24285     // setcc([su]{add,sub,mul}o == 0)
24286     // setcc([su]{add,sub,mul}o != 1)
24287     if (ISD::isOverflowIntrOpRes(LHS) &&
24288         (CC == ISD::SETEQ || CC == ISD::SETNE) &&
24289         (isNullConstant(RHS) || isOneConstant(RHS))) {
24290       SDValue Value, Overflow;
24291       X86::CondCode X86Cond;
24292       std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, LHS.getValue(0), DAG);
24293 
24294       if ((CC == ISD::SETEQ) == isNullConstant(RHS))
24295         X86Cond = X86::GetOppositeBranchCondition(X86Cond);
24296 
24297       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24298       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24299                          Overflow);
24300     }
24301 
24302     if (LHS.getSimpleValueType().isInteger()) {
24303       SDValue CCVal;
24304       SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, CC, SDLoc(Cond), DAG, CCVal);
24305       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24306                          EFLAGS);
24307     }
24308 
24309     if (CC == ISD::SETOEQ) {
24310       // For FCMP_OEQ, we can emit
24311       // two branches instead of an explicit AND instruction with a
24312       // separate test. However, we only do this if this block doesn't
24313       // have a fall-through edge, because this requires an explicit
24314       // jmp when the condition is false.
24315       if (Op.getNode()->hasOneUse()) {
24316         SDNode *User = *Op.getNode()->use_begin();
24317         // Look for an unconditional branch following this conditional branch.
24318         // We need this because we need to reverse the successors in order
24319         // to implement FCMP_OEQ.
24320         if (User->getOpcode() == ISD::BR) {
24321           SDValue FalseBB = User->getOperand(1);
24322           SDNode *NewBR =
24323             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
24324           assert(NewBR == User);
24325           (void)NewBR;
24326           Dest = FalseBB;
24327 
24328           SDValue Cmp =
24329               DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24330           SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
24331           Chain = DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest,
24332                               CCVal, Cmp);
24333           CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
24334           return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24335                              Cmp);
24336         }
24337       }
24338     } else if (CC == ISD::SETUNE) {
24339       // For FCMP_UNE, we can emit
24340       // two branches instead of an explicit OR instruction with a
24341       // separate test.
24342       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24343       SDValue CCVal = DAG.getTargetConstant(X86::COND_NE, dl, MVT::i8);
24344       Chain =
24345           DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp);
24346       CCVal = DAG.getTargetConstant(X86::COND_P, dl, MVT::i8);
24347       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24348                          Cmp);
24349     } else {
24350       X86::CondCode X86Cond =
24351           TranslateX86CC(CC, dl, /*IsFP*/ true, LHS, RHS, DAG);
24352       SDValue Cmp = DAG.getNode(X86ISD::FCMP, SDLoc(Cond), MVT::i32, LHS, RHS);
24353       SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24354       return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24355                          Cmp);
24356     }
24357   }
24358 
24359   if (ISD::isOverflowIntrOpRes(Cond)) {
24360     SDValue Value, Overflow;
24361     X86::CondCode X86Cond;
24362     std::tie(Value, Overflow) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
24363 
24364     SDValue CCVal = DAG.getTargetConstant(X86Cond, dl, MVT::i8);
24365     return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24366                        Overflow);
24367   }
24368 
24369   // Look past the truncate if the high bits are known zero.
24370   if (isTruncWithZeroHighBitsInput(Cond, DAG))
24371     Cond = Cond.getOperand(0);
24372 
24373   EVT CondVT = Cond.getValueType();
24374 
24375   // Add an AND with 1 if we don't already have one.
24376   if (!(Cond.getOpcode() == ISD::AND && isOneConstant(Cond.getOperand(1))))
24377     Cond =
24378         DAG.getNode(ISD::AND, dl, CondVT, Cond, DAG.getConstant(1, dl, CondVT));
24379 
24380   SDValue LHS = Cond;
24381   SDValue RHS = DAG.getConstant(0, dl, CondVT);
24382 
24383   SDValue CCVal;
24384   SDValue EFLAGS = emitFlagsForSetcc(LHS, RHS, ISD::SETNE, dl, DAG, CCVal);
24385   return DAG.getNode(X86ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
24386                      EFLAGS);
24387 }
24388 
24389 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
24390 // Calls to _alloca are needed to probe the stack when allocating more than 4k
24391 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
24392 // that the guard pages used by the OS virtual memory manager are allocated in
24393 // correct sequence.
24394 SDValue
24395 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
24396                                            SelectionDAG &DAG) const {
24397   MachineFunction &MF = DAG.getMachineFunction();
24398   bool SplitStack = MF.shouldSplitStack();
24399   bool EmitStackProbeCall = hasStackProbeSymbol(MF);
24400   bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
24401                SplitStack || EmitStackProbeCall;
24402   SDLoc dl(Op);
24403 
24404   // Get the inputs.
24405   SDNode *Node = Op.getNode();
24406   SDValue Chain = Op.getOperand(0);
24407   SDValue Size  = Op.getOperand(1);
24408   MaybeAlign Alignment(Op.getConstantOperandVal(2));
24409   EVT VT = Node->getValueType(0);
24410 
24411   // Chain the dynamic stack allocation so that it doesn't modify the stack
24412   // pointer when other instructions are using the stack.
24413   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
24414 
24415   bool Is64Bit = Subtarget.is64Bit();
24416   MVT SPTy = getPointerTy(DAG.getDataLayout());
24417 
24418   SDValue Result;
24419   if (!Lower) {
24420     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24421     Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
24422     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
24423                     " not tell us which reg is the stack pointer!");
24424 
24425     const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
24426     const Align StackAlign = TFI.getStackAlign();
24427     if (hasInlineStackProbe(MF)) {
24428       MachineRegisterInfo &MRI = MF.getRegInfo();
24429 
24430       const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
24431       Register Vreg = MRI.createVirtualRegister(AddrRegClass);
24432       Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
24433       Result = DAG.getNode(X86ISD::PROBED_ALLOCA, dl, SPTy, Chain,
24434                            DAG.getRegister(Vreg, SPTy));
24435     } else {
24436       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
24437       Chain = SP.getValue(1);
24438       Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
24439     }
24440     if (Alignment && *Alignment > StackAlign)
24441       Result =
24442           DAG.getNode(ISD::AND, dl, VT, Result,
24443                       DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
24444     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
24445   } else if (SplitStack) {
24446     MachineRegisterInfo &MRI = MF.getRegInfo();
24447 
24448     if (Is64Bit) {
24449       // The 64 bit implementation of segmented stacks needs to clobber both r10
24450       // r11. This makes it impossible to use it along with nested parameters.
24451       const Function &F = MF.getFunction();
24452       for (const auto &A : F.args()) {
24453         if (A.hasNestAttr())
24454           report_fatal_error("Cannot use segmented stacks with functions that "
24455                              "have nested arguments.");
24456       }
24457     }
24458 
24459     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
24460     Register Vreg = MRI.createVirtualRegister(AddrRegClass);
24461     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
24462     Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
24463                                 DAG.getRegister(Vreg, SPTy));
24464   } else {
24465     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
24466     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
24467     MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
24468 
24469     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
24470     Register SPReg = RegInfo->getStackRegister();
24471     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
24472     Chain = SP.getValue(1);
24473 
24474     if (Alignment) {
24475       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
24476                        DAG.getConstant(~(Alignment->value() - 1ULL), dl, VT));
24477       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
24478     }
24479 
24480     Result = SP;
24481   }
24482 
24483   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
24484                              DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
24485 
24486   SDValue Ops[2] = {Result, Chain};
24487   return DAG.getMergeValues(Ops, dl);
24488 }
24489 
24490 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
24491   MachineFunction &MF = DAG.getMachineFunction();
24492   auto PtrVT = getPointerTy(MF.getDataLayout());
24493   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
24494 
24495   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
24496   SDLoc DL(Op);
24497 
24498   if (!Subtarget.is64Bit() ||
24499       Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
24500     // vastart just stores the address of the VarArgsFrameIndex slot into the
24501     // memory location argument.
24502     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
24503     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
24504                         MachinePointerInfo(SV));
24505   }
24506 
24507   // __va_list_tag:
24508   //   gp_offset         (0 - 6 * 8)
24509   //   fp_offset         (48 - 48 + 8 * 16)
24510   //   overflow_arg_area (point to parameters coming in memory).
24511   //   reg_save_area
24512   SmallVector<SDValue, 8> MemOps;
24513   SDValue FIN = Op.getOperand(1);
24514   // Store gp_offset
24515   SDValue Store = DAG.getStore(
24516       Op.getOperand(0), DL,
24517       DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
24518       MachinePointerInfo(SV));
24519   MemOps.push_back(Store);
24520 
24521   // Store fp_offset
24522   FIN = DAG.getMemBasePlusOffset(FIN, TypeSize::Fixed(4), DL);
24523   Store = DAG.getStore(
24524       Op.getOperand(0), DL,
24525       DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
24526       MachinePointerInfo(SV, 4));
24527   MemOps.push_back(Store);
24528 
24529   // Store ptr to overflow_arg_area
24530   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
24531   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
24532   Store =
24533       DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
24534   MemOps.push_back(Store);
24535 
24536   // Store ptr to reg_save_area.
24537   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
24538       Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
24539   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
24540   Store = DAG.getStore(
24541       Op.getOperand(0), DL, RSFIN, FIN,
24542       MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
24543   MemOps.push_back(Store);
24544   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
24545 }
24546 
24547 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
24548   assert(Subtarget.is64Bit() &&
24549          "LowerVAARG only handles 64-bit va_arg!");
24550   assert(Op.getNumOperands() == 4);
24551 
24552   MachineFunction &MF = DAG.getMachineFunction();
24553   if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
24554     // The Win64 ABI uses char* instead of a structure.
24555     return DAG.expandVAArg(Op.getNode());
24556 
24557   SDValue Chain = Op.getOperand(0);
24558   SDValue SrcPtr = Op.getOperand(1);
24559   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
24560   unsigned Align = Op.getConstantOperandVal(3);
24561   SDLoc dl(Op);
24562 
24563   EVT ArgVT = Op.getNode()->getValueType(0);
24564   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
24565   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
24566   uint8_t ArgMode;
24567 
24568   // Decide which area this value should be read from.
24569   // TODO: Implement the AMD64 ABI in its entirety. This simple
24570   // selection mechanism works only for the basic types.
24571   assert(ArgVT != MVT::f80 && "va_arg for f80 not yet implemented");
24572   if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
24573     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
24574   } else {
24575     assert(ArgVT.isInteger() && ArgSize <= 32 /*bytes*/ &&
24576            "Unhandled argument type in LowerVAARG");
24577     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
24578   }
24579 
24580   if (ArgMode == 2) {
24581     // Sanity Check: Make sure using fp_offset makes sense.
24582     assert(!Subtarget.useSoftFloat() &&
24583            !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&
24584            Subtarget.hasSSE1());
24585   }
24586 
24587   // Insert VAARG node into the DAG
24588   // VAARG returns two values: Variable Argument Address, Chain
24589   SDValue InstOps[] = {Chain, SrcPtr,
24590                        DAG.getTargetConstant(ArgSize, dl, MVT::i32),
24591                        DAG.getTargetConstant(ArgMode, dl, MVT::i8),
24592                        DAG.getTargetConstant(Align, dl, MVT::i32)};
24593   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
24594   SDValue VAARG = DAG.getMemIntrinsicNode(
24595       Subtarget.isTarget64BitLP64() ? X86ISD::VAARG_64 : X86ISD::VAARG_X32, dl,
24596       VTs, InstOps, MVT::i64, MachinePointerInfo(SV),
24597       /*Alignment=*/None,
24598       MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
24599   Chain = VAARG.getValue(1);
24600 
24601   // Load the next argument and return it
24602   return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
24603 }
24604 
24605 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
24606                            SelectionDAG &DAG) {
24607   // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
24608   // where a va_list is still an i8*.
24609   assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!");
24610   if (Subtarget.isCallingConvWin64(
24611         DAG.getMachineFunction().getFunction().getCallingConv()))
24612     // Probably a Win64 va_copy.
24613     return DAG.expandVACopy(Op.getNode());
24614 
24615   SDValue Chain = Op.getOperand(0);
24616   SDValue DstPtr = Op.getOperand(1);
24617   SDValue SrcPtr = Op.getOperand(2);
24618   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
24619   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
24620   SDLoc DL(Op);
24621 
24622   return DAG.getMemcpy(
24623       Chain, DL, DstPtr, SrcPtr,
24624       DAG.getIntPtrConstant(Subtarget.isTarget64BitLP64() ? 24 : 16, DL),
24625       Align(Subtarget.isTarget64BitLP64() ? 8 : 4), /*isVolatile*/ false, false,
24626       false, MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
24627 }
24628 
24629 // Helper to get immediate/variable SSE shift opcode from other shift opcodes.
24630 static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
24631   switch (Opc) {
24632   case ISD::SHL:
24633   case X86ISD::VSHL:
24634   case X86ISD::VSHLI:
24635     return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
24636   case ISD::SRL:
24637   case X86ISD::VSRL:
24638   case X86ISD::VSRLI:
24639     return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
24640   case ISD::SRA:
24641   case X86ISD::VSRA:
24642   case X86ISD::VSRAI:
24643     return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
24644   }
24645   llvm_unreachable("Unknown target vector shift node");
24646 }
24647 
24648 /// Handle vector element shifts where the shift amount is a constant.
24649 /// Takes immediate version of shift as input.
24650 static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
24651                                           SDValue SrcOp, uint64_t ShiftAmt,
24652                                           SelectionDAG &DAG) {
24653   MVT ElementType = VT.getVectorElementType();
24654 
24655   // Bitcast the source vector to the output type, this is mainly necessary for
24656   // vXi8/vXi64 shifts.
24657   if (VT != SrcOp.getSimpleValueType())
24658     SrcOp = DAG.getBitcast(VT, SrcOp);
24659 
24660   // Fold this packed shift into its first operand if ShiftAmt is 0.
24661   if (ShiftAmt == 0)
24662     return SrcOp;
24663 
24664   // Check for ShiftAmt >= element width
24665   if (ShiftAmt >= ElementType.getSizeInBits()) {
24666     if (Opc == X86ISD::VSRAI)
24667       ShiftAmt = ElementType.getSizeInBits() - 1;
24668     else
24669       return DAG.getConstant(0, dl, VT);
24670   }
24671 
24672   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
24673          && "Unknown target vector shift-by-constant node");
24674 
24675   // Fold this packed vector shift into a build vector if SrcOp is a
24676   // vector of Constants or UNDEFs.
24677   if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
24678     SmallVector<SDValue, 8> Elts;
24679     unsigned NumElts = SrcOp->getNumOperands();
24680 
24681     switch (Opc) {
24682     default: llvm_unreachable("Unknown opcode!");
24683     case X86ISD::VSHLI:
24684       for (unsigned i = 0; i != NumElts; ++i) {
24685         SDValue CurrentOp = SrcOp->getOperand(i);
24686         if (CurrentOp->isUndef()) {
24687           // Must produce 0s in the correct bits.
24688           Elts.push_back(DAG.getConstant(0, dl, ElementType));
24689           continue;
24690         }
24691         auto *ND = cast<ConstantSDNode>(CurrentOp);
24692         const APInt &C = ND->getAPIntValue();
24693         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
24694       }
24695       break;
24696     case X86ISD::VSRLI:
24697       for (unsigned i = 0; i != NumElts; ++i) {
24698         SDValue CurrentOp = SrcOp->getOperand(i);
24699         if (CurrentOp->isUndef()) {
24700           // Must produce 0s in the correct bits.
24701           Elts.push_back(DAG.getConstant(0, dl, ElementType));
24702           continue;
24703         }
24704         auto *ND = cast<ConstantSDNode>(CurrentOp);
24705         const APInt &C = ND->getAPIntValue();
24706         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
24707       }
24708       break;
24709     case X86ISD::VSRAI:
24710       for (unsigned i = 0; i != NumElts; ++i) {
24711         SDValue CurrentOp = SrcOp->getOperand(i);
24712         if (CurrentOp->isUndef()) {
24713           // All shifted in bits must be the same so use 0.
24714           Elts.push_back(DAG.getConstant(0, dl, ElementType));
24715           continue;
24716         }
24717         auto *ND = cast<ConstantSDNode>(CurrentOp);
24718         const APInt &C = ND->getAPIntValue();
24719         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
24720       }
24721       break;
24722     }
24723 
24724     return DAG.getBuildVector(VT, dl, Elts);
24725   }
24726 
24727   return DAG.getNode(Opc, dl, VT, SrcOp,
24728                      DAG.getTargetConstant(ShiftAmt, dl, MVT::i8));
24729 }
24730 
24731 /// Handle vector element shifts where the shift amount may or may not be a
24732 /// constant. Takes immediate version of shift as input.
24733 static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
24734                                    SDValue SrcOp, SDValue ShAmt,
24735                                    const X86Subtarget &Subtarget,
24736                                    SelectionDAG &DAG) {
24737   MVT SVT = ShAmt.getSimpleValueType();
24738   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
24739 
24740   // Catch shift-by-constant.
24741   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
24742     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
24743                                       CShAmt->getZExtValue(), DAG);
24744 
24745   // Change opcode to non-immediate version.
24746   Opc = getTargetVShiftUniformOpcode(Opc, true);
24747 
24748   // Need to build a vector containing shift amount.
24749   // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
24750   // +====================+============+=======================================+
24751   // | ShAmt is           | HasSSE4.1? | Construct ShAmt vector as             |
24752   // +====================+============+=======================================+
24753   // | i64                | Yes, No    | Use ShAmt as lowest elt               |
24754   // | i32                | Yes        | zero-extend in-reg                    |
24755   // | (i32 zext(i16/i8)) | Yes        | zero-extend in-reg                    |
24756   // | (i32 zext(i16/i8)) | No         | byte-shift-in-reg                     |
24757   // | i16/i32            | No         | v4i32 build_vector(ShAmt, 0, ud, ud)) |
24758   // +====================+============+=======================================+
24759 
24760   if (SVT == MVT::i64)
24761     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
24762   else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
24763            ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24764            (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
24765             ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
24766     ShAmt = ShAmt.getOperand(0);
24767     MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
24768     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
24769     if (Subtarget.hasSSE41())
24770       ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
24771                           MVT::v2i64, ShAmt);
24772     else {
24773       SDValue ByteShift = DAG.getTargetConstant(
24774           (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
24775       ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
24776       ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
24777                           ByteShift);
24778       ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
24779                           ByteShift);
24780     }
24781   } else if (Subtarget.hasSSE41() &&
24782              ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24783     ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
24784     ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
24785                         MVT::v2i64, ShAmt);
24786   } else {
24787     SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
24788                         DAG.getUNDEF(SVT)};
24789     ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
24790   }
24791 
24792   // The return type has to be a 128-bit type with the same element
24793   // type as the input type.
24794   MVT EltVT = VT.getVectorElementType();
24795   MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
24796 
24797   ShAmt = DAG.getBitcast(ShVT, ShAmt);
24798   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
24799 }
24800 
24801 /// Return Mask with the necessary casting or extending
24802 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
24803 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
24804                            const X86Subtarget &Subtarget, SelectionDAG &DAG,
24805                            const SDLoc &dl) {
24806 
24807   if (isAllOnesConstant(Mask))
24808     return DAG.getConstant(1, dl, MaskVT);
24809   if (X86::isZeroNode(Mask))
24810     return DAG.getConstant(0, dl, MaskVT);
24811 
24812   assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!");
24813 
24814   if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
24815     assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!");
24816     assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
24817     // In case 32bit mode, bitcast i64 is illegal, extend/split it.
24818     SDValue Lo, Hi;
24819     Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
24820                         DAG.getConstant(0, dl, MVT::i32));
24821     Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
24822                         DAG.getConstant(1, dl, MVT::i32));
24823 
24824     Lo = DAG.getBitcast(MVT::v32i1, Lo);
24825     Hi = DAG.getBitcast(MVT::v32i1, Hi);
24826 
24827     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
24828   } else {
24829     MVT BitcastVT = MVT::getVectorVT(MVT::i1,
24830                                      Mask.getSimpleValueType().getSizeInBits());
24831     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
24832     // are extracted by EXTRACT_SUBVECTOR.
24833     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
24834                        DAG.getBitcast(BitcastVT, Mask),
24835                        DAG.getIntPtrConstant(0, dl));
24836   }
24837 }
24838 
24839 /// Return (and \p Op, \p Mask) for compare instructions or
24840 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
24841 /// necessary casting or extending for \p Mask when lowering masking intrinsics
24842 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
24843                   SDValue PreservedSrc,
24844                   const X86Subtarget &Subtarget,
24845                   SelectionDAG &DAG) {
24846   MVT VT = Op.getSimpleValueType();
24847   MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
24848   unsigned OpcodeSelect = ISD::VSELECT;
24849   SDLoc dl(Op);
24850 
24851   if (isAllOnesConstant(Mask))
24852     return Op;
24853 
24854   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
24855 
24856   if (PreservedSrc.isUndef())
24857     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
24858   return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
24859 }
24860 
24861 /// Creates an SDNode for a predicated scalar operation.
24862 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
24863 /// The mask is coming as MVT::i8 and it should be transformed
24864 /// to MVT::v1i1 while lowering masking intrinsics.
24865 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
24866 /// "X86select" instead of "vselect". We just can't create the "vselect" node
24867 /// for a scalar instruction.
24868 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
24869                                     SDValue PreservedSrc,
24870                                     const X86Subtarget &Subtarget,
24871                                     SelectionDAG &DAG) {
24872 
24873   if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
24874     if (MaskConst->getZExtValue() & 0x1)
24875       return Op;
24876 
24877   MVT VT = Op.getSimpleValueType();
24878   SDLoc dl(Op);
24879 
24880   assert(Mask.getValueType() == MVT::i8 && "Unexpect type");
24881   SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
24882                               DAG.getBitcast(MVT::v8i1, Mask),
24883                               DAG.getIntPtrConstant(0, dl));
24884   if (Op.getOpcode() == X86ISD::FSETCCM ||
24885       Op.getOpcode() == X86ISD::FSETCCM_SAE ||
24886       Op.getOpcode() == X86ISD::VFPCLASSS)
24887     return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
24888 
24889   if (PreservedSrc.isUndef())
24890     PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
24891   return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
24892 }
24893 
24894 static int getSEHRegistrationNodeSize(const Function *Fn) {
24895   if (!Fn->hasPersonalityFn())
24896     report_fatal_error(
24897         "querying registration node size for function without personality");
24898   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
24899   // WinEHStatePass for the full struct definition.
24900   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
24901   case EHPersonality::MSVC_X86SEH: return 24;
24902   case EHPersonality::MSVC_CXX: return 16;
24903   default: break;
24904   }
24905   report_fatal_error(
24906       "can only recover FP for 32-bit MSVC EH personality functions");
24907 }
24908 
24909 /// When the MSVC runtime transfers control to us, either to an outlined
24910 /// function or when returning to a parent frame after catching an exception, we
24911 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
24912 /// Here's the math:
24913 ///   RegNodeBase = EntryEBP - RegNodeSize
24914 ///   ParentFP = RegNodeBase - ParentFrameOffset
24915 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
24916 /// subtracting the offset (negative on x86) takes us back to the parent FP.
24917 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
24918                                    SDValue EntryEBP) {
24919   MachineFunction &MF = DAG.getMachineFunction();
24920   SDLoc dl;
24921 
24922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24923   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24924 
24925   // It's possible that the parent function no longer has a personality function
24926   // if the exceptional code was optimized away, in which case we just return
24927   // the incoming EBP.
24928   if (!Fn->hasPersonalityFn())
24929     return EntryEBP;
24930 
24931   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
24932   // registration, or the .set_setframe offset.
24933   MCSymbol *OffsetSym =
24934       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
24935           GlobalValue::dropLLVMManglingEscape(Fn->getName()));
24936   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
24937   SDValue ParentFrameOffset =
24938       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
24939 
24940   // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
24941   // prologue to RBP in the parent function.
24942   const X86Subtarget &Subtarget =
24943       static_cast<const X86Subtarget &>(DAG.getSubtarget());
24944   if (Subtarget.is64Bit())
24945     return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
24946 
24947   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
24948   // RegNodeBase = EntryEBP - RegNodeSize
24949   // ParentFP = RegNodeBase - ParentFrameOffset
24950   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
24951                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
24952   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
24953 }
24954 
24955 SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
24956                                                    SelectionDAG &DAG) const {
24957   // Helper to detect if the operand is CUR_DIRECTION rounding mode.
24958   auto isRoundModeCurDirection = [](SDValue Rnd) {
24959     if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
24960       return C->getAPIntValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
24961 
24962     return false;
24963   };
24964   auto isRoundModeSAE = [](SDValue Rnd) {
24965     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
24966       unsigned RC = C->getZExtValue();
24967       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
24968         // Clear the NO_EXC bit and check remaining bits.
24969         RC ^= X86::STATIC_ROUNDING::NO_EXC;
24970         // As a convenience we allow no other bits or explicitly
24971         // current direction.
24972         return RC == 0 || RC == X86::STATIC_ROUNDING::CUR_DIRECTION;
24973       }
24974     }
24975 
24976     return false;
24977   };
24978   auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
24979     if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
24980       RC = C->getZExtValue();
24981       if (RC & X86::STATIC_ROUNDING::NO_EXC) {
24982         // Clear the NO_EXC bit and check remaining bits.
24983         RC ^= X86::STATIC_ROUNDING::NO_EXC;
24984         return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
24985                RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
24986                RC == X86::STATIC_ROUNDING::TO_POS_INF ||
24987                RC == X86::STATIC_ROUNDING::TO_ZERO;
24988       }
24989     }
24990 
24991     return false;
24992   };
24993 
24994   SDLoc dl(Op);
24995   unsigned IntNo = Op.getConstantOperandVal(0);
24996   MVT VT = Op.getSimpleValueType();
24997   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
24998 
24999   if (IntrData) {
25000     switch(IntrData->Type) {
25001     case INTR_TYPE_1OP: {
25002       // We specify 2 possible opcodes for intrinsics with rounding modes.
25003       // First, we check if the intrinsic may have non-default rounding mode,
25004       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25005       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25006       if (IntrWithRoundingModeOpcode != 0) {
25007         SDValue Rnd = Op.getOperand(2);
25008         unsigned RC = 0;
25009         if (isRoundModeSAEToX(Rnd, RC))
25010           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25011                              Op.getOperand(1),
25012                              DAG.getTargetConstant(RC, dl, MVT::i32));
25013         if (!isRoundModeCurDirection(Rnd))
25014           return SDValue();
25015       }
25016       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25017                          Op.getOperand(1));
25018     }
25019     case INTR_TYPE_1OP_SAE: {
25020       SDValue Sae = Op.getOperand(2);
25021 
25022       unsigned Opc;
25023       if (isRoundModeCurDirection(Sae))
25024         Opc = IntrData->Opc0;
25025       else if (isRoundModeSAE(Sae))
25026         Opc = IntrData->Opc1;
25027       else
25028         return SDValue();
25029 
25030       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
25031     }
25032     case INTR_TYPE_2OP: {
25033       SDValue Src2 = Op.getOperand(2);
25034 
25035       // We specify 2 possible opcodes for intrinsics with rounding modes.
25036       // First, we check if the intrinsic may have non-default rounding mode,
25037       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25038       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25039       if (IntrWithRoundingModeOpcode != 0) {
25040         SDValue Rnd = Op.getOperand(3);
25041         unsigned RC = 0;
25042         if (isRoundModeSAEToX(Rnd, RC))
25043           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25044                              Op.getOperand(1), Src2,
25045                              DAG.getTargetConstant(RC, dl, MVT::i32));
25046         if (!isRoundModeCurDirection(Rnd))
25047           return SDValue();
25048       }
25049 
25050       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25051                          Op.getOperand(1), Src2);
25052     }
25053     case INTR_TYPE_2OP_SAE: {
25054       SDValue Sae = Op.getOperand(3);
25055 
25056       unsigned Opc;
25057       if (isRoundModeCurDirection(Sae))
25058         Opc = IntrData->Opc0;
25059       else if (isRoundModeSAE(Sae))
25060         Opc = IntrData->Opc1;
25061       else
25062         return SDValue();
25063 
25064       return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
25065                          Op.getOperand(2));
25066     }
25067     case INTR_TYPE_3OP:
25068     case INTR_TYPE_3OP_IMM8: {
25069       SDValue Src1 = Op.getOperand(1);
25070       SDValue Src2 = Op.getOperand(2);
25071       SDValue Src3 = Op.getOperand(3);
25072 
25073       if (IntrData->Type == INTR_TYPE_3OP_IMM8 &&
25074           Src3.getValueType() != MVT::i8) {
25075         Src3 = DAG.getTargetConstant(
25076             cast<ConstantSDNode>(Src3)->getZExtValue() & 0xff, dl, MVT::i8);
25077       }
25078 
25079       // We specify 2 possible opcodes for intrinsics with rounding modes.
25080       // First, we check if the intrinsic may have non-default rounding mode,
25081       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25082       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25083       if (IntrWithRoundingModeOpcode != 0) {
25084         SDValue Rnd = Op.getOperand(4);
25085         unsigned RC = 0;
25086         if (isRoundModeSAEToX(Rnd, RC))
25087           return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25088                              Src1, Src2, Src3,
25089                              DAG.getTargetConstant(RC, dl, MVT::i32));
25090         if (!isRoundModeCurDirection(Rnd))
25091           return SDValue();
25092       }
25093 
25094       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25095                          {Src1, Src2, Src3});
25096     }
25097     case INTR_TYPE_4OP_IMM8: {
25098       assert(Op.getOperand(4)->getOpcode() == ISD::TargetConstant);
25099       SDValue Src4 = Op.getOperand(4);
25100       if (Src4.getValueType() != MVT::i8) {
25101         Src4 = DAG.getTargetConstant(
25102             cast<ConstantSDNode>(Src4)->getZExtValue() & 0xff, dl, MVT::i8);
25103       }
25104 
25105       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25106                          Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
25107                          Src4);
25108     }
25109     case INTR_TYPE_1OP_MASK: {
25110       SDValue Src = Op.getOperand(1);
25111       SDValue PassThru = Op.getOperand(2);
25112       SDValue Mask = Op.getOperand(3);
25113       // We add rounding mode to the Node when
25114       //   - RC Opcode is specified and
25115       //   - RC is not "current direction".
25116       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25117       if (IntrWithRoundingModeOpcode != 0) {
25118         SDValue Rnd = Op.getOperand(4);
25119         unsigned RC = 0;
25120         if (isRoundModeSAEToX(Rnd, RC))
25121           return getVectorMaskingNode(
25122               DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
25123                           Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
25124               Mask, PassThru, Subtarget, DAG);
25125         if (!isRoundModeCurDirection(Rnd))
25126           return SDValue();
25127       }
25128       return getVectorMaskingNode(
25129           DAG.getNode(IntrData->Opc0, dl, VT, Src), Mask, PassThru,
25130           Subtarget, DAG);
25131     }
25132     case INTR_TYPE_1OP_MASK_SAE: {
25133       SDValue Src = Op.getOperand(1);
25134       SDValue PassThru = Op.getOperand(2);
25135       SDValue Mask = Op.getOperand(3);
25136       SDValue Rnd = Op.getOperand(4);
25137 
25138       unsigned Opc;
25139       if (isRoundModeCurDirection(Rnd))
25140         Opc = IntrData->Opc0;
25141       else if (isRoundModeSAE(Rnd))
25142         Opc = IntrData->Opc1;
25143       else
25144         return SDValue();
25145 
25146       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src), Mask, PassThru,
25147                                   Subtarget, DAG);
25148     }
25149     case INTR_TYPE_SCALAR_MASK: {
25150       SDValue Src1 = Op.getOperand(1);
25151       SDValue Src2 = Op.getOperand(2);
25152       SDValue passThru = Op.getOperand(3);
25153       SDValue Mask = Op.getOperand(4);
25154       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
25155       // There are 2 kinds of intrinsics in this group:
25156       // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
25157       // (2) With rounding mode and sae - 7 operands.
25158       bool HasRounding = IntrWithRoundingModeOpcode != 0;
25159       if (Op.getNumOperands() == (5U + HasRounding)) {
25160         if (HasRounding) {
25161           SDValue Rnd = Op.getOperand(5);
25162           unsigned RC = 0;
25163           if (isRoundModeSAEToX(Rnd, RC))
25164             return getScalarMaskingNode(
25165                 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
25166                             DAG.getTargetConstant(RC, dl, MVT::i32)),
25167                 Mask, passThru, Subtarget, DAG);
25168           if (!isRoundModeCurDirection(Rnd))
25169             return SDValue();
25170         }
25171         return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
25172                                                 Src2),
25173                                     Mask, passThru, Subtarget, DAG);
25174       }
25175 
25176       assert(Op.getNumOperands() == (6U + HasRounding) &&
25177              "Unexpected intrinsic form");
25178       SDValue RoundingMode = Op.getOperand(5);
25179       unsigned Opc = IntrData->Opc0;
25180       if (HasRounding) {
25181         SDValue Sae = Op.getOperand(6);
25182         if (isRoundModeSAE(Sae))
25183           Opc = IntrWithRoundingModeOpcode;
25184         else if (!isRoundModeCurDirection(Sae))
25185           return SDValue();
25186       }
25187       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
25188                                               Src2, RoundingMode),
25189                                   Mask, passThru, Subtarget, DAG);
25190     }
25191     case INTR_TYPE_SCALAR_MASK_RND: {
25192       SDValue Src1 = Op.getOperand(1);
25193       SDValue Src2 = Op.getOperand(2);
25194       SDValue passThru = Op.getOperand(3);
25195       SDValue Mask = Op.getOperand(4);
25196       SDValue Rnd = Op.getOperand(5);
25197 
25198       SDValue NewOp;
25199       unsigned RC = 0;
25200       if (isRoundModeCurDirection(Rnd))
25201         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
25202       else if (isRoundModeSAEToX(Rnd, RC))
25203         NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
25204                             DAG.getTargetConstant(RC, dl, MVT::i32));
25205       else
25206         return SDValue();
25207 
25208       return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
25209     }
25210     case INTR_TYPE_SCALAR_MASK_SAE: {
25211       SDValue Src1 = Op.getOperand(1);
25212       SDValue Src2 = Op.getOperand(2);
25213       SDValue passThru = Op.getOperand(3);
25214       SDValue Mask = Op.getOperand(4);
25215       SDValue Sae = Op.getOperand(5);
25216       unsigned Opc;
25217       if (isRoundModeCurDirection(Sae))
25218         Opc = IntrData->Opc0;
25219       else if (isRoundModeSAE(Sae))
25220         Opc = IntrData->Opc1;
25221       else
25222         return SDValue();
25223 
25224       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
25225                                   Mask, passThru, Subtarget, DAG);
25226     }
25227     case INTR_TYPE_2OP_MASK: {
25228       SDValue Src1 = Op.getOperand(1);
25229       SDValue Src2 = Op.getOperand(2);
25230       SDValue PassThru = Op.getOperand(3);
25231       SDValue Mask = Op.getOperand(4);
25232       SDValue NewOp;
25233       if (IntrData->Opc1 != 0) {
25234         SDValue Rnd = Op.getOperand(5);
25235         unsigned RC = 0;
25236         if (isRoundModeSAEToX(Rnd, RC))
25237           NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
25238                               DAG.getTargetConstant(RC, dl, MVT::i32));
25239         else if (!isRoundModeCurDirection(Rnd))
25240           return SDValue();
25241       }
25242       if (!NewOp)
25243         NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
25244       return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
25245     }
25246     case INTR_TYPE_2OP_MASK_SAE: {
25247       SDValue Src1 = Op.getOperand(1);
25248       SDValue Src2 = Op.getOperand(2);
25249       SDValue PassThru = Op.getOperand(3);
25250       SDValue Mask = Op.getOperand(4);
25251 
25252       unsigned Opc = IntrData->Opc0;
25253       if (IntrData->Opc1 != 0) {
25254         SDValue Sae = Op.getOperand(5);
25255         if (isRoundModeSAE(Sae))
25256           Opc = IntrData->Opc1;
25257         else if (!isRoundModeCurDirection(Sae))
25258           return SDValue();
25259       }
25260 
25261       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
25262                                   Mask, PassThru, Subtarget, DAG);
25263     }
25264     case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
25265       SDValue Src1 = Op.getOperand(1);
25266       SDValue Src2 = Op.getOperand(2);
25267       SDValue Src3 = Op.getOperand(3);
25268       SDValue PassThru = Op.getOperand(4);
25269       SDValue Mask = Op.getOperand(5);
25270       SDValue Sae = Op.getOperand(6);
25271       unsigned Opc;
25272       if (isRoundModeCurDirection(Sae))
25273         Opc = IntrData->Opc0;
25274       else if (isRoundModeSAE(Sae))
25275         Opc = IntrData->Opc1;
25276       else
25277         return SDValue();
25278 
25279       return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
25280                                   Mask, PassThru, Subtarget, DAG);
25281     }
25282     case INTR_TYPE_3OP_MASK_SAE: {
25283       SDValue Src1 = Op.getOperand(1);
25284       SDValue Src2 = Op.getOperand(2);
25285       SDValue Src3 = Op.getOperand(3);
25286       SDValue PassThru = Op.getOperand(4);
25287       SDValue Mask = Op.getOperand(5);
25288 
25289       unsigned Opc = IntrData->Opc0;
25290       if (IntrData->Opc1 != 0) {
25291         SDValue Sae = Op.getOperand(6);
25292         if (isRoundModeSAE(Sae))
25293           Opc = IntrData->Opc1;
25294         else if (!isRoundModeCurDirection(Sae))
25295           return SDValue();
25296       }
25297       return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
25298                                   Mask, PassThru, Subtarget, DAG);
25299     }
25300     case BLENDV: {
25301       SDValue Src1 = Op.getOperand(1);
25302       SDValue Src2 = Op.getOperand(2);
25303       SDValue Src3 = Op.getOperand(3);
25304 
25305       EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
25306       Src3 = DAG.getBitcast(MaskVT, Src3);
25307 
25308       // Reverse the operands to match VSELECT order.
25309       return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
25310     }
25311     case VPERM_2OP : {
25312       SDValue Src1 = Op.getOperand(1);
25313       SDValue Src2 = Op.getOperand(2);
25314 
25315       // Swap Src1 and Src2 in the node creation
25316       return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
25317     }
25318     case IFMA_OP:
25319       // NOTE: We need to swizzle the operands to pass the multiply operands
25320       // first.
25321       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25322                          Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
25323     case FPCLASSS: {
25324       SDValue Src1 = Op.getOperand(1);
25325       SDValue Imm = Op.getOperand(2);
25326       SDValue Mask = Op.getOperand(3);
25327       SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
25328       SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
25329                                                  Subtarget, DAG);
25330       // Need to fill with zeros to ensure the bitcast will produce zeroes
25331       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25332       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
25333                                 DAG.getConstant(0, dl, MVT::v8i1),
25334                                 FPclassMask, DAG.getIntPtrConstant(0, dl));
25335       return DAG.getBitcast(MVT::i8, Ins);
25336     }
25337 
25338     case CMP_MASK_CC: {
25339       MVT MaskVT = Op.getSimpleValueType();
25340       SDValue CC = Op.getOperand(3);
25341       SDValue Mask = Op.getOperand(4);
25342       // We specify 2 possible opcodes for intrinsics with rounding modes.
25343       // First, we check if the intrinsic may have non-default rounding mode,
25344       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
25345       if (IntrData->Opc1 != 0) {
25346         SDValue Sae = Op.getOperand(5);
25347         if (isRoundModeSAE(Sae))
25348           return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
25349                              Op.getOperand(2), CC, Mask, Sae);
25350         if (!isRoundModeCurDirection(Sae))
25351           return SDValue();
25352       }
25353       //default rounding mode
25354       return DAG.getNode(IntrData->Opc0, dl, MaskVT,
25355                          {Op.getOperand(1), Op.getOperand(2), CC, Mask});
25356     }
25357     case CMP_MASK_SCALAR_CC: {
25358       SDValue Src1 = Op.getOperand(1);
25359       SDValue Src2 = Op.getOperand(2);
25360       SDValue CC = Op.getOperand(3);
25361       SDValue Mask = Op.getOperand(4);
25362 
25363       SDValue Cmp;
25364       if (IntrData->Opc1 != 0) {
25365         SDValue Sae = Op.getOperand(5);
25366         if (isRoundModeSAE(Sae))
25367           Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
25368         else if (!isRoundModeCurDirection(Sae))
25369           return SDValue();
25370       }
25371       //default rounding mode
25372       if (!Cmp.getNode())
25373         Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
25374 
25375       SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
25376                                              Subtarget, DAG);
25377       // Need to fill with zeros to ensure the bitcast will produce zeroes
25378       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25379       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
25380                                 DAG.getConstant(0, dl, MVT::v8i1),
25381                                 CmpMask, DAG.getIntPtrConstant(0, dl));
25382       return DAG.getBitcast(MVT::i8, Ins);
25383     }
25384     case COMI: { // Comparison intrinsics
25385       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
25386       SDValue LHS = Op.getOperand(1);
25387       SDValue RHS = Op.getOperand(2);
25388       // Some conditions require the operands to be swapped.
25389       if (CC == ISD::SETLT || CC == ISD::SETLE)
25390         std::swap(LHS, RHS);
25391 
25392       SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
25393       SDValue SetCC;
25394       switch (CC) {
25395       case ISD::SETEQ: { // (ZF = 0 and PF = 0)
25396         SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
25397         SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
25398         SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
25399         break;
25400       }
25401       case ISD::SETNE: { // (ZF = 1 or PF = 1)
25402         SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
25403         SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
25404         SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
25405         break;
25406       }
25407       case ISD::SETGT: // (CF = 0 and ZF = 0)
25408       case ISD::SETLT: { // Condition opposite to GT. Operands swapped above.
25409         SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
25410         break;
25411       }
25412       case ISD::SETGE: // CF = 0
25413       case ISD::SETLE: // Condition opposite to GE. Operands swapped above.
25414         SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
25415         break;
25416       default:
25417         llvm_unreachable("Unexpected illegal condition!");
25418       }
25419       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25420     }
25421     case COMI_RM: { // Comparison intrinsics with Sae
25422       SDValue LHS = Op.getOperand(1);
25423       SDValue RHS = Op.getOperand(2);
25424       unsigned CondVal = Op.getConstantOperandVal(3);
25425       SDValue Sae = Op.getOperand(4);
25426 
25427       SDValue FCmp;
25428       if (isRoundModeCurDirection(Sae))
25429         FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
25430                            DAG.getTargetConstant(CondVal, dl, MVT::i8));
25431       else if (isRoundModeSAE(Sae))
25432         FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
25433                            DAG.getTargetConstant(CondVal, dl, MVT::i8), Sae);
25434       else
25435         return SDValue();
25436       // Need to fill with zeros to ensure the bitcast will produce zeroes
25437       // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
25438       SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
25439                                 DAG.getConstant(0, dl, MVT::v16i1),
25440                                 FCmp, DAG.getIntPtrConstant(0, dl));
25441       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
25442                          DAG.getBitcast(MVT::i16, Ins));
25443     }
25444     case VSHIFT:
25445       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
25446                                  Op.getOperand(1), Op.getOperand(2), Subtarget,
25447                                  DAG);
25448     case COMPRESS_EXPAND_IN_REG: {
25449       SDValue Mask = Op.getOperand(3);
25450       SDValue DataToCompress = Op.getOperand(1);
25451       SDValue PassThru = Op.getOperand(2);
25452       if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
25453         return Op.getOperand(1);
25454 
25455       // Avoid false dependency.
25456       if (PassThru.isUndef())
25457         PassThru = DAG.getConstant(0, dl, VT);
25458 
25459       return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
25460                          Mask);
25461     }
25462     case FIXUPIMM:
25463     case FIXUPIMM_MASKZ: {
25464       SDValue Src1 = Op.getOperand(1);
25465       SDValue Src2 = Op.getOperand(2);
25466       SDValue Src3 = Op.getOperand(3);
25467       SDValue Imm = Op.getOperand(4);
25468       SDValue Mask = Op.getOperand(5);
25469       SDValue Passthru = (IntrData->Type == FIXUPIMM)
25470                              ? Src1
25471                              : getZeroVector(VT, Subtarget, DAG, dl);
25472 
25473       unsigned Opc = IntrData->Opc0;
25474       if (IntrData->Opc1 != 0) {
25475         SDValue Sae = Op.getOperand(6);
25476         if (isRoundModeSAE(Sae))
25477           Opc = IntrData->Opc1;
25478         else if (!isRoundModeCurDirection(Sae))
25479           return SDValue();
25480       }
25481 
25482       SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
25483 
25484       if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
25485         return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
25486 
25487       return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
25488     }
25489     case ROUNDP: {
25490       assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode");
25491       // Clear the upper bits of the rounding immediate so that the legacy
25492       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
25493       auto Round = cast<ConstantSDNode>(Op.getOperand(2));
25494       SDValue RoundingMode =
25495           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
25496       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25497                          Op.getOperand(1), RoundingMode);
25498     }
25499     case ROUNDS: {
25500       assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode");
25501       // Clear the upper bits of the rounding immediate so that the legacy
25502       // intrinsic can't trigger the scaling behavior of VRNDSCALE.
25503       auto Round = cast<ConstantSDNode>(Op.getOperand(3));
25504       SDValue RoundingMode =
25505           DAG.getTargetConstant(Round->getZExtValue() & 0xf, dl, MVT::i32);
25506       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25507                          Op.getOperand(1), Op.getOperand(2), RoundingMode);
25508     }
25509     case BEXTRI: {
25510       assert(IntrData->Opc0 == X86ISD::BEXTRI && "Unexpected opcode");
25511 
25512       uint64_t Imm = Op.getConstantOperandVal(2);
25513       SDValue Control = DAG.getTargetConstant(Imm & 0xffff, dl,
25514                                               Op.getValueType());
25515       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
25516                          Op.getOperand(1), Control);
25517     }
25518     // ADC/ADCX/SBB
25519     case ADX: {
25520       SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
25521       SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
25522 
25523       SDValue Res;
25524       // If the carry in is zero, then we should just use ADD/SUB instead of
25525       // ADC/SBB.
25526       if (isNullConstant(Op.getOperand(1))) {
25527         Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
25528                           Op.getOperand(3));
25529       } else {
25530         SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
25531                                     DAG.getConstant(-1, dl, MVT::i8));
25532         Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
25533                           Op.getOperand(3), GenCF.getValue(1));
25534       }
25535       SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
25536       SDValue Results[] = { SetCC, Res };
25537       return DAG.getMergeValues(Results, dl);
25538     }
25539     case CVTPD2PS_MASK:
25540     case CVTPD2DQ_MASK:
25541     case CVTQQ2PS_MASK:
25542     case TRUNCATE_TO_REG: {
25543       SDValue Src = Op.getOperand(1);
25544       SDValue PassThru = Op.getOperand(2);
25545       SDValue Mask = Op.getOperand(3);
25546 
25547       if (isAllOnesConstant(Mask))
25548         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
25549 
25550       MVT SrcVT = Src.getSimpleValueType();
25551       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
25552       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25553       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(),
25554                          {Src, PassThru, Mask});
25555     }
25556     case CVTPS2PH_MASK: {
25557       SDValue Src = Op.getOperand(1);
25558       SDValue Rnd = Op.getOperand(2);
25559       SDValue PassThru = Op.getOperand(3);
25560       SDValue Mask = Op.getOperand(4);
25561 
25562       if (isAllOnesConstant(Mask))
25563         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
25564 
25565       MVT SrcVT = Src.getSimpleValueType();
25566       MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
25567       Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25568       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
25569                          PassThru, Mask);
25570 
25571     }
25572     case CVTNEPS2BF16_MASK: {
25573       SDValue Src = Op.getOperand(1);
25574       SDValue PassThru = Op.getOperand(2);
25575       SDValue Mask = Op.getOperand(3);
25576 
25577       if (ISD::isBuildVectorAllOnes(Mask.getNode()))
25578         return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
25579 
25580       // Break false dependency.
25581       if (PassThru.isUndef())
25582         PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
25583 
25584       return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
25585                          Mask);
25586     }
25587     default:
25588       break;
25589     }
25590   }
25591 
25592   switch (IntNo) {
25593   default: return SDValue();    // Don't custom lower most intrinsics.
25594 
25595   // ptest and testp intrinsics. The intrinsic these come from are designed to
25596   // return an integer value, not just an instruction so lower it to the ptest
25597   // or testp pattern and a setcc for the result.
25598   case Intrinsic::x86_avx512_ktestc_b:
25599   case Intrinsic::x86_avx512_ktestc_w:
25600   case Intrinsic::x86_avx512_ktestc_d:
25601   case Intrinsic::x86_avx512_ktestc_q:
25602   case Intrinsic::x86_avx512_ktestz_b:
25603   case Intrinsic::x86_avx512_ktestz_w:
25604   case Intrinsic::x86_avx512_ktestz_d:
25605   case Intrinsic::x86_avx512_ktestz_q:
25606   case Intrinsic::x86_sse41_ptestz:
25607   case Intrinsic::x86_sse41_ptestc:
25608   case Intrinsic::x86_sse41_ptestnzc:
25609   case Intrinsic::x86_avx_ptestz_256:
25610   case Intrinsic::x86_avx_ptestc_256:
25611   case Intrinsic::x86_avx_ptestnzc_256:
25612   case Intrinsic::x86_avx_vtestz_ps:
25613   case Intrinsic::x86_avx_vtestc_ps:
25614   case Intrinsic::x86_avx_vtestnzc_ps:
25615   case Intrinsic::x86_avx_vtestz_pd:
25616   case Intrinsic::x86_avx_vtestc_pd:
25617   case Intrinsic::x86_avx_vtestnzc_pd:
25618   case Intrinsic::x86_avx_vtestz_ps_256:
25619   case Intrinsic::x86_avx_vtestc_ps_256:
25620   case Intrinsic::x86_avx_vtestnzc_ps_256:
25621   case Intrinsic::x86_avx_vtestz_pd_256:
25622   case Intrinsic::x86_avx_vtestc_pd_256:
25623   case Intrinsic::x86_avx_vtestnzc_pd_256: {
25624     unsigned TestOpc = X86ISD::PTEST;
25625     X86::CondCode X86CC;
25626     switch (IntNo) {
25627     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
25628     case Intrinsic::x86_avx512_ktestc_b:
25629     case Intrinsic::x86_avx512_ktestc_w:
25630     case Intrinsic::x86_avx512_ktestc_d:
25631     case Intrinsic::x86_avx512_ktestc_q:
25632       // CF = 1
25633       TestOpc = X86ISD::KTEST;
25634       X86CC = X86::COND_B;
25635       break;
25636     case Intrinsic::x86_avx512_ktestz_b:
25637     case Intrinsic::x86_avx512_ktestz_w:
25638     case Intrinsic::x86_avx512_ktestz_d:
25639     case Intrinsic::x86_avx512_ktestz_q:
25640       TestOpc = X86ISD::KTEST;
25641       X86CC = X86::COND_E;
25642       break;
25643     case Intrinsic::x86_avx_vtestz_ps:
25644     case Intrinsic::x86_avx_vtestz_pd:
25645     case Intrinsic::x86_avx_vtestz_ps_256:
25646     case Intrinsic::x86_avx_vtestz_pd_256:
25647       TestOpc = X86ISD::TESTP;
25648       LLVM_FALLTHROUGH;
25649     case Intrinsic::x86_sse41_ptestz:
25650     case Intrinsic::x86_avx_ptestz_256:
25651       // ZF = 1
25652       X86CC = X86::COND_E;
25653       break;
25654     case Intrinsic::x86_avx_vtestc_ps:
25655     case Intrinsic::x86_avx_vtestc_pd:
25656     case Intrinsic::x86_avx_vtestc_ps_256:
25657     case Intrinsic::x86_avx_vtestc_pd_256:
25658       TestOpc = X86ISD::TESTP;
25659       LLVM_FALLTHROUGH;
25660     case Intrinsic::x86_sse41_ptestc:
25661     case Intrinsic::x86_avx_ptestc_256:
25662       // CF = 1
25663       X86CC = X86::COND_B;
25664       break;
25665     case Intrinsic::x86_avx_vtestnzc_ps:
25666     case Intrinsic::x86_avx_vtestnzc_pd:
25667     case Intrinsic::x86_avx_vtestnzc_ps_256:
25668     case Intrinsic::x86_avx_vtestnzc_pd_256:
25669       TestOpc = X86ISD::TESTP;
25670       LLVM_FALLTHROUGH;
25671     case Intrinsic::x86_sse41_ptestnzc:
25672     case Intrinsic::x86_avx_ptestnzc_256:
25673       // ZF and CF = 0
25674       X86CC = X86::COND_A;
25675       break;
25676     }
25677 
25678     SDValue LHS = Op.getOperand(1);
25679     SDValue RHS = Op.getOperand(2);
25680     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
25681     SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
25682     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25683   }
25684 
25685   case Intrinsic::x86_sse42_pcmpistria128:
25686   case Intrinsic::x86_sse42_pcmpestria128:
25687   case Intrinsic::x86_sse42_pcmpistric128:
25688   case Intrinsic::x86_sse42_pcmpestric128:
25689   case Intrinsic::x86_sse42_pcmpistrio128:
25690   case Intrinsic::x86_sse42_pcmpestrio128:
25691   case Intrinsic::x86_sse42_pcmpistris128:
25692   case Intrinsic::x86_sse42_pcmpestris128:
25693   case Intrinsic::x86_sse42_pcmpistriz128:
25694   case Intrinsic::x86_sse42_pcmpestriz128: {
25695     unsigned Opcode;
25696     X86::CondCode X86CC;
25697     switch (IntNo) {
25698     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
25699     case Intrinsic::x86_sse42_pcmpistria128:
25700       Opcode = X86ISD::PCMPISTR;
25701       X86CC = X86::COND_A;
25702       break;
25703     case Intrinsic::x86_sse42_pcmpestria128:
25704       Opcode = X86ISD::PCMPESTR;
25705       X86CC = X86::COND_A;
25706       break;
25707     case Intrinsic::x86_sse42_pcmpistric128:
25708       Opcode = X86ISD::PCMPISTR;
25709       X86CC = X86::COND_B;
25710       break;
25711     case Intrinsic::x86_sse42_pcmpestric128:
25712       Opcode = X86ISD::PCMPESTR;
25713       X86CC = X86::COND_B;
25714       break;
25715     case Intrinsic::x86_sse42_pcmpistrio128:
25716       Opcode = X86ISD::PCMPISTR;
25717       X86CC = X86::COND_O;
25718       break;
25719     case Intrinsic::x86_sse42_pcmpestrio128:
25720       Opcode = X86ISD::PCMPESTR;
25721       X86CC = X86::COND_O;
25722       break;
25723     case Intrinsic::x86_sse42_pcmpistris128:
25724       Opcode = X86ISD::PCMPISTR;
25725       X86CC = X86::COND_S;
25726       break;
25727     case Intrinsic::x86_sse42_pcmpestris128:
25728       Opcode = X86ISD::PCMPESTR;
25729       X86CC = X86::COND_S;
25730       break;
25731     case Intrinsic::x86_sse42_pcmpistriz128:
25732       Opcode = X86ISD::PCMPISTR;
25733       X86CC = X86::COND_E;
25734       break;
25735     case Intrinsic::x86_sse42_pcmpestriz128:
25736       Opcode = X86ISD::PCMPESTR;
25737       X86CC = X86::COND_E;
25738       break;
25739     }
25740     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25741     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25742     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
25743     SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
25744     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
25745   }
25746 
25747   case Intrinsic::x86_sse42_pcmpistri128:
25748   case Intrinsic::x86_sse42_pcmpestri128: {
25749     unsigned Opcode;
25750     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
25751       Opcode = X86ISD::PCMPISTR;
25752     else
25753       Opcode = X86ISD::PCMPESTR;
25754 
25755     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25756     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25757     return DAG.getNode(Opcode, dl, VTs, NewOps);
25758   }
25759 
25760   case Intrinsic::x86_sse42_pcmpistrm128:
25761   case Intrinsic::x86_sse42_pcmpestrm128: {
25762     unsigned Opcode;
25763     if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
25764       Opcode = X86ISD::PCMPISTR;
25765     else
25766       Opcode = X86ISD::PCMPESTR;
25767 
25768     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
25769     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
25770     return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
25771   }
25772 
25773   case Intrinsic::eh_sjlj_lsda: {
25774     MachineFunction &MF = DAG.getMachineFunction();
25775     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25776     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
25777     auto &Context = MF.getMMI().getContext();
25778     MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
25779                                             Twine(MF.getFunctionNumber()));
25780     return DAG.getNode(getGlobalWrapperKind(), dl, VT,
25781                        DAG.getMCSymbol(S, PtrVT));
25782   }
25783 
25784   case Intrinsic::x86_seh_lsda: {
25785     // Compute the symbol for the LSDA. We know it'll get emitted later.
25786     MachineFunction &MF = DAG.getMachineFunction();
25787     SDValue Op1 = Op.getOperand(1);
25788     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
25789     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
25790         GlobalValue::dropLLVMManglingEscape(Fn->getName()));
25791 
25792     // Generate a simple absolute symbol reference. This intrinsic is only
25793     // supported on 32-bit Windows, which isn't PIC.
25794     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
25795     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
25796   }
25797 
25798   case Intrinsic::eh_recoverfp: {
25799     SDValue FnOp = Op.getOperand(1);
25800     SDValue IncomingFPOp = Op.getOperand(2);
25801     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
25802     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
25803     if (!Fn)
25804       report_fatal_error(
25805           "llvm.eh.recoverfp must take a function as the first argument");
25806     return recoverFramePointer(DAG, Fn, IncomingFPOp);
25807   }
25808 
25809   case Intrinsic::localaddress: {
25810     // Returns one of the stack, base, or frame pointer registers, depending on
25811     // which is used to reference local variables.
25812     MachineFunction &MF = DAG.getMachineFunction();
25813     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
25814     unsigned Reg;
25815     if (RegInfo->hasBasePointer(MF))
25816       Reg = RegInfo->getBaseRegister();
25817     else { // Handles the SP or FP case.
25818       bool CantUseFP = RegInfo->needsStackRealignment(MF);
25819       if (CantUseFP)
25820         Reg = RegInfo->getPtrSizedStackRegister(MF);
25821       else
25822         Reg = RegInfo->getPtrSizedFrameRegister(MF);
25823     }
25824     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
25825   }
25826 
25827   case Intrinsic::x86_avx512_vp2intersect_q_512:
25828   case Intrinsic::x86_avx512_vp2intersect_q_256:
25829   case Intrinsic::x86_avx512_vp2intersect_q_128:
25830   case Intrinsic::x86_avx512_vp2intersect_d_512:
25831   case Intrinsic::x86_avx512_vp2intersect_d_256:
25832   case Intrinsic::x86_avx512_vp2intersect_d_128: {
25833     MVT MaskVT = Op.getSimpleValueType();
25834 
25835     SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
25836     SDLoc DL(Op);
25837 
25838     SDValue Operation =
25839         DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
25840                     Op->getOperand(1), Op->getOperand(2));
25841 
25842     SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
25843                                                  MaskVT, Operation);
25844     SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
25845                                                  MaskVT, Operation);
25846     return DAG.getMergeValues({Result0, Result1}, DL);
25847   }
25848   case Intrinsic::x86_mmx_pslli_w:
25849   case Intrinsic::x86_mmx_pslli_d:
25850   case Intrinsic::x86_mmx_pslli_q:
25851   case Intrinsic::x86_mmx_psrli_w:
25852   case Intrinsic::x86_mmx_psrli_d:
25853   case Intrinsic::x86_mmx_psrli_q:
25854   case Intrinsic::x86_mmx_psrai_w:
25855   case Intrinsic::x86_mmx_psrai_d: {
25856     SDLoc DL(Op);
25857     SDValue ShAmt = Op.getOperand(2);
25858     // If the argument is a constant, convert it to a target constant.
25859     if (auto *C = dyn_cast<ConstantSDNode>(ShAmt)) {
25860       // Clamp out of bounds shift amounts since they will otherwise be masked
25861       // to 8-bits which may make it no longer out of bounds.
25862       unsigned ShiftAmount = C->getAPIntValue().getLimitedValue(255);
25863       if (ShiftAmount == 0)
25864         return Op.getOperand(1);
25865 
25866       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
25867                          Op.getOperand(0), Op.getOperand(1),
25868                          DAG.getTargetConstant(ShiftAmount, DL, MVT::i32));
25869     }
25870 
25871     unsigned NewIntrinsic;
25872     switch (IntNo) {
25873     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
25874     case Intrinsic::x86_mmx_pslli_w:
25875       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
25876       break;
25877     case Intrinsic::x86_mmx_pslli_d:
25878       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
25879       break;
25880     case Intrinsic::x86_mmx_pslli_q:
25881       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
25882       break;
25883     case Intrinsic::x86_mmx_psrli_w:
25884       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
25885       break;
25886     case Intrinsic::x86_mmx_psrli_d:
25887       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
25888       break;
25889     case Intrinsic::x86_mmx_psrli_q:
25890       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
25891       break;
25892     case Intrinsic::x86_mmx_psrai_w:
25893       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
25894       break;
25895     case Intrinsic::x86_mmx_psrai_d:
25896       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
25897       break;
25898     }
25899 
25900     // The vector shift intrinsics with scalars uses 32b shift amounts but
25901     // the sse2/mmx shift instructions reads 64 bits. Copy the 32 bits to an
25902     // MMX register.
25903     ShAmt = DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, ShAmt);
25904     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
25905                        DAG.getTargetConstant(NewIntrinsic, DL,
25906                                              getPointerTy(DAG.getDataLayout())),
25907                        Op.getOperand(1), ShAmt);
25908   }
25909   }
25910 }
25911 
25912 static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
25913                                  SDValue Src, SDValue Mask, SDValue Base,
25914                                  SDValue Index, SDValue ScaleOp, SDValue Chain,
25915                                  const X86Subtarget &Subtarget) {
25916   SDLoc dl(Op);
25917   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25918   // Scale must be constant.
25919   if (!C)
25920     return SDValue();
25921   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25922   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25923                                         TLI.getPointerTy(DAG.getDataLayout()));
25924   EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
25925   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
25926   // If source is undef or we know it won't be used, use a zero vector
25927   // to break register dependency.
25928   // TODO: use undef instead and let BreakFalseDeps deal with it?
25929   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
25930     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
25931 
25932   // Cast mask to an integer type.
25933   Mask = DAG.getBitcast(MaskVT, Mask);
25934 
25935   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
25936 
25937   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
25938   SDValue Res =
25939       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
25940                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
25941   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
25942 }
25943 
25944 static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
25945                              SDValue Src, SDValue Mask, SDValue Base,
25946                              SDValue Index, SDValue ScaleOp, SDValue Chain,
25947                              const X86Subtarget &Subtarget) {
25948   MVT VT = Op.getSimpleValueType();
25949   SDLoc dl(Op);
25950   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25951   // Scale must be constant.
25952   if (!C)
25953     return SDValue();
25954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25955   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25956                                         TLI.getPointerTy(DAG.getDataLayout()));
25957   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
25958                               VT.getVectorNumElements());
25959   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
25960 
25961   // We support two versions of the gather intrinsics. One with scalar mask and
25962   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
25963   if (Mask.getValueType() != MaskVT)
25964     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
25965 
25966   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Other);
25967   // If source is undef or we know it won't be used, use a zero vector
25968   // to break register dependency.
25969   // TODO: use undef instead and let BreakFalseDeps deal with it?
25970   if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
25971     Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
25972 
25973   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
25974 
25975   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
25976   SDValue Res =
25977       DAG.getMemIntrinsicNode(X86ISD::MGATHER, dl, VTs, Ops,
25978                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
25979   return DAG.getMergeValues({Res, Res.getValue(1)}, dl);
25980 }
25981 
25982 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
25983                                SDValue Src, SDValue Mask, SDValue Base,
25984                                SDValue Index, SDValue ScaleOp, SDValue Chain,
25985                                const X86Subtarget &Subtarget) {
25986   SDLoc dl(Op);
25987   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
25988   // Scale must be constant.
25989   if (!C)
25990     return SDValue();
25991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25992   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
25993                                         TLI.getPointerTy(DAG.getDataLayout()));
25994   unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
25995                               Src.getSimpleValueType().getVectorNumElements());
25996   MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
25997 
25998   // We support two versions of the scatter intrinsics. One with scalar mask and
25999   // one with vXi1 mask. Convert scalar to vXi1 if necessary.
26000   if (Mask.getValueType() != MaskVT)
26001     Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26002 
26003   MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26004 
26005   SDVTList VTs = DAG.getVTList(MVT::Other);
26006   SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
26007   SDValue Res =
26008       DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
26009                               MemIntr->getMemoryVT(), MemIntr->getMemOperand());
26010   return Res;
26011 }
26012 
26013 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
26014                                SDValue Mask, SDValue Base, SDValue Index,
26015                                SDValue ScaleOp, SDValue Chain,
26016                                const X86Subtarget &Subtarget) {
26017   SDLoc dl(Op);
26018   auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
26019   // Scale must be constant.
26020   if (!C)
26021     return SDValue();
26022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26023   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl,
26024                                         TLI.getPointerTy(DAG.getDataLayout()));
26025   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
26026   SDValue Segment = DAG.getRegister(0, MVT::i32);
26027   MVT MaskVT =
26028     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
26029   SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26030   SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
26031   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
26032   return SDValue(Res, 0);
26033 }
26034 
26035 /// Handles the lowering of builtin intrinsics with chain that return their
26036 /// value into registers EDX:EAX.
26037 /// If operand ScrReg is a valid register identifier, then operand 2 of N is
26038 /// copied to SrcReg. The assumption is that SrcReg is an implicit input to
26039 /// TargetOpcode.
26040 /// Returns a Glue value which can be used to add extra copy-from-reg if the
26041 /// expanded intrinsics implicitly defines extra registers (i.e. not just
26042 /// EDX:EAX).
26043 static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
26044                                         SelectionDAG &DAG,
26045                                         unsigned TargetOpcode,
26046                                         unsigned SrcReg,
26047                                         const X86Subtarget &Subtarget,
26048                                         SmallVectorImpl<SDValue> &Results) {
26049   SDValue Chain = N->getOperand(0);
26050   SDValue Glue;
26051 
26052   if (SrcReg) {
26053     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
26054     Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
26055     Glue = Chain.getValue(1);
26056   }
26057 
26058   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
26059   SDValue N1Ops[] = {Chain, Glue};
26060   SDNode *N1 = DAG.getMachineNode(
26061       TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
26062   Chain = SDValue(N1, 0);
26063 
26064   // Reads the content of XCR and returns it in registers EDX:EAX.
26065   SDValue LO, HI;
26066   if (Subtarget.is64Bit()) {
26067     LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
26068     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
26069                             LO.getValue(2));
26070   } else {
26071     LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
26072     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
26073                             LO.getValue(2));
26074   }
26075   Chain = HI.getValue(1);
26076   Glue = HI.getValue(2);
26077 
26078   if (Subtarget.is64Bit()) {
26079     // Merge the two 32-bit values into a 64-bit one.
26080     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
26081                               DAG.getConstant(32, DL, MVT::i8));
26082     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
26083     Results.push_back(Chain);
26084     return Glue;
26085   }
26086 
26087   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
26088   SDValue Ops[] = { LO, HI };
26089   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
26090   Results.push_back(Pair);
26091   Results.push_back(Chain);
26092   return Glue;
26093 }
26094 
26095 /// Handles the lowering of builtin intrinsics that read the time stamp counter
26096 /// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
26097 /// READCYCLECOUNTER nodes.
26098 static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
26099                                     SelectionDAG &DAG,
26100                                     const X86Subtarget &Subtarget,
26101                                     SmallVectorImpl<SDValue> &Results) {
26102   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
26103   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
26104   // and the EAX register is loaded with the low-order 32 bits.
26105   SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
26106                                              /* NoRegister */0, Subtarget,
26107                                              Results);
26108   if (Opcode != X86::RDTSCP)
26109     return;
26110 
26111   SDValue Chain = Results[1];
26112   // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
26113   // the ECX register. Add 'ecx' explicitly to the chain.
26114   SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
26115   Results[1] = ecx;
26116   Results.push_back(ecx.getValue(1));
26117 }
26118 
26119 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
26120                                      SelectionDAG &DAG) {
26121   SmallVector<SDValue, 3> Results;
26122   SDLoc DL(Op);
26123   getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
26124                           Results);
26125   return DAG.getMergeValues(Results, DL);
26126 }
26127 
26128 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
26129   MachineFunction &MF = DAG.getMachineFunction();
26130   SDValue Chain = Op.getOperand(0);
26131   SDValue RegNode = Op.getOperand(2);
26132   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
26133   if (!EHInfo)
26134     report_fatal_error("EH registrations only live in functions using WinEH");
26135 
26136   // Cast the operand to an alloca, and remember the frame index.
26137   auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
26138   if (!FINode)
26139     report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
26140   EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
26141 
26142   // Return the chain operand without making any DAG nodes.
26143   return Chain;
26144 }
26145 
26146 static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
26147   MachineFunction &MF = DAG.getMachineFunction();
26148   SDValue Chain = Op.getOperand(0);
26149   SDValue EHGuard = Op.getOperand(2);
26150   WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
26151   if (!EHInfo)
26152     report_fatal_error("EHGuard only live in functions using WinEH");
26153 
26154   // Cast the operand to an alloca, and remember the frame index.
26155   auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
26156   if (!FINode)
26157     report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
26158   EHInfo->EHGuardFrameIndex = FINode->getIndex();
26159 
26160   // Return the chain operand without making any DAG nodes.
26161   return Chain;
26162 }
26163 
26164 /// Emit Truncating Store with signed or unsigned saturation.
26165 static SDValue
26166 EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
26167                 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
26168                 SelectionDAG &DAG) {
26169   SDVTList VTs = DAG.getVTList(MVT::Other);
26170   SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
26171   SDValue Ops[] = { Chain, Val, Ptr, Undef };
26172   unsigned Opc = SignedSat ? X86ISD::VTRUNCSTORES : X86ISD::VTRUNCSTOREUS;
26173   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
26174 }
26175 
26176 /// Emit Masked Truncating Store with signed or unsigned saturation.
26177 static SDValue
26178 EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
26179                       SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
26180                       MachineMemOperand *MMO, SelectionDAG &DAG) {
26181   SDVTList VTs = DAG.getVTList(MVT::Other);
26182   SDValue Ops[] = { Chain, Val, Ptr, Mask };
26183   unsigned Opc = SignedSat ? X86ISD::VMTRUNCSTORES : X86ISD::VMTRUNCSTOREUS;
26184   return DAG.getMemIntrinsicNode(Opc, Dl, VTs, Ops, MemVT, MMO);
26185 }
26186 
26187 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
26188                                       SelectionDAG &DAG) {
26189   unsigned IntNo = Op.getConstantOperandVal(1);
26190   const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
26191   if (!IntrData) {
26192     switch (IntNo) {
26193     case llvm::Intrinsic::x86_seh_ehregnode:
26194       return MarkEHRegistrationNode(Op, DAG);
26195     case llvm::Intrinsic::x86_seh_ehguard:
26196       return MarkEHGuard(Op, DAG);
26197     case llvm::Intrinsic::x86_rdpkru: {
26198       SDLoc dl(Op);
26199       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26200       // Create a RDPKRU node and pass 0 to the ECX parameter.
26201       return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
26202                          DAG.getConstant(0, dl, MVT::i32));
26203     }
26204     case llvm::Intrinsic::x86_wrpkru: {
26205       SDLoc dl(Op);
26206       // Create a WRPKRU node, pass the input to the EAX parameter,  and pass 0
26207       // to the EDX and ECX parameters.
26208       return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
26209                          Op.getOperand(0), Op.getOperand(2),
26210                          DAG.getConstant(0, dl, MVT::i32),
26211                          DAG.getConstant(0, dl, MVT::i32));
26212     }
26213     case llvm::Intrinsic::x86_flags_read_u32:
26214     case llvm::Intrinsic::x86_flags_read_u64:
26215     case llvm::Intrinsic::x86_flags_write_u32:
26216     case llvm::Intrinsic::x86_flags_write_u64: {
26217       // We need a frame pointer because this will get lowered to a PUSH/POP
26218       // sequence.
26219       MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
26220       MFI.setHasCopyImplyingStackAdjustment(true);
26221       // Don't do anything here, we will expand these intrinsics out later
26222       // during FinalizeISel in EmitInstrWithCustomInserter.
26223       return Op;
26224     }
26225     case Intrinsic::x86_lwpins32:
26226     case Intrinsic::x86_lwpins64:
26227     case Intrinsic::x86_umwait:
26228     case Intrinsic::x86_tpause: {
26229       SDLoc dl(Op);
26230       SDValue Chain = Op->getOperand(0);
26231       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26232       unsigned Opcode;
26233 
26234       switch (IntNo) {
26235       default: llvm_unreachable("Impossible intrinsic");
26236       case Intrinsic::x86_umwait:
26237         Opcode = X86ISD::UMWAIT;
26238         break;
26239       case Intrinsic::x86_tpause:
26240         Opcode = X86ISD::TPAUSE;
26241         break;
26242       case Intrinsic::x86_lwpins32:
26243       case Intrinsic::x86_lwpins64:
26244         Opcode = X86ISD::LWPINS;
26245         break;
26246       }
26247 
26248       SDValue Operation =
26249           DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
26250                       Op->getOperand(3), Op->getOperand(4));
26251       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
26252       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26253                          Operation.getValue(1));
26254     }
26255     case Intrinsic::x86_enqcmd:
26256     case Intrinsic::x86_enqcmds: {
26257       SDLoc dl(Op);
26258       SDValue Chain = Op.getOperand(0);
26259       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26260       unsigned Opcode;
26261       switch (IntNo) {
26262       default: llvm_unreachable("Impossible intrinsic!");
26263       case Intrinsic::x86_enqcmd:
26264         Opcode = X86ISD::ENQCMD;
26265         break;
26266       case Intrinsic::x86_enqcmds:
26267         Opcode = X86ISD::ENQCMDS;
26268         break;
26269       }
26270       SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
26271                                       Op.getOperand(3));
26272       SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
26273       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26274                          Operation.getValue(1));
26275     }
26276     case Intrinsic::x86_aesenc128kl:
26277     case Intrinsic::x86_aesdec128kl:
26278     case Intrinsic::x86_aesenc256kl:
26279     case Intrinsic::x86_aesdec256kl: {
26280       SDLoc DL(Op);
26281       SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
26282       SDValue Chain = Op.getOperand(0);
26283       unsigned Opcode;
26284 
26285       switch (IntNo) {
26286       default: llvm_unreachable("Impossible intrinsic");
26287       case Intrinsic::x86_aesenc128kl:
26288         Opcode = X86ISD::AESENC128KL;
26289         break;
26290       case Intrinsic::x86_aesdec128kl:
26291         Opcode = X86ISD::AESDEC128KL;
26292         break;
26293       case Intrinsic::x86_aesenc256kl:
26294         Opcode = X86ISD::AESENC256KL;
26295         break;
26296       case Intrinsic::x86_aesdec256kl:
26297         Opcode = X86ISD::AESDEC256KL;
26298         break;
26299       }
26300 
26301       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26302       MachineMemOperand *MMO = MemIntr->getMemOperand();
26303       EVT MemVT = MemIntr->getMemoryVT();
26304       SDValue Operation = DAG.getMemIntrinsicNode(
26305           Opcode, DL, VTs, {Chain, Op.getOperand(2), Op.getOperand(3)}, MemVT,
26306           MMO);
26307       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(1), DL, DAG);
26308 
26309       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26310                          {ZF, Operation.getValue(0), Operation.getValue(2)});
26311     }
26312     case Intrinsic::x86_aesencwide128kl:
26313     case Intrinsic::x86_aesdecwide128kl:
26314     case Intrinsic::x86_aesencwide256kl:
26315     case Intrinsic::x86_aesdecwide256kl: {
26316       SDLoc DL(Op);
26317       SDVTList VTs = DAG.getVTList(
26318           {MVT::i32, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::v2i64,
26319            MVT::v2i64, MVT::v2i64, MVT::v2i64, MVT::Other});
26320       SDValue Chain = Op.getOperand(0);
26321       unsigned Opcode;
26322 
26323       switch (IntNo) {
26324       default: llvm_unreachable("Impossible intrinsic");
26325       case Intrinsic::x86_aesencwide128kl:
26326         Opcode = X86ISD::AESENCWIDE128KL;
26327         break;
26328       case Intrinsic::x86_aesdecwide128kl:
26329         Opcode = X86ISD::AESDECWIDE128KL;
26330         break;
26331       case Intrinsic::x86_aesencwide256kl:
26332         Opcode = X86ISD::AESENCWIDE256KL;
26333         break;
26334       case Intrinsic::x86_aesdecwide256kl:
26335         Opcode = X86ISD::AESDECWIDE256KL;
26336         break;
26337       }
26338 
26339       MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
26340       MachineMemOperand *MMO = MemIntr->getMemOperand();
26341       EVT MemVT = MemIntr->getMemoryVT();
26342       SDValue Operation = DAG.getMemIntrinsicNode(
26343           Opcode, DL, VTs,
26344           {Chain, Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
26345            Op.getOperand(5), Op.getOperand(6), Op.getOperand(7),
26346            Op.getOperand(8), Op.getOperand(9), Op.getOperand(10)},
26347           MemVT, MMO);
26348       SDValue ZF = getSETCC(X86::COND_E, Operation.getValue(0), DL, DAG);
26349 
26350       return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26351                          {ZF, Operation.getValue(1), Operation.getValue(2),
26352                           Operation.getValue(3), Operation.getValue(4),
26353                           Operation.getValue(5), Operation.getValue(6),
26354                           Operation.getValue(7), Operation.getValue(8),
26355                           Operation.getValue(9)});
26356     }
26357     case Intrinsic::x86_testui: {
26358       SDLoc dl(Op);
26359       SDValue Chain = Op.getOperand(0);
26360       SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
26361       SDValue Operation = DAG.getNode(X86ISD::TESTUI, dl, VTs, Chain);
26362       SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
26363       return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
26364                          Operation.getValue(1));
26365     }
26366     }
26367     return SDValue();
26368   }
26369 
26370   SDLoc dl(Op);
26371   switch(IntrData->Type) {
26372   default: llvm_unreachable("Unknown Intrinsic Type");
26373   case RDSEED:
26374   case RDRAND: {
26375     // Emit the node with the right value type.
26376     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
26377     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
26378 
26379     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
26380     // Otherwise return the value from Rand, which is always 0, casted to i32.
26381     SDValue Ops[] = {DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
26382                      DAG.getConstant(1, dl, Op->getValueType(1)),
26383                      DAG.getTargetConstant(X86::COND_B, dl, MVT::i8),
26384                      SDValue(Result.getNode(), 1)};
26385     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
26386 
26387     // Return { result, isValid, chain }.
26388     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
26389                        SDValue(Result.getNode(), 2));
26390   }
26391   case GATHER_AVX2: {
26392     SDValue Chain = Op.getOperand(0);
26393     SDValue Src   = Op.getOperand(2);
26394     SDValue Base  = Op.getOperand(3);
26395     SDValue Index = Op.getOperand(4);
26396     SDValue Mask  = Op.getOperand(5);
26397     SDValue Scale = Op.getOperand(6);
26398     return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
26399                              Scale, Chain, Subtarget);
26400   }
26401   case GATHER: {
26402   //gather(v1, mask, index, base, scale);
26403     SDValue Chain = Op.getOperand(0);
26404     SDValue Src   = Op.getOperand(2);
26405     SDValue Base  = Op.getOperand(3);
26406     SDValue Index = Op.getOperand(4);
26407     SDValue Mask  = Op.getOperand(5);
26408     SDValue Scale = Op.getOperand(6);
26409     return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
26410                          Chain, Subtarget);
26411   }
26412   case SCATTER: {
26413   //scatter(base, mask, index, v1, scale);
26414     SDValue Chain = Op.getOperand(0);
26415     SDValue Base  = Op.getOperand(2);
26416     SDValue Mask  = Op.getOperand(3);
26417     SDValue Index = Op.getOperand(4);
26418     SDValue Src   = Op.getOperand(5);
26419     SDValue Scale = Op.getOperand(6);
26420     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
26421                           Scale, Chain, Subtarget);
26422   }
26423   case PREFETCH: {
26424     const APInt &HintVal = Op.getConstantOperandAPInt(6);
26425     assert((HintVal == 2 || HintVal == 3) &&
26426            "Wrong prefetch hint in intrinsic: should be 2 or 3");
26427     unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
26428     SDValue Chain = Op.getOperand(0);
26429     SDValue Mask  = Op.getOperand(2);
26430     SDValue Index = Op.getOperand(3);
26431     SDValue Base  = Op.getOperand(4);
26432     SDValue Scale = Op.getOperand(5);
26433     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
26434                            Subtarget);
26435   }
26436   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
26437   case RDTSC: {
26438     SmallVector<SDValue, 2> Results;
26439     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
26440                             Results);
26441     return DAG.getMergeValues(Results, dl);
26442   }
26443   // Read Performance Monitoring Counters.
26444   case RDPMC:
26445   // GetExtended Control Register.
26446   case XGETBV: {
26447     SmallVector<SDValue, 2> Results;
26448 
26449     // RDPMC uses ECX to select the index of the performance counter to read.
26450     // XGETBV uses ECX to select the index of the XCR register to return.
26451     // The result is stored into registers EDX:EAX.
26452     expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
26453                                 Subtarget, Results);
26454     return DAG.getMergeValues(Results, dl);
26455   }
26456   // XTEST intrinsics.
26457   case XTEST: {
26458     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
26459     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
26460 
26461     SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
26462     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
26463     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
26464                        Ret, SDValue(InTrans.getNode(), 1));
26465   }
26466   case TRUNCATE_TO_MEM_VI8:
26467   case TRUNCATE_TO_MEM_VI16:
26468   case TRUNCATE_TO_MEM_VI32: {
26469     SDValue Mask = Op.getOperand(4);
26470     SDValue DataToTruncate = Op.getOperand(3);
26471     SDValue Addr = Op.getOperand(2);
26472     SDValue Chain = Op.getOperand(0);
26473 
26474     MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
26475     assert(MemIntr && "Expected MemIntrinsicSDNode!");
26476 
26477     EVT MemVT  = MemIntr->getMemoryVT();
26478 
26479     uint16_t TruncationOp = IntrData->Opc0;
26480     switch (TruncationOp) {
26481     case X86ISD::VTRUNC: {
26482       if (isAllOnesConstant(Mask)) // return just a truncate store
26483         return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
26484                                  MemIntr->getMemOperand());
26485 
26486       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
26487       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26488       SDValue Offset = DAG.getUNDEF(VMask.getValueType());
26489 
26490       return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, Offset, VMask,
26491                                 MemVT, MemIntr->getMemOperand(), ISD::UNINDEXED,
26492                                 true /* truncating */);
26493     }
26494     case X86ISD::VTRUNCUS:
26495     case X86ISD::VTRUNCS: {
26496       bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
26497       if (isAllOnesConstant(Mask))
26498         return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
26499                                MemIntr->getMemOperand(), DAG);
26500 
26501       MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
26502       SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
26503 
26504       return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
26505                                    VMask, MemVT, MemIntr->getMemOperand(), DAG);
26506     }
26507     default:
26508       llvm_unreachable("Unsupported truncstore intrinsic");
26509     }
26510   }
26511   }
26512 }
26513 
26514 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
26515                                            SelectionDAG &DAG) const {
26516   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
26517   MFI.setReturnAddressIsTaken(true);
26518 
26519   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
26520     return SDValue();
26521 
26522   unsigned Depth = Op.getConstantOperandVal(0);
26523   SDLoc dl(Op);
26524   EVT PtrVT = getPointerTy(DAG.getDataLayout());
26525 
26526   if (Depth > 0) {
26527     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
26528     const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26529     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
26530     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
26531                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
26532                        MachinePointerInfo());
26533   }
26534 
26535   // Just load the return address.
26536   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
26537   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
26538                      MachinePointerInfo());
26539 }
26540 
26541 SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
26542                                                  SelectionDAG &DAG) const {
26543   DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
26544   return getReturnAddressFrameIndex(DAG);
26545 }
26546 
26547 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
26548   MachineFunction &MF = DAG.getMachineFunction();
26549   MachineFrameInfo &MFI = MF.getFrameInfo();
26550   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
26551   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26552   EVT VT = Op.getValueType();
26553 
26554   MFI.setFrameAddressIsTaken(true);
26555 
26556   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
26557     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
26558     // is not possible to crawl up the stack without looking at the unwind codes
26559     // simultaneously.
26560     int FrameAddrIndex = FuncInfo->getFAIndex();
26561     if (!FrameAddrIndex) {
26562       // Set up a frame object for the return address.
26563       unsigned SlotSize = RegInfo->getSlotSize();
26564       FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
26565           SlotSize, /*SPOffset=*/0, /*IsImmutable=*/false);
26566       FuncInfo->setFAIndex(FrameAddrIndex);
26567     }
26568     return DAG.getFrameIndex(FrameAddrIndex, VT);
26569   }
26570 
26571   unsigned FrameReg =
26572       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
26573   SDLoc dl(Op);  // FIXME probably not meaningful
26574   unsigned Depth = Op.getConstantOperandVal(0);
26575   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
26576           (FrameReg == X86::EBP && VT == MVT::i32)) &&
26577          "Invalid Frame Register!");
26578   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
26579   while (Depth--)
26580     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
26581                             MachinePointerInfo());
26582   return FrameAddr;
26583 }
26584 
26585 // FIXME? Maybe this could be a TableGen attribute on some registers and
26586 // this table could be generated automatically from RegInfo.
26587 Register X86TargetLowering::getRegisterByName(const char* RegName, LLT VT,
26588                                               const MachineFunction &MF) const {
26589   const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
26590 
26591   Register Reg = StringSwitch<unsigned>(RegName)
26592                        .Case("esp", X86::ESP)
26593                        .Case("rsp", X86::RSP)
26594                        .Case("ebp", X86::EBP)
26595                        .Case("rbp", X86::RBP)
26596                        .Default(0);
26597 
26598   if (Reg == X86::EBP || Reg == X86::RBP) {
26599     if (!TFI.hasFP(MF))
26600       report_fatal_error("register " + StringRef(RegName) +
26601                          " is allocatable: function has no frame pointer");
26602 #ifndef NDEBUG
26603     else {
26604       const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26605       Register FrameReg = RegInfo->getPtrSizedFrameRegister(MF);
26606       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
26607              "Invalid Frame Register!");
26608     }
26609 #endif
26610   }
26611 
26612   if (Reg)
26613     return Reg;
26614 
26615   report_fatal_error("Invalid register name global variable");
26616 }
26617 
26618 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
26619                                                      SelectionDAG &DAG) const {
26620   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26621   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
26622 }
26623 
26624 Register X86TargetLowering::getExceptionPointerRegister(
26625     const Constant *PersonalityFn) const {
26626   if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
26627     return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
26628 
26629   return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
26630 }
26631 
26632 Register X86TargetLowering::getExceptionSelectorRegister(
26633     const Constant *PersonalityFn) const {
26634   // Funclet personalities don't use selectors (the runtime does the selection).
26635   assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
26636   return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
26637 }
26638 
26639 bool X86TargetLowering::needsFixedCatchObjects() const {
26640   return Subtarget.isTargetWin64();
26641 }
26642 
26643 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
26644   SDValue Chain     = Op.getOperand(0);
26645   SDValue Offset    = Op.getOperand(1);
26646   SDValue Handler   = Op.getOperand(2);
26647   SDLoc dl      (Op);
26648 
26649   EVT PtrVT = getPointerTy(DAG.getDataLayout());
26650   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
26651   Register FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
26652   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
26653           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
26654          "Invalid Frame Register!");
26655   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
26656   Register StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
26657 
26658   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
26659                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
26660                                                        dl));
26661   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
26662   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
26663   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
26664 
26665   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
26666                      DAG.getRegister(StoreAddrReg, PtrVT));
26667 }
26668 
26669 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
26670                                                SelectionDAG &DAG) const {
26671   SDLoc DL(Op);
26672   // If the subtarget is not 64bit, we may need the global base reg
26673   // after isel expand pseudo, i.e., after CGBR pass ran.
26674   // Therefore, ask for the GlobalBaseReg now, so that the pass
26675   // inserts the code for us in case we need it.
26676   // Otherwise, we will end up in a situation where we will
26677   // reference a virtual register that is not defined!
26678   if (!Subtarget.is64Bit()) {
26679     const X86InstrInfo *TII = Subtarget.getInstrInfo();
26680     (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
26681   }
26682   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
26683                      DAG.getVTList(MVT::i32, MVT::Other),
26684                      Op.getOperand(0), Op.getOperand(1));
26685 }
26686 
26687 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
26688                                                 SelectionDAG &DAG) const {
26689   SDLoc DL(Op);
26690   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
26691                      Op.getOperand(0), Op.getOperand(1));
26692 }
26693 
26694 SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
26695                                                        SelectionDAG &DAG) const {
26696   SDLoc DL(Op);
26697   return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
26698                      Op.getOperand(0));
26699 }
26700 
26701 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
26702   return Op.getOperand(0);
26703 }
26704 
26705 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
26706                                                 SelectionDAG &DAG) const {
26707   SDValue Root = Op.getOperand(0);
26708   SDValue Trmp = Op.getOperand(1); // trampoline
26709   SDValue FPtr = Op.getOperand(2); // nested function
26710   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
26711   SDLoc dl (Op);
26712 
26713   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
26714   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
26715 
26716   if (Subtarget.is64Bit()) {
26717     SDValue OutChains[6];
26718 
26719     // Large code-model.
26720     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
26721     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
26722 
26723     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
26724     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
26725 
26726     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
26727 
26728     // Load the pointer to the nested function into R11.
26729     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
26730     SDValue Addr = Trmp;
26731     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26732                                 Addr, MachinePointerInfo(TrmpAddr));
26733 
26734     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26735                        DAG.getConstant(2, dl, MVT::i64));
26736     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
26737                                 MachinePointerInfo(TrmpAddr, 2), Align(2));
26738 
26739     // Load the 'nest' parameter value into R10.
26740     // R10 is specified in X86CallingConv.td
26741     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
26742     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26743                        DAG.getConstant(10, dl, MVT::i64));
26744     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26745                                 Addr, MachinePointerInfo(TrmpAddr, 10));
26746 
26747     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26748                        DAG.getConstant(12, dl, MVT::i64));
26749     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
26750                                 MachinePointerInfo(TrmpAddr, 12), Align(2));
26751 
26752     // Jump to the nested function.
26753     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
26754     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26755                        DAG.getConstant(20, dl, MVT::i64));
26756     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
26757                                 Addr, MachinePointerInfo(TrmpAddr, 20));
26758 
26759     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
26760     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
26761                        DAG.getConstant(22, dl, MVT::i64));
26762     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
26763                                 Addr, MachinePointerInfo(TrmpAddr, 22));
26764 
26765     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
26766   } else {
26767     const Function *Func =
26768       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
26769     CallingConv::ID CC = Func->getCallingConv();
26770     unsigned NestReg;
26771 
26772     switch (CC) {
26773     default:
26774       llvm_unreachable("Unsupported calling convention");
26775     case CallingConv::C:
26776     case CallingConv::X86_StdCall: {
26777       // Pass 'nest' parameter in ECX.
26778       // Must be kept in sync with X86CallingConv.td
26779       NestReg = X86::ECX;
26780 
26781       // Check that ECX wasn't needed by an 'inreg' parameter.
26782       FunctionType *FTy = Func->getFunctionType();
26783       const AttributeList &Attrs = Func->getAttributes();
26784 
26785       if (!Attrs.isEmpty() && !Func->isVarArg()) {
26786         unsigned InRegCount = 0;
26787         unsigned Idx = 1;
26788 
26789         for (FunctionType::param_iterator I = FTy->param_begin(),
26790              E = FTy->param_end(); I != E; ++I, ++Idx)
26791           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
26792             const DataLayout &DL = DAG.getDataLayout();
26793             // FIXME: should only count parameters that are lowered to integers.
26794             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
26795           }
26796 
26797         if (InRegCount > 2) {
26798           report_fatal_error("Nest register in use - reduce number of inreg"
26799                              " parameters!");
26800         }
26801       }
26802       break;
26803     }
26804     case CallingConv::X86_FastCall:
26805     case CallingConv::X86_ThisCall:
26806     case CallingConv::Fast:
26807     case CallingConv::Tail:
26808       // Pass 'nest' parameter in EAX.
26809       // Must be kept in sync with X86CallingConv.td
26810       NestReg = X86::EAX;
26811       break;
26812     }
26813 
26814     SDValue OutChains[4];
26815     SDValue Addr, Disp;
26816 
26817     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26818                        DAG.getConstant(10, dl, MVT::i32));
26819     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
26820 
26821     // This is storing the opcode for MOV32ri.
26822     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
26823     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
26824     OutChains[0] =
26825         DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
26826                      Trmp, MachinePointerInfo(TrmpAddr));
26827 
26828     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26829                        DAG.getConstant(1, dl, MVT::i32));
26830     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
26831                                 MachinePointerInfo(TrmpAddr, 1), Align(1));
26832 
26833     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
26834     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26835                        DAG.getConstant(5, dl, MVT::i32));
26836     OutChains[2] =
26837         DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8), Addr,
26838                      MachinePointerInfo(TrmpAddr, 5), Align(1));
26839 
26840     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
26841                        DAG.getConstant(6, dl, MVT::i32));
26842     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
26843                                 MachinePointerInfo(TrmpAddr, 6), Align(1));
26844 
26845     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
26846   }
26847 }
26848 
26849 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
26850                                             SelectionDAG &DAG) const {
26851   /*
26852    The rounding mode is in bits 11:10 of FPSR, and has the following
26853    settings:
26854      00 Round to nearest
26855      01 Round to -inf
26856      10 Round to +inf
26857      11 Round to 0
26858 
26859   FLT_ROUNDS, on the other hand, expects the following:
26860     -1 Undefined
26861      0 Round to 0
26862      1 Round to nearest
26863      2 Round to +inf
26864      3 Round to -inf
26865 
26866   To perform the conversion, we use a packed lookup table of the four 2-bit
26867   values that we can index by FPSP[11:10]
26868     0x2d --> (0b00,10,11,01) --> (0,2,3,1) >> FPSR[11:10]
26869 
26870     (0x2d >> ((FPSR & 0xc00) >> 9)) & 3
26871   */
26872 
26873   MachineFunction &MF = DAG.getMachineFunction();
26874   MVT VT = Op.getSimpleValueType();
26875   SDLoc DL(Op);
26876 
26877   // Save FP Control Word to stack slot
26878   int SSFI = MF.getFrameInfo().CreateStackObject(2, Align(2), false);
26879   SDValue StackSlot =
26880       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
26881 
26882   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
26883 
26884   SDValue Chain = Op.getOperand(0);
26885   SDValue Ops[] = {Chain, StackSlot};
26886   Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
26887                                   DAG.getVTList(MVT::Other), Ops, MVT::i16, MPI,
26888                                   Align(2), MachineMemOperand::MOStore);
26889 
26890   // Load FP Control Word from stack slot
26891   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MPI, Align(2));
26892   Chain = CWD.getValue(1);
26893 
26894   // Mask and turn the control bits into a shift for the lookup table.
26895   SDValue Shift =
26896     DAG.getNode(ISD::SRL, DL, MVT::i16,
26897                 DAG.getNode(ISD::AND, DL, MVT::i16,
26898                             CWD, DAG.getConstant(0xc00, DL, MVT::i16)),
26899                 DAG.getConstant(9, DL, MVT::i8));
26900   Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Shift);
26901 
26902   SDValue LUT = DAG.getConstant(0x2d, DL, MVT::i32);
26903   SDValue RetVal =
26904     DAG.getNode(ISD::AND, DL, MVT::i32,
26905                 DAG.getNode(ISD::SRL, DL, MVT::i32, LUT, Shift),
26906                 DAG.getConstant(3, DL, MVT::i32));
26907 
26908   RetVal = DAG.getZExtOrTrunc(RetVal, DL, VT);
26909 
26910   return DAG.getMergeValues({RetVal, Chain}, DL);
26911 }
26912 
26913 /// Lower a vector CTLZ using native supported vector CTLZ instruction.
26914 //
26915 // i8/i16 vector implemented using dword LZCNT vector instruction
26916 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
26917 // split the vector, perform operation on it's Lo a Hi part and
26918 // concatenate the results.
26919 static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
26920                                          const X86Subtarget &Subtarget) {
26921   assert(Op.getOpcode() == ISD::CTLZ);
26922   SDLoc dl(Op);
26923   MVT VT = Op.getSimpleValueType();
26924   MVT EltVT = VT.getVectorElementType();
26925   unsigned NumElems = VT.getVectorNumElements();
26926 
26927   assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
26928           "Unsupported element type");
26929 
26930   // Split vector, it's Lo and Hi parts will be handled in next iteration.
26931   if (NumElems > 16 ||
26932       (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
26933     return splitVectorIntUnary(Op, DAG);
26934 
26935   MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
26936   assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
26937           "Unsupported value type for operation");
26938 
26939   // Use native supported vector instruction vplzcntd.
26940   Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
26941   SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
26942   SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
26943   SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
26944 
26945   return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
26946 }
26947 
26948 // Lower CTLZ using a PSHUFB lookup table implementation.
26949 static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
26950                                        const X86Subtarget &Subtarget,
26951                                        SelectionDAG &DAG) {
26952   MVT VT = Op.getSimpleValueType();
26953   int NumElts = VT.getVectorNumElements();
26954   int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
26955   MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
26956 
26957   // Per-nibble leading zero PSHUFB lookup table.
26958   const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
26959                        /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
26960                        /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
26961                        /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
26962 
26963   SmallVector<SDValue, 64> LUTVec;
26964   for (int i = 0; i < NumBytes; ++i)
26965     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
26966   SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
26967 
26968   // Begin by bitcasting the input to byte vector, then split those bytes
26969   // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
26970   // If the hi input nibble is zero then we add both results together, otherwise
26971   // we just take the hi result (by masking the lo result to zero before the
26972   // add).
26973   SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
26974   SDValue Zero = DAG.getConstant(0, DL, CurrVT);
26975 
26976   SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
26977   SDValue Lo = Op0;
26978   SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
26979   SDValue HiZ;
26980   if (CurrVT.is512BitVector()) {
26981     MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
26982     HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
26983     HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
26984   } else {
26985     HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
26986   }
26987 
26988   Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
26989   Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
26990   Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
26991   SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
26992 
26993   // Merge result back from vXi8 back to VT, working on the lo/hi halves
26994   // of the current vector width in the same way we did for the nibbles.
26995   // If the upper half of the input element is zero then add the halves'
26996   // leading zero counts together, otherwise just use the upper half's.
26997   // Double the width of the result until we are at target width.
26998   while (CurrVT != VT) {
26999     int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
27000     int CurrNumElts = CurrVT.getVectorNumElements();
27001     MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
27002     MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
27003     SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
27004 
27005     // Check if the upper half of the input element is zero.
27006     if (CurrVT.is512BitVector()) {
27007       MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
27008       HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
27009                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
27010       HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
27011     } else {
27012       HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
27013                          DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
27014     }
27015     HiZ = DAG.getBitcast(NextVT, HiZ);
27016 
27017     // Move the upper/lower halves to the lower bits as we'll be extending to
27018     // NextVT. Mask the lower result to zero if HiZ is true and add the results
27019     // together.
27020     SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
27021     SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
27022     SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
27023     R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
27024     Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
27025     CurrVT = NextVT;
27026   }
27027 
27028   return Res;
27029 }
27030 
27031 static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
27032                                const X86Subtarget &Subtarget,
27033                                SelectionDAG &DAG) {
27034   MVT VT = Op.getSimpleValueType();
27035 
27036   if (Subtarget.hasCDI() &&
27037       // vXi8 vectors need to be promoted to 512-bits for vXi32.
27038       (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
27039     return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
27040 
27041   // Decompose 256-bit ops into smaller 128-bit ops.
27042   if (VT.is256BitVector() && !Subtarget.hasInt256())
27043     return splitVectorIntUnary(Op, DAG);
27044 
27045   // Decompose 512-bit ops into smaller 256-bit ops.
27046   if (VT.is512BitVector() && !Subtarget.hasBWI())
27047     return splitVectorIntUnary(Op, DAG);
27048 
27049   assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB");
27050   return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
27051 }
27052 
27053 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
27054                          SelectionDAG &DAG) {
27055   MVT VT = Op.getSimpleValueType();
27056   MVT OpVT = VT;
27057   unsigned NumBits = VT.getSizeInBits();
27058   SDLoc dl(Op);
27059   unsigned Opc = Op.getOpcode();
27060 
27061   if (VT.isVector())
27062     return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
27063 
27064   Op = Op.getOperand(0);
27065   if (VT == MVT::i8) {
27066     // Zero extend to i32 since there is not an i8 bsr.
27067     OpVT = MVT::i32;
27068     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
27069   }
27070 
27071   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
27072   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
27073   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
27074 
27075   if (Opc == ISD::CTLZ) {
27076     // If src is zero (i.e. bsr sets ZF), returns NumBits.
27077     SDValue Ops[] = {Op, DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
27078                      DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
27079                      Op.getValue(1)};
27080     Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
27081   }
27082 
27083   // Finally xor with NumBits-1.
27084   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
27085                    DAG.getConstant(NumBits - 1, dl, OpVT));
27086 
27087   if (VT == MVT::i8)
27088     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
27089   return Op;
27090 }
27091 
27092 static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
27093                          SelectionDAG &DAG) {
27094   MVT VT = Op.getSimpleValueType();
27095   unsigned NumBits = VT.getScalarSizeInBits();
27096   SDValue N0 = Op.getOperand(0);
27097   SDLoc dl(Op);
27098 
27099   assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
27100          "Only scalar CTTZ requires custom lowering");
27101 
27102   // Issue a bsf (scan bits forward) which also sets EFLAGS.
27103   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
27104   Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
27105 
27106   // If src is zero (i.e. bsf sets ZF), returns NumBits.
27107   SDValue Ops[] = {Op, DAG.getConstant(NumBits, dl, VT),
27108                    DAG.getTargetConstant(X86::COND_E, dl, MVT::i8),
27109                    Op.getValue(1)};
27110   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
27111 }
27112 
27113 static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
27114                            const X86Subtarget &Subtarget) {
27115   MVT VT = Op.getSimpleValueType();
27116   if (VT == MVT::i16 || VT == MVT::i32)
27117     return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
27118 
27119   if (VT.getScalarType() == MVT::i1)
27120     return DAG.getNode(ISD::XOR, SDLoc(Op), VT,
27121                        Op.getOperand(0), Op.getOperand(1));
27122 
27123   if (VT == MVT::v32i16 || VT == MVT::v64i8)
27124     return splitVectorIntBinary(Op, DAG);
27125 
27126   assert(Op.getSimpleValueType().is256BitVector() &&
27127          Op.getSimpleValueType().isInteger() &&
27128          "Only handle AVX 256-bit vector integer operation");
27129   return splitVectorIntBinary(Op, DAG);
27130 }
27131 
27132 static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
27133                                   const X86Subtarget &Subtarget) {
27134   MVT VT = Op.getSimpleValueType();
27135   SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
27136   unsigned Opcode = Op.getOpcode();
27137   SDLoc DL(Op);
27138 
27139   if (VT.getScalarType() == MVT::i1) {
27140     switch (Opcode) {
27141     default: llvm_unreachable("Expected saturated arithmetic opcode");
27142     case ISD::UADDSAT:
27143     case ISD::SADDSAT:
27144       // *addsat i1 X, Y --> X | Y
27145       return DAG.getNode(ISD::OR, DL, VT, X, Y);
27146     case ISD::USUBSAT:
27147     case ISD::SSUBSAT:
27148       // *subsat i1 X, Y --> X & ~Y
27149       return DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, Y, VT));
27150     }
27151   }
27152 
27153   if (VT == MVT::v32i16 || VT == MVT::v64i8 ||
27154       (VT.is256BitVector() && !Subtarget.hasInt256())) {
27155     assert(Op.getSimpleValueType().isInteger() &&
27156            "Only handle AVX vector integer operation");
27157     return splitVectorIntBinary(Op, DAG);
27158   }
27159 
27160   // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
27161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27162   EVT SetCCResultType =
27163       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
27164 
27165   if (Opcode == ISD::USUBSAT && !TLI.isOperationLegal(ISD::UMAX, VT)) {
27166     // usubsat X, Y --> (X >u Y) ? X - Y : 0
27167     SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
27168     SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
27169     // TODO: Move this to DAGCombiner?
27170     if (SetCCResultType == VT &&
27171         DAG.ComputeNumSignBits(Cmp) == VT.getScalarSizeInBits())
27172       return DAG.getNode(ISD::AND, DL, VT, Cmp, Sub);
27173     return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
27174   }
27175 
27176   // Use default expansion.
27177   return SDValue();
27178 }
27179 
27180 static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
27181                         SelectionDAG &DAG) {
27182   MVT VT = Op.getSimpleValueType();
27183   if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
27184     // Since X86 does not have CMOV for 8-bit integer, we don't convert
27185     // 8-bit integer abs to NEG and CMOV.
27186     SDLoc DL(Op);
27187     SDValue N0 = Op.getOperand(0);
27188     SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
27189                               DAG.getConstant(0, DL, VT), N0);
27190     SDValue Ops[] = {N0, Neg, DAG.getTargetConstant(X86::COND_GE, DL, MVT::i8),
27191                      SDValue(Neg.getNode(), 1)};
27192     return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
27193   }
27194 
27195   // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
27196   if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
27197     SDLoc DL(Op);
27198     SDValue Src = Op.getOperand(0);
27199     SDValue Sub =
27200         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
27201     return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
27202   }
27203 
27204   if (VT.is256BitVector() && !Subtarget.hasInt256()) {
27205     assert(VT.isInteger() &&
27206            "Only handle AVX 256-bit vector integer operation");
27207     return splitVectorIntUnary(Op, DAG);
27208   }
27209 
27210   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
27211     return splitVectorIntUnary(Op, DAG);
27212 
27213   // Default to expand.
27214   return SDValue();
27215 }
27216 
27217 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
27218   MVT VT = Op.getSimpleValueType();
27219 
27220   // For AVX1 cases, split to use legal ops (everything but v4i64).
27221   if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
27222     return splitVectorIntBinary(Op, DAG);
27223 
27224   if (VT == MVT::v32i16 || VT == MVT::v64i8)
27225     return splitVectorIntBinary(Op, DAG);
27226 
27227   // Default to expand.
27228   return SDValue();
27229 }
27230 
27231 static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
27232                         SelectionDAG &DAG) {
27233   SDLoc dl(Op);
27234   MVT VT = Op.getSimpleValueType();
27235 
27236   if (VT.getScalarType() == MVT::i1)
27237     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
27238 
27239   // Decompose 256-bit ops into 128-bit ops.
27240   if (VT.is256BitVector() && !Subtarget.hasInt256())
27241     return splitVectorIntBinary(Op, DAG);
27242 
27243   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
27244     return splitVectorIntBinary(Op, DAG);
27245 
27246   SDValue A = Op.getOperand(0);
27247   SDValue B = Op.getOperand(1);
27248 
27249   // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
27250   // vector pairs, multiply and truncate.
27251   if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
27252     unsigned NumElts = VT.getVectorNumElements();
27253 
27254     if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
27255         (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
27256       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
27257       return DAG.getNode(
27258           ISD::TRUNCATE, dl, VT,
27259           DAG.getNode(ISD::MUL, dl, ExVT,
27260                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
27261                       DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
27262     }
27263 
27264     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27265 
27266     // Extract the lo/hi parts to any extend to i16.
27267     // We're going to mask off the low byte of each result element of the
27268     // pmullw, so it doesn't matter what's in the high byte of each 16-bit
27269     // element.
27270     SDValue Undef = DAG.getUNDEF(VT);
27271     SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
27272     SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
27273 
27274     SDValue BLo, BHi;
27275     if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
27276       // If the LHS is a constant, manually unpackl/unpackh.
27277       SmallVector<SDValue, 16> LoOps, HiOps;
27278       for (unsigned i = 0; i != NumElts; i += 16) {
27279         for (unsigned j = 0; j != 8; ++j) {
27280           LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
27281                                                MVT::i16));
27282           HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
27283                                                MVT::i16));
27284         }
27285       }
27286 
27287       BLo = DAG.getBuildVector(ExVT, dl, LoOps);
27288       BHi = DAG.getBuildVector(ExVT, dl, HiOps);
27289     } else {
27290       BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
27291       BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
27292     }
27293 
27294     // Multiply, mask the lower 8bits of the lo/hi results and pack.
27295     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
27296     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
27297     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
27298     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
27299     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
27300   }
27301 
27302   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
27303   if (VT == MVT::v4i32) {
27304     assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
27305            "Should not custom lower when pmulld is available!");
27306 
27307     // Extract the odd parts.
27308     static const int UnpackMask[] = { 1, -1, 3, -1 };
27309     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
27310     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
27311 
27312     // Multiply the even parts.
27313     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
27314                                 DAG.getBitcast(MVT::v2i64, A),
27315                                 DAG.getBitcast(MVT::v2i64, B));
27316     // Now multiply odd parts.
27317     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
27318                                DAG.getBitcast(MVT::v2i64, Aodds),
27319                                DAG.getBitcast(MVT::v2i64, Bodds));
27320 
27321     Evens = DAG.getBitcast(VT, Evens);
27322     Odds = DAG.getBitcast(VT, Odds);
27323 
27324     // Merge the two vectors back together with a shuffle. This expands into 2
27325     // shuffles.
27326     static const int ShufMask[] = { 0, 4, 2, 6 };
27327     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
27328   }
27329 
27330   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
27331          "Only know how to lower V2I64/V4I64/V8I64 multiply");
27332   assert(!Subtarget.hasDQI() && "DQI should use MULLQ");
27333 
27334   //  Ahi = psrlqi(a, 32);
27335   //  Bhi = psrlqi(b, 32);
27336   //
27337   //  AloBlo = pmuludq(a, b);
27338   //  AloBhi = pmuludq(a, Bhi);
27339   //  AhiBlo = pmuludq(Ahi, b);
27340   //
27341   //  Hi = psllqi(AloBhi + AhiBlo, 32);
27342   //  return AloBlo + Hi;
27343   KnownBits AKnown = DAG.computeKnownBits(A);
27344   KnownBits BKnown = DAG.computeKnownBits(B);
27345 
27346   APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
27347   bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
27348   bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
27349 
27350   APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
27351   bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
27352   bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
27353 
27354   SDValue Zero = DAG.getConstant(0, dl, VT);
27355 
27356   // Only multiply lo/hi halves that aren't known to be zero.
27357   SDValue AloBlo = Zero;
27358   if (!ALoIsZero && !BLoIsZero)
27359     AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
27360 
27361   SDValue AloBhi = Zero;
27362   if (!ALoIsZero && !BHiIsZero) {
27363     SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
27364     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
27365   }
27366 
27367   SDValue AhiBlo = Zero;
27368   if (!AHiIsZero && !BLoIsZero) {
27369     SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
27370     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
27371   }
27372 
27373   SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
27374   Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
27375 
27376   return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
27377 }
27378 
27379 static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
27380                          SelectionDAG &DAG) {
27381   SDLoc dl(Op);
27382   MVT VT = Op.getSimpleValueType();
27383   bool IsSigned = Op->getOpcode() == ISD::MULHS;
27384   unsigned NumElts = VT.getVectorNumElements();
27385   SDValue A = Op.getOperand(0);
27386   SDValue B = Op.getOperand(1);
27387 
27388   // Decompose 256-bit ops into 128-bit ops.
27389   if (VT.is256BitVector() && !Subtarget.hasInt256())
27390     return splitVectorIntBinary(Op, DAG);
27391 
27392   if ((VT == MVT::v32i16 || VT == MVT::v64i8) && !Subtarget.hasBWI())
27393     return splitVectorIntBinary(Op, DAG);
27394 
27395   if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
27396     assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||
27397            (VT == MVT::v8i32 && Subtarget.hasInt256()) ||
27398            (VT == MVT::v16i32 && Subtarget.hasAVX512()));
27399 
27400     // PMULxD operations multiply each even value (starting at 0) of LHS with
27401     // the related value of RHS and produce a widen result.
27402     // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
27403     // => <2 x i64> <ae|cg>
27404     //
27405     // In other word, to have all the results, we need to perform two PMULxD:
27406     // 1. one with the even values.
27407     // 2. one with the odd values.
27408     // To achieve #2, with need to place the odd values at an even position.
27409     //
27410     // Place the odd value at an even position (basically, shift all values 1
27411     // step to the left):
27412     const int Mask[] = {1, -1,  3, -1,  5, -1,  7, -1,
27413                         9, -1, 11, -1, 13, -1, 15, -1};
27414     // <a|b|c|d> => <b|undef|d|undef>
27415     SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
27416                                         makeArrayRef(&Mask[0], NumElts));
27417     // <e|f|g|h> => <f|undef|h|undef>
27418     SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
27419                                         makeArrayRef(&Mask[0], NumElts));
27420 
27421     // Emit two multiplies, one for the lower 2 ints and one for the higher 2
27422     // ints.
27423     MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
27424     unsigned Opcode =
27425         (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
27426     // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
27427     // => <2 x i64> <ae|cg>
27428     SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
27429                                                   DAG.getBitcast(MulVT, A),
27430                                                   DAG.getBitcast(MulVT, B)));
27431     // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
27432     // => <2 x i64> <bf|dh>
27433     SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
27434                                                   DAG.getBitcast(MulVT, Odd0),
27435                                                   DAG.getBitcast(MulVT, Odd1)));
27436 
27437     // Shuffle it back into the right order.
27438     SmallVector<int, 16> ShufMask(NumElts);
27439     for (int i = 0; i != (int)NumElts; ++i)
27440       ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
27441 
27442     SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
27443 
27444     // If we have a signed multiply but no PMULDQ fix up the result of an
27445     // unsigned multiply.
27446     if (IsSigned && !Subtarget.hasSSE41()) {
27447       SDValue Zero = DAG.getConstant(0, dl, VT);
27448       SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
27449                                DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
27450       SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
27451                                DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
27452 
27453       SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
27454       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
27455     }
27456 
27457     return Res;
27458   }
27459 
27460   // Only i8 vectors should need custom lowering after this.
27461   assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
27462          (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
27463          "Unsupported vector type");
27464 
27465   // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
27466   // logical shift down the upper half and pack back to i8.
27467 
27468   // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
27469   // and then ashr/lshr the upper bits down to the lower bits before multiply.
27470   unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
27471 
27472   if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
27473       (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
27474     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
27475     SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
27476     SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
27477     SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
27478     Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
27479     return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
27480   }
27481 
27482   // For vXi8 we will unpack the low and high half of each 128 bit lane to widen
27483   // to a vXi16 type. Do the multiplies, shift the results and pack the half
27484   // lane results back together.
27485 
27486   MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27487 
27488   static const int PSHUFDMask[] = { 8,  9, 10, 11, 12, 13, 14, 15,
27489                                    -1, -1, -1, -1, -1, -1, -1, -1};
27490 
27491   // Extract the lo parts and zero/sign extend to i16.
27492   // Only use SSE4.1 instructions for signed v16i8 where using unpack requires
27493   // shifts to sign extend. Using unpack for unsigned only requires an xor to
27494   // create zeros and a copy due to tied registers contraints pre-avx. But using
27495   // zero_extend_vector_inreg would require an additional pshufd for the high
27496   // part.
27497 
27498   SDValue ALo, AHi;
27499   if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
27500     ALo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, A);
27501 
27502     AHi = DAG.getVectorShuffle(VT, dl, A, A, PSHUFDMask);
27503     AHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, AHi);
27504   } else if (IsSigned) {
27505     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), A));
27506     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), A));
27507 
27508     ALo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, ALo, 8, DAG);
27509     AHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, AHi, 8, DAG);
27510   } else {
27511     ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A,
27512                                           DAG.getConstant(0, dl, VT)));
27513     AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A,
27514                                           DAG.getConstant(0, dl, VT)));
27515   }
27516 
27517   SDValue BLo, BHi;
27518   if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
27519     // If the LHS is a constant, manually unpackl/unpackh and extend.
27520     SmallVector<SDValue, 16> LoOps, HiOps;
27521     for (unsigned i = 0; i != NumElts; i += 16) {
27522       for (unsigned j = 0; j != 8; ++j) {
27523         SDValue LoOp = B.getOperand(i + j);
27524         SDValue HiOp = B.getOperand(i + j + 8);
27525 
27526         if (IsSigned) {
27527           LoOp = DAG.getSExtOrTrunc(LoOp, dl, MVT::i16);
27528           HiOp = DAG.getSExtOrTrunc(HiOp, dl, MVT::i16);
27529         } else {
27530           LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
27531           HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
27532         }
27533 
27534         LoOps.push_back(LoOp);
27535         HiOps.push_back(HiOp);
27536       }
27537     }
27538 
27539     BLo = DAG.getBuildVector(ExVT, dl, LoOps);
27540     BHi = DAG.getBuildVector(ExVT, dl, HiOps);
27541   } else if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
27542     BLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, B);
27543 
27544     BHi = DAG.getVectorShuffle(VT, dl, B, B, PSHUFDMask);
27545     BHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, BHi);
27546   } else if (IsSigned) {
27547     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), B));
27548     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), B));
27549 
27550     BLo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BLo, 8, DAG);
27551     BHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BHi, 8, DAG);
27552   } else {
27553     BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B,
27554                                           DAG.getConstant(0, dl, VT)));
27555     BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B,
27556                                           DAG.getConstant(0, dl, VT)));
27557   }
27558 
27559   // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
27560   // pack back to vXi8.
27561   SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
27562   SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
27563   RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RLo, 8, DAG);
27564   RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RHi, 8, DAG);
27565 
27566   // Bitcast back to VT and then pack all the even elements from Lo and Hi.
27567   return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
27568 }
27569 
27570 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
27571   assert(Subtarget.isTargetWin64() && "Unexpected target");
27572   EVT VT = Op.getValueType();
27573   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
27574          "Unexpected return type for lowering");
27575 
27576   RTLIB::Libcall LC;
27577   bool isSigned;
27578   switch (Op->getOpcode()) {
27579   default: llvm_unreachable("Unexpected request for libcall!");
27580   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
27581   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
27582   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
27583   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
27584   }
27585 
27586   SDLoc dl(Op);
27587   SDValue InChain = DAG.getEntryNode();
27588 
27589   TargetLowering::ArgListTy Args;
27590   TargetLowering::ArgListEntry Entry;
27591   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
27592     EVT ArgVT = Op->getOperand(i).getValueType();
27593     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
27594            "Unexpected argument type for lowering");
27595     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
27596     int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
27597     MachinePointerInfo MPI =
27598         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
27599     Entry.Node = StackPtr;
27600     InChain =
27601         DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MPI, Align(16));
27602     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
27603     Entry.Ty = PointerType::get(ArgTy,0);
27604     Entry.IsSExt = false;
27605     Entry.IsZExt = false;
27606     Args.push_back(Entry);
27607   }
27608 
27609   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
27610                                          getPointerTy(DAG.getDataLayout()));
27611 
27612   TargetLowering::CallLoweringInfo CLI(DAG);
27613   CLI.setDebugLoc(dl)
27614       .setChain(InChain)
27615       .setLibCallee(
27616           getLibcallCallingConv(LC),
27617           static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
27618           std::move(Args))
27619       .setInRegister()
27620       .setSExtResult(isSigned)
27621       .setZExtResult(!isSigned);
27622 
27623   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
27624   return DAG.getBitcast(VT, CallInfo.first);
27625 }
27626 
27627 // Return true if the required (according to Opcode) shift-imm form is natively
27628 // supported by the Subtarget
27629 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
27630                                         unsigned Opcode) {
27631   if (VT.getScalarSizeInBits() < 16)
27632     return false;
27633 
27634   if (VT.is512BitVector() && Subtarget.hasAVX512() &&
27635       (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
27636     return true;
27637 
27638   bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
27639                 (VT.is256BitVector() && Subtarget.hasInt256());
27640 
27641   bool AShift = LShift && (Subtarget.hasAVX512() ||
27642                            (VT != MVT::v2i64 && VT != MVT::v4i64));
27643   return (Opcode == ISD::SRA) ? AShift : LShift;
27644 }
27645 
27646 // The shift amount is a variable, but it is the same for all vector lanes.
27647 // These instructions are defined together with shift-immediate.
27648 static
27649 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
27650                                       unsigned Opcode) {
27651   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
27652 }
27653 
27654 // Return true if the required (according to Opcode) variable-shift form is
27655 // natively supported by the Subtarget
27656 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
27657                                     unsigned Opcode) {
27658 
27659   if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
27660     return false;
27661 
27662   // vXi16 supported only on AVX-512, BWI
27663   if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
27664     return false;
27665 
27666   if (Subtarget.hasAVX512())
27667     return true;
27668 
27669   bool LShift = VT.is128BitVector() || VT.is256BitVector();
27670   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
27671   return (Opcode == ISD::SRA) ? AShift : LShift;
27672 }
27673 
27674 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
27675                                          const X86Subtarget &Subtarget) {
27676   MVT VT = Op.getSimpleValueType();
27677   SDLoc dl(Op);
27678   SDValue R = Op.getOperand(0);
27679   SDValue Amt = Op.getOperand(1);
27680   unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
27681 
27682   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
27683     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
27684     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
27685     SDValue Ex = DAG.getBitcast(ExVT, R);
27686 
27687     // ashr(R, 63) === cmp_slt(R, 0)
27688     if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
27689       assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&
27690              "Unsupported PCMPGT op");
27691       return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
27692     }
27693 
27694     if (ShiftAmt >= 32) {
27695       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
27696       SDValue Upper =
27697           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
27698       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
27699                                                  ShiftAmt - 32, DAG);
27700       if (VT == MVT::v2i64)
27701         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
27702       if (VT == MVT::v4i64)
27703         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
27704                                   {9, 1, 11, 3, 13, 5, 15, 7});
27705     } else {
27706       // SRA upper i32, SRL whole i64 and select lower i32.
27707       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
27708                                                  ShiftAmt, DAG);
27709       SDValue Lower =
27710           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
27711       Lower = DAG.getBitcast(ExVT, Lower);
27712       if (VT == MVT::v2i64)
27713         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
27714       if (VT == MVT::v4i64)
27715         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
27716                                   {8, 1, 10, 3, 12, 5, 14, 7});
27717     }
27718     return DAG.getBitcast(VT, Ex);
27719   };
27720 
27721   // Optimize shl/srl/sra with constant shift amount.
27722   APInt APIntShiftAmt;
27723   if (!X86::isConstantSplat(Amt, APIntShiftAmt))
27724     return SDValue();
27725 
27726   // If the shift amount is out of range, return undef.
27727   if (APIntShiftAmt.uge(VT.getScalarSizeInBits()))
27728     return DAG.getUNDEF(VT);
27729 
27730   uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
27731 
27732   if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
27733     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
27734 
27735   // i64 SRA needs to be performed as partial shifts.
27736   if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
27737        (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
27738       Op.getOpcode() == ISD::SRA)
27739     return ArithmeticShiftRight64(ShiftAmt);
27740 
27741   if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
27742       (Subtarget.hasBWI() && VT == MVT::v64i8)) {
27743     unsigned NumElts = VT.getVectorNumElements();
27744     MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27745 
27746     // Simple i8 add case
27747     if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
27748       return DAG.getNode(ISD::ADD, dl, VT, R, R);
27749 
27750     // ashr(R, 7)  === cmp_slt(R, 0)
27751     if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
27752       SDValue Zeros = DAG.getConstant(0, dl, VT);
27753       if (VT.is512BitVector()) {
27754         assert(VT == MVT::v64i8 && "Unexpected element type!");
27755         SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
27756         return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
27757       }
27758       return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
27759     }
27760 
27761     // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
27762     if (VT == MVT::v16i8 && Subtarget.hasXOP())
27763       return SDValue();
27764 
27765     if (Op.getOpcode() == ISD::SHL) {
27766       // Make a large shift.
27767       SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
27768                                                ShiftAmt, DAG);
27769       SHL = DAG.getBitcast(VT, SHL);
27770       // Zero out the rightmost bits.
27771       APInt Mask = APInt::getHighBitsSet(8, 8 - ShiftAmt);
27772       return DAG.getNode(ISD::AND, dl, VT, SHL, DAG.getConstant(Mask, dl, VT));
27773     }
27774     if (Op.getOpcode() == ISD::SRL) {
27775       // Make a large shift.
27776       SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
27777                                                ShiftAmt, DAG);
27778       SRL = DAG.getBitcast(VT, SRL);
27779       // Zero out the leftmost bits.
27780       return DAG.getNode(ISD::AND, dl, VT, SRL,
27781                          DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
27782     }
27783     if (Op.getOpcode() == ISD::SRA) {
27784       // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
27785       SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
27786 
27787       SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
27788       Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
27789       Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
27790       return Res;
27791     }
27792     llvm_unreachable("Unknown shift opcode.");
27793   }
27794 
27795   return SDValue();
27796 }
27797 
27798 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
27799                                         const X86Subtarget &Subtarget) {
27800   MVT VT = Op.getSimpleValueType();
27801   SDLoc dl(Op);
27802   SDValue R = Op.getOperand(0);
27803   SDValue Amt = Op.getOperand(1);
27804   unsigned Opcode = Op.getOpcode();
27805   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
27806   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
27807 
27808   if (SDValue BaseShAmt = DAG.getSplatValue(Amt)) {
27809     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
27810       MVT EltVT = VT.getVectorElementType();
27811       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
27812       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
27813         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
27814       else if (EltVT.bitsLT(MVT::i32))
27815         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
27816 
27817       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
27818     }
27819 
27820     // vXi8 shifts - shift as v8i16 + mask result.
27821     if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
27822          (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
27823          VT == MVT::v64i8) &&
27824         !Subtarget.hasXOP()) {
27825       unsigned NumElts = VT.getVectorNumElements();
27826       MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
27827       if (SupportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
27828         unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
27829         unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
27830         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
27831 
27832         // Create the mask using vXi16 shifts. For shift-rights we need to move
27833         // the upper byte down before splatting the vXi8 mask.
27834         SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
27835         BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
27836                                       BaseShAmt, Subtarget, DAG);
27837         if (Opcode != ISD::SHL)
27838           BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
27839                                                8, DAG);
27840         BitMask = DAG.getBitcast(VT, BitMask);
27841         BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
27842                                        SmallVector<int, 64>(NumElts, 0));
27843 
27844         SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
27845                                           DAG.getBitcast(ExtVT, R), BaseShAmt,
27846                                           Subtarget, DAG);
27847         Res = DAG.getBitcast(VT, Res);
27848         Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
27849 
27850         if (Opcode == ISD::SRA) {
27851           // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
27852           // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
27853           SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
27854           SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
27855                                          BaseShAmt, Subtarget, DAG);
27856           SignMask = DAG.getBitcast(VT, SignMask);
27857           Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
27858           Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
27859         }
27860         return Res;
27861       }
27862     }
27863   }
27864 
27865   // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
27866   if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
27867       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
27868     Amt = Amt.getOperand(0);
27869     unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
27870     std::vector<SDValue> Vals(Ratio);
27871     for (unsigned i = 0; i != Ratio; ++i)
27872       Vals[i] = Amt.getOperand(i);
27873     for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
27874       for (unsigned j = 0; j != Ratio; ++j)
27875         if (Vals[j] != Amt.getOperand(i + j))
27876           return SDValue();
27877     }
27878 
27879     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
27880       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
27881   }
27882   return SDValue();
27883 }
27884 
27885 // Convert a shift/rotate left amount to a multiplication scale factor.
27886 static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
27887                                        const X86Subtarget &Subtarget,
27888                                        SelectionDAG &DAG) {
27889   MVT VT = Amt.getSimpleValueType();
27890   if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
27891         (Subtarget.hasInt256() && VT == MVT::v16i16) ||
27892         (Subtarget.hasVBMI2() && VT == MVT::v32i16) ||
27893         (!Subtarget.hasAVX512() && VT == MVT::v16i8)))
27894     return SDValue();
27895 
27896   if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
27897     SmallVector<SDValue, 8> Elts;
27898     MVT SVT = VT.getVectorElementType();
27899     unsigned SVTBits = SVT.getSizeInBits();
27900     APInt One(SVTBits, 1);
27901     unsigned NumElems = VT.getVectorNumElements();
27902 
27903     for (unsigned i = 0; i != NumElems; ++i) {
27904       SDValue Op = Amt->getOperand(i);
27905       if (Op->isUndef()) {
27906         Elts.push_back(Op);
27907         continue;
27908       }
27909 
27910       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
27911       APInt C(SVTBits, ND->getZExtValue());
27912       uint64_t ShAmt = C.getZExtValue();
27913       if (ShAmt >= SVTBits) {
27914         Elts.push_back(DAG.getUNDEF(SVT));
27915         continue;
27916       }
27917       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
27918     }
27919     return DAG.getBuildVector(VT, dl, Elts);
27920   }
27921 
27922   // If the target doesn't support variable shifts, use either FP conversion
27923   // or integer multiplication to avoid shifting each element individually.
27924   if (VT == MVT::v4i32) {
27925     Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
27926     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
27927                       DAG.getConstant(0x3f800000U, dl, VT));
27928     Amt = DAG.getBitcast(MVT::v4f32, Amt);
27929     return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
27930   }
27931 
27932   // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
27933   if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
27934     SDValue Z = DAG.getConstant(0, dl, VT);
27935     SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
27936     SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
27937     Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
27938     Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
27939     if (Subtarget.hasSSE41())
27940       return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
27941 
27942     return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, Lo),
27943                                         DAG.getBitcast(VT, Hi),
27944                                         {0, 2, 4, 6, 8, 10, 12, 14});
27945   }
27946 
27947   return SDValue();
27948 }
27949 
27950 static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
27951                           SelectionDAG &DAG) {
27952   MVT VT = Op.getSimpleValueType();
27953   SDLoc dl(Op);
27954   SDValue R = Op.getOperand(0);
27955   SDValue Amt = Op.getOperand(1);
27956   unsigned EltSizeInBits = VT.getScalarSizeInBits();
27957   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
27958 
27959   unsigned Opc = Op.getOpcode();
27960   unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
27961   unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
27962 
27963   assert(VT.isVector() && "Custom lowering only for vector shifts!");
27964   assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!");
27965 
27966   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
27967     return V;
27968 
27969   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
27970     return V;
27971 
27972   if (SupportedVectorVarShift(VT, Subtarget, Opc))
27973     return Op;
27974 
27975   // XOP has 128-bit variable logical/arithmetic shifts.
27976   // +ve/-ve Amt = shift left/right.
27977   if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
27978                              VT == MVT::v8i16 || VT == MVT::v16i8)) {
27979     if (Opc == ISD::SRL || Opc == ISD::SRA) {
27980       SDValue Zero = DAG.getConstant(0, dl, VT);
27981       Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
27982     }
27983     if (Opc == ISD::SHL || Opc == ISD::SRL)
27984       return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
27985     if (Opc == ISD::SRA)
27986       return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
27987   }
27988 
27989   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
27990   // shifts per-lane and then shuffle the partial results back together.
27991   if (VT == MVT::v2i64 && Opc != ISD::SRA) {
27992     // Splat the shift amounts so the scalar shifts above will catch it.
27993     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
27994     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
27995     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
27996     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
27997     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
27998   }
27999 
28000   // i64 vector arithmetic shift can be emulated with the transform:
28001   // M = lshr(SIGN_MASK, Amt)
28002   // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
28003   if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
28004       Opc == ISD::SRA) {
28005     SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
28006     SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
28007     R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
28008     R = DAG.getNode(ISD::XOR, dl, VT, R, M);
28009     R = DAG.getNode(ISD::SUB, dl, VT, R, M);
28010     return R;
28011   }
28012 
28013   // If possible, lower this shift as a sequence of two shifts by
28014   // constant plus a BLENDing shuffle instead of scalarizing it.
28015   // Example:
28016   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
28017   //
28018   // Could be rewritten as:
28019   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
28020   //
28021   // The advantage is that the two shifts from the example would be
28022   // lowered as X86ISD::VSRLI nodes in parallel before blending.
28023   if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
28024                       (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
28025     SDValue Amt1, Amt2;
28026     unsigned NumElts = VT.getVectorNumElements();
28027     SmallVector<int, 8> ShuffleMask;
28028     for (unsigned i = 0; i != NumElts; ++i) {
28029       SDValue A = Amt->getOperand(i);
28030       if (A.isUndef()) {
28031         ShuffleMask.push_back(SM_SentinelUndef);
28032         continue;
28033       }
28034       if (!Amt1 || Amt1 == A) {
28035         ShuffleMask.push_back(i);
28036         Amt1 = A;
28037         continue;
28038       }
28039       if (!Amt2 || Amt2 == A) {
28040         ShuffleMask.push_back(i + NumElts);
28041         Amt2 = A;
28042         continue;
28043       }
28044       break;
28045     }
28046 
28047     // Only perform this blend if we can perform it without loading a mask.
28048     if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
28049         (VT != MVT::v16i16 ||
28050          is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
28051         (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
28052          canWidenShuffleElements(ShuffleMask))) {
28053       auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
28054       auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
28055       if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
28056           Cst2->getAPIntValue().ult(EltSizeInBits)) {
28057         SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
28058                                                     Cst1->getZExtValue(), DAG);
28059         SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
28060                                                     Cst2->getZExtValue(), DAG);
28061         return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
28062       }
28063     }
28064   }
28065 
28066   // If possible, lower this packed shift into a vector multiply instead of
28067   // expanding it into a sequence of scalar shifts.
28068   if (Opc == ISD::SHL)
28069     if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
28070       return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
28071 
28072   // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
28073   // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
28074   if (Opc == ISD::SRL && ConstantAmt &&
28075       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
28076     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
28077     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
28078     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
28079       SDValue Zero = DAG.getConstant(0, dl, VT);
28080       SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
28081       SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
28082       return DAG.getSelect(dl, VT, ZAmt, R, Res);
28083     }
28084   }
28085 
28086   // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
28087   // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
28088   // TODO: Special case handling for shift by 0/1, really we can afford either
28089   // of these cases in pre-SSE41/XOP/AVX512 but not both.
28090   if (Opc == ISD::SRA && ConstantAmt &&
28091       (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
28092       ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
28093         !Subtarget.hasAVX512()) ||
28094        DAG.isKnownNeverZero(Amt))) {
28095     SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
28096     SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
28097     if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
28098       SDValue Amt0 =
28099           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
28100       SDValue Amt1 =
28101           DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
28102       SDValue Sra1 =
28103           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
28104       SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
28105       Res = DAG.getSelect(dl, VT, Amt0, R, Res);
28106       return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
28107     }
28108   }
28109 
28110   // v4i32 Non Uniform Shifts.
28111   // If the shift amount is constant we can shift each lane using the SSE2
28112   // immediate shifts, else we need to zero-extend each lane to the lower i64
28113   // and shift using the SSE2 variable shifts.
28114   // The separate results can then be blended together.
28115   if (VT == MVT::v4i32) {
28116     SDValue Amt0, Amt1, Amt2, Amt3;
28117     if (ConstantAmt) {
28118       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
28119       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
28120       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
28121       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
28122     } else {
28123       // The SSE2 shifts use the lower i64 as the same shift amount for
28124       // all lanes and the upper i64 is ignored. On AVX we're better off
28125       // just zero-extending, but for SSE just duplicating the top 16-bits is
28126       // cheaper and has the same effect for out of range values.
28127       if (Subtarget.hasAVX()) {
28128         SDValue Z = DAG.getConstant(0, dl, VT);
28129         Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
28130         Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
28131         Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
28132         Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
28133       } else {
28134         SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
28135         SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
28136                                              {4, 5, 6, 7, -1, -1, -1, -1});
28137         Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
28138                                     {0, 1, 1, 1, -1, -1, -1, -1});
28139         Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
28140                                     {2, 3, 3, 3, -1, -1, -1, -1});
28141         Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
28142                                     {0, 1, 1, 1, -1, -1, -1, -1});
28143         Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
28144                                     {2, 3, 3, 3, -1, -1, -1, -1});
28145       }
28146     }
28147 
28148     unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
28149     SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
28150     SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
28151     SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
28152     SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
28153 
28154     // Merge the shifted lane results optimally with/without PBLENDW.
28155     // TODO - ideally shuffle combining would handle this.
28156     if (Subtarget.hasSSE41()) {
28157       SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
28158       SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
28159       return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
28160     }
28161     SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
28162     SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
28163     return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
28164   }
28165 
28166   // It's worth extending once and using the vXi16/vXi32 shifts for smaller
28167   // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
28168   // make the existing SSE solution better.
28169   // NOTE: We honor prefered vector width before promoting to 512-bits.
28170   if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
28171       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
28172       (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
28173       (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
28174       (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
28175     assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&
28176            "Unexpected vector type");
28177     MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
28178     MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
28179     unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
28180     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
28181     Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
28182     return DAG.getNode(ISD::TRUNCATE, dl, VT,
28183                        DAG.getNode(Opc, dl, ExtVT, R, Amt));
28184   }
28185 
28186   // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
28187   // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
28188   if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
28189       (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||
28190        (VT == MVT::v64i8 && Subtarget.hasBWI())) &&
28191       !Subtarget.hasXOP()) {
28192     int NumElts = VT.getVectorNumElements();
28193     SDValue Cst8 = DAG.getTargetConstant(8, dl, MVT::i8);
28194 
28195     // Extend constant shift amount to vXi16 (it doesn't matter if the type
28196     // isn't legal).
28197     MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
28198     Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
28199     Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
28200     Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
28201     assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
28202            "Constant build vector expected");
28203 
28204     if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
28205       R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
28206                           : DAG.getZExtOrTrunc(R, dl, ExVT);
28207       R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
28208       R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
28209       return DAG.getZExtOrTrunc(R, dl, VT);
28210     }
28211 
28212     SmallVector<SDValue, 16> LoAmt, HiAmt;
28213     for (int i = 0; i != NumElts; i += 16) {
28214       for (int j = 0; j != 8; ++j) {
28215         LoAmt.push_back(Amt.getOperand(i + j));
28216         HiAmt.push_back(Amt.getOperand(i + j + 8));
28217       }
28218     }
28219 
28220     MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
28221     SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
28222     SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
28223 
28224     SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
28225     SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
28226     LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
28227     HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
28228     LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
28229     HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
28230     LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
28231     HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
28232     return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
28233   }
28234 
28235   if (VT == MVT::v16i8 ||
28236       (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
28237       (VT == MVT::v64i8 && Subtarget.hasBWI())) {
28238     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
28239 
28240     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
28241       if (VT.is512BitVector()) {
28242         // On AVX512BW targets we make use of the fact that VSELECT lowers
28243         // to a masked blend which selects bytes based just on the sign bit
28244         // extracted to a mask.
28245         MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
28246         V0 = DAG.getBitcast(VT, V0);
28247         V1 = DAG.getBitcast(VT, V1);
28248         Sel = DAG.getBitcast(VT, Sel);
28249         Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
28250                            ISD::SETGT);
28251         return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
28252       } else if (Subtarget.hasSSE41()) {
28253         // On SSE41 targets we can use PBLENDVB which selects bytes based just
28254         // on the sign bit.
28255         V0 = DAG.getBitcast(VT, V0);
28256         V1 = DAG.getBitcast(VT, V1);
28257         Sel = DAG.getBitcast(VT, Sel);
28258         return DAG.getBitcast(SelVT,
28259                               DAG.getNode(X86ISD::BLENDV, dl, VT, Sel, V0, V1));
28260       }
28261       // On pre-SSE41 targets we test for the sign bit by comparing to
28262       // zero - a negative value will set all bits of the lanes to true
28263       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
28264       SDValue Z = DAG.getConstant(0, dl, SelVT);
28265       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
28266       return DAG.getSelect(dl, SelVT, C, V0, V1);
28267     };
28268 
28269     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
28270     // We can safely do this using i16 shifts as we're only interested in
28271     // the 3 lower bits of each byte.
28272     Amt = DAG.getBitcast(ExtVT, Amt);
28273     Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
28274     Amt = DAG.getBitcast(VT, Amt);
28275 
28276     if (Opc == ISD::SHL || Opc == ISD::SRL) {
28277       // r = VSELECT(r, shift(r, 4), a);
28278       SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
28279       R = SignBitSelect(VT, Amt, M, R);
28280 
28281       // a += a
28282       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28283 
28284       // r = VSELECT(r, shift(r, 2), a);
28285       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
28286       R = SignBitSelect(VT, Amt, M, R);
28287 
28288       // a += a
28289       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28290 
28291       // return VSELECT(r, shift(r, 1), a);
28292       M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
28293       R = SignBitSelect(VT, Amt, M, R);
28294       return R;
28295     }
28296 
28297     if (Opc == ISD::SRA) {
28298       // For SRA we need to unpack each byte to the higher byte of a i16 vector
28299       // so we can correctly sign extend. We don't care what happens to the
28300       // lower byte.
28301       SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
28302       SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
28303       SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
28304       SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
28305       ALo = DAG.getBitcast(ExtVT, ALo);
28306       AHi = DAG.getBitcast(ExtVT, AHi);
28307       RLo = DAG.getBitcast(ExtVT, RLo);
28308       RHi = DAG.getBitcast(ExtVT, RHi);
28309 
28310       // r = VSELECT(r, shift(r, 4), a);
28311       SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
28312       SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
28313       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
28314       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
28315 
28316       // a += a
28317       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
28318       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
28319 
28320       // r = VSELECT(r, shift(r, 2), a);
28321       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
28322       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
28323       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
28324       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
28325 
28326       // a += a
28327       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
28328       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
28329 
28330       // r = VSELECT(r, shift(r, 1), a);
28331       MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
28332       MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
28333       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
28334       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
28335 
28336       // Logical shift the result back to the lower byte, leaving a zero upper
28337       // byte meaning that we can safely pack with PACKUSWB.
28338       RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
28339       RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
28340       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
28341     }
28342   }
28343 
28344   if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
28345     MVT ExtVT = MVT::v8i32;
28346     SDValue Z = DAG.getConstant(0, dl, VT);
28347     SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
28348     SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
28349     SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
28350     SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
28351     ALo = DAG.getBitcast(ExtVT, ALo);
28352     AHi = DAG.getBitcast(ExtVT, AHi);
28353     RLo = DAG.getBitcast(ExtVT, RLo);
28354     RHi = DAG.getBitcast(ExtVT, RHi);
28355     SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
28356     SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
28357     Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
28358     Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
28359     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
28360   }
28361 
28362   if (VT == MVT::v8i16) {
28363     // If we have a constant shift amount, the non-SSE41 path is best as
28364     // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
28365     bool UseSSE41 = Subtarget.hasSSE41() &&
28366                     !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
28367 
28368     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
28369       // On SSE41 targets we can use PBLENDVB which selects bytes based just on
28370       // the sign bit.
28371       if (UseSSE41) {
28372         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
28373         V0 = DAG.getBitcast(ExtVT, V0);
28374         V1 = DAG.getBitcast(ExtVT, V1);
28375         Sel = DAG.getBitcast(ExtVT, Sel);
28376         return DAG.getBitcast(
28377             VT, DAG.getNode(X86ISD::BLENDV, dl, ExtVT, Sel, V0, V1));
28378       }
28379       // On pre-SSE41 targets we splat the sign bit - a negative value will
28380       // set all bits of the lanes to true and VSELECT uses that in
28381       // its OR(AND(V0,C),AND(V1,~C)) lowering.
28382       SDValue C =
28383           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
28384       return DAG.getSelect(dl, VT, C, V0, V1);
28385     };
28386 
28387     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
28388     if (UseSSE41) {
28389       // On SSE41 targets we need to replicate the shift mask in both
28390       // bytes for PBLENDVB.
28391       Amt = DAG.getNode(
28392           ISD::OR, dl, VT,
28393           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
28394           getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
28395     } else {
28396       Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
28397     }
28398 
28399     // r = VSELECT(r, shift(r, 8), a);
28400     SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
28401     R = SignBitSelect(Amt, M, R);
28402 
28403     // a += a
28404     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28405 
28406     // r = VSELECT(r, shift(r, 4), a);
28407     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
28408     R = SignBitSelect(Amt, M, R);
28409 
28410     // a += a
28411     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28412 
28413     // r = VSELECT(r, shift(r, 2), a);
28414     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
28415     R = SignBitSelect(Amt, M, R);
28416 
28417     // a += a
28418     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
28419 
28420     // return VSELECT(r, shift(r, 1), a);
28421     M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
28422     R = SignBitSelect(Amt, M, R);
28423     return R;
28424   }
28425 
28426   // Decompose 256-bit shifts into 128-bit shifts.
28427   if (VT.is256BitVector())
28428     return splitVectorIntBinary(Op, DAG);
28429 
28430   if (VT == MVT::v32i16 || VT == MVT::v64i8)
28431     return splitVectorIntBinary(Op, DAG);
28432 
28433   return SDValue();
28434 }
28435 
28436 static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
28437                            SelectionDAG &DAG) {
28438   MVT VT = Op.getSimpleValueType();
28439   assert(VT.isVector() && "Custom lowering only for vector rotates!");
28440 
28441   SDLoc DL(Op);
28442   SDValue R = Op.getOperand(0);
28443   SDValue Amt = Op.getOperand(1);
28444   unsigned Opcode = Op.getOpcode();
28445   unsigned EltSizeInBits = VT.getScalarSizeInBits();
28446   int NumElts = VT.getVectorNumElements();
28447 
28448   // Check for constant splat rotation amount.
28449   APInt CstSplatValue;
28450   bool IsCstSplat = X86::isConstantSplat(Amt, CstSplatValue);
28451 
28452   // Check for splat rotate by zero.
28453   if (IsCstSplat && CstSplatValue.urem(EltSizeInBits) == 0)
28454     return R;
28455 
28456   // AVX512 implicitly uses modulo rotation amounts.
28457   if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
28458     // Attempt to rotate by immediate.
28459     if (IsCstSplat) {
28460       unsigned RotOpc = (Opcode == ISD::ROTL ? X86ISD::VROTLI : X86ISD::VROTRI);
28461       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
28462       return DAG.getNode(RotOpc, DL, VT, R,
28463                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
28464     }
28465 
28466     // Else, fall-back on VPROLV/VPRORV.
28467     return Op;
28468   }
28469 
28470   // AVX512 VBMI2 vXi16 - lower to funnel shifts.
28471   if (Subtarget.hasVBMI2() && 16 == EltSizeInBits) {
28472     unsigned FunnelOpc = (Opcode == ISD::ROTL ? ISD::FSHL : ISD::FSHR);
28473     return DAG.getNode(FunnelOpc, DL, VT, R, R, Amt);
28474   }
28475 
28476   assert((Opcode == ISD::ROTL) && "Only ROTL supported");
28477 
28478   // XOP has 128-bit vector variable + immediate rotates.
28479   // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
28480   // XOP implicitly uses modulo rotation amounts.
28481   if (Subtarget.hasXOP()) {
28482     if (VT.is256BitVector())
28483       return splitVectorIntBinary(Op, DAG);
28484     assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
28485 
28486     // Attempt to rotate by immediate.
28487     if (IsCstSplat) {
28488       uint64_t RotAmt = CstSplatValue.urem(EltSizeInBits);
28489       return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
28490                          DAG.getTargetConstant(RotAmt, DL, MVT::i8));
28491     }
28492 
28493     // Use general rotate by variable (per-element).
28494     return Op;
28495   }
28496 
28497   // Split 256-bit integers on pre-AVX2 targets.
28498   if (VT.is256BitVector() && !Subtarget.hasAVX2())
28499     return splitVectorIntBinary(Op, DAG);
28500 
28501   assert((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
28502           ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8 ||
28503             VT == MVT::v32i16) &&
28504            Subtarget.hasAVX2())) &&
28505          "Only vXi32/vXi16/vXi8 vector rotates supported");
28506 
28507   // Rotate by an uniform constant - expand back to shifts.
28508   if (IsCstSplat)
28509     return SDValue();
28510 
28511   bool IsSplatAmt = DAG.isSplatValue(Amt);
28512 
28513   // v16i8/v32i8: Split rotation into rot4/rot2/rot1 stages and select by
28514   // the amount bit.
28515   if (EltSizeInBits == 8 && !IsSplatAmt) {
28516     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()))
28517       return SDValue();
28518 
28519     // We don't need ModuloAmt here as we just peek at individual bits.
28520     MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
28521 
28522     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
28523       if (Subtarget.hasSSE41()) {
28524         // On SSE41 targets we can use PBLENDVB which selects bytes based just
28525         // on the sign bit.
28526         V0 = DAG.getBitcast(VT, V0);
28527         V1 = DAG.getBitcast(VT, V1);
28528         Sel = DAG.getBitcast(VT, Sel);
28529         return DAG.getBitcast(SelVT,
28530                               DAG.getNode(X86ISD::BLENDV, DL, VT, Sel, V0, V1));
28531       }
28532       // On pre-SSE41 targets we test for the sign bit by comparing to
28533       // zero - a negative value will set all bits of the lanes to true
28534       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
28535       SDValue Z = DAG.getConstant(0, DL, SelVT);
28536       SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
28537       return DAG.getSelect(DL, SelVT, C, V0, V1);
28538     };
28539 
28540     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
28541     // We can safely do this using i16 shifts as we're only interested in
28542     // the 3 lower bits of each byte.
28543     Amt = DAG.getBitcast(ExtVT, Amt);
28544     Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
28545     Amt = DAG.getBitcast(VT, Amt);
28546 
28547     // r = VSELECT(r, rot(r, 4), a);
28548     SDValue M;
28549     M = DAG.getNode(
28550         ISD::OR, DL, VT,
28551         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(4, DL, VT)),
28552         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(4, DL, VT)));
28553     R = SignBitSelect(VT, Amt, M, R);
28554 
28555     // a += a
28556     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
28557 
28558     // r = VSELECT(r, rot(r, 2), a);
28559     M = DAG.getNode(
28560         ISD::OR, DL, VT,
28561         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(2, DL, VT)),
28562         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(6, DL, VT)));
28563     R = SignBitSelect(VT, Amt, M, R);
28564 
28565     // a += a
28566     Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
28567 
28568     // return VSELECT(r, rot(r, 1), a);
28569     M = DAG.getNode(
28570         ISD::OR, DL, VT,
28571         DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(1, DL, VT)),
28572         DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(7, DL, VT)));
28573     return SignBitSelect(VT, Amt, M, R);
28574   }
28575 
28576   // ISD::ROT* uses modulo rotate amounts.
28577   Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
28578                     DAG.getConstant(EltSizeInBits - 1, DL, VT));
28579 
28580   bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
28581   bool LegalVarShifts = SupportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
28582                         SupportedVectorVarShift(VT, Subtarget, ISD::SRL);
28583 
28584   // Fallback for splats + all supported variable shifts.
28585   // Fallback for non-constants AVX2 vXi16 as well.
28586   if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
28587     SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
28588     AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
28589     SDValue SHL = DAG.getNode(ISD::SHL, DL, VT, R, Amt);
28590     SDValue SRL = DAG.getNode(ISD::SRL, DL, VT, R, AmtR);
28591     return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
28592   }
28593 
28594   // As with shifts, convert the rotation amount to a multiplication factor.
28595   SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
28596   assert(Scale && "Failed to convert ROTL amount to scale");
28597 
28598   // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
28599   if (EltSizeInBits == 16) {
28600     SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
28601     SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
28602     return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
28603   }
28604 
28605   // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
28606   // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
28607   // that can then be OR'd with the lower 32-bits.
28608   assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected");
28609   static const int OddMask[] = {1, -1, 3, -1};
28610   SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
28611   SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
28612 
28613   SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
28614                               DAG.getBitcast(MVT::v2i64, R),
28615                               DAG.getBitcast(MVT::v2i64, Scale));
28616   SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
28617                               DAG.getBitcast(MVT::v2i64, R13),
28618                               DAG.getBitcast(MVT::v2i64, Scale13));
28619   Res02 = DAG.getBitcast(VT, Res02);
28620   Res13 = DAG.getBitcast(VT, Res13);
28621 
28622   return DAG.getNode(ISD::OR, DL, VT,
28623                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
28624                      DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
28625 }
28626 
28627 /// Returns true if the operand type is exactly twice the native width, and
28628 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
28629 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
28630 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
28631 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
28632   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
28633 
28634   if (OpWidth == 64)
28635     return Subtarget.hasCmpxchg8b() && !Subtarget.is64Bit();
28636   if (OpWidth == 128)
28637     return Subtarget.hasCmpxchg16b();
28638 
28639   return false;
28640 }
28641 
28642 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
28643   Type *MemType = SI->getValueOperand()->getType();
28644 
28645   bool NoImplicitFloatOps =
28646       SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
28647   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
28648       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
28649       (Subtarget.hasSSE1() || Subtarget.hasX87()))
28650     return false;
28651 
28652   return needsCmpXchgNb(MemType);
28653 }
28654 
28655 // Note: this turns large loads into lock cmpxchg8b/16b.
28656 // TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
28657 TargetLowering::AtomicExpansionKind
28658 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
28659   Type *MemType = LI->getType();
28660 
28661   // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
28662   // can use movq to do the load. If we have X87 we can load into an 80-bit
28663   // X87 register and store it to a stack temporary.
28664   bool NoImplicitFloatOps =
28665       LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
28666   if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
28667       !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
28668       (Subtarget.hasSSE1() || Subtarget.hasX87()))
28669     return AtomicExpansionKind::None;
28670 
28671   return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
28672                                  : AtomicExpansionKind::None;
28673 }
28674 
28675 TargetLowering::AtomicExpansionKind
28676 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
28677   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
28678   Type *MemType = AI->getType();
28679 
28680   // If the operand is too big, we must see if cmpxchg8/16b is available
28681   // and default to library calls otherwise.
28682   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
28683     return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
28684                                    : AtomicExpansionKind::None;
28685   }
28686 
28687   AtomicRMWInst::BinOp Op = AI->getOperation();
28688   switch (Op) {
28689   default:
28690     llvm_unreachable("Unknown atomic operation");
28691   case AtomicRMWInst::Xchg:
28692   case AtomicRMWInst::Add:
28693   case AtomicRMWInst::Sub:
28694     // It's better to use xadd, xsub or xchg for these in all cases.
28695     return AtomicExpansionKind::None;
28696   case AtomicRMWInst::Or:
28697   case AtomicRMWInst::And:
28698   case AtomicRMWInst::Xor:
28699     // If the atomicrmw's result isn't actually used, we can just add a "lock"
28700     // prefix to a normal instruction for these operations.
28701     return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
28702                             : AtomicExpansionKind::None;
28703   case AtomicRMWInst::Nand:
28704   case AtomicRMWInst::Max:
28705   case AtomicRMWInst::Min:
28706   case AtomicRMWInst::UMax:
28707   case AtomicRMWInst::UMin:
28708   case AtomicRMWInst::FAdd:
28709   case AtomicRMWInst::FSub:
28710     // These always require a non-trivial set of data operations on x86. We must
28711     // use a cmpxchg loop.
28712     return AtomicExpansionKind::CmpXChg;
28713   }
28714 }
28715 
28716 LoadInst *
28717 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
28718   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
28719   Type *MemType = AI->getType();
28720   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
28721   // there is no benefit in turning such RMWs into loads, and it is actually
28722   // harmful as it introduces a mfence.
28723   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
28724     return nullptr;
28725 
28726   // If this is a canonical idempotent atomicrmw w/no uses, we have a better
28727   // lowering available in lowerAtomicArith.
28728   // TODO: push more cases through this path.
28729   if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
28730     if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
28731         AI->use_empty())
28732       return nullptr;
28733 
28734   IRBuilder<> Builder(AI);
28735   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
28736   auto SSID = AI->getSyncScopeID();
28737   // We must restrict the ordering to avoid generating loads with Release or
28738   // ReleaseAcquire orderings.
28739   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
28740 
28741   // Before the load we need a fence. Here is an example lifted from
28742   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
28743   // is required:
28744   // Thread 0:
28745   //   x.store(1, relaxed);
28746   //   r1 = y.fetch_add(0, release);
28747   // Thread 1:
28748   //   y.fetch_add(42, acquire);
28749   //   r2 = x.load(relaxed);
28750   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
28751   // lowered to just a load without a fence. A mfence flushes the store buffer,
28752   // making the optimization clearly correct.
28753   // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
28754   // otherwise, we might be able to be more aggressive on relaxed idempotent
28755   // rmw. In practice, they do not look useful, so we don't try to be
28756   // especially clever.
28757   if (SSID == SyncScope::SingleThread)
28758     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
28759     // the IR level, so we must wrap it in an intrinsic.
28760     return nullptr;
28761 
28762   if (!Subtarget.hasMFence())
28763     // FIXME: it might make sense to use a locked operation here but on a
28764     // different cache-line to prevent cache-line bouncing. In practice it
28765     // is probably a small win, and x86 processors without mfence are rare
28766     // enough that we do not bother.
28767     return nullptr;
28768 
28769   Function *MFence =
28770       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
28771   Builder.CreateCall(MFence, {});
28772 
28773   // Finally we can emit the atomic load.
28774   LoadInst *Loaded =
28775       Builder.CreateAlignedLoad(AI->getType(), AI->getPointerOperand(),
28776                                 Align(AI->getType()->getPrimitiveSizeInBits()));
28777   Loaded->setAtomic(Order, SSID);
28778   AI->replaceAllUsesWith(Loaded);
28779   AI->eraseFromParent();
28780   return Loaded;
28781 }
28782 
28783 bool X86TargetLowering::lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
28784   if (!SI.isUnordered())
28785     return false;
28786   return ExperimentalUnorderedISEL;
28787 }
28788 bool X86TargetLowering::lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
28789   if (!LI.isUnordered())
28790     return false;
28791   return ExperimentalUnorderedISEL;
28792 }
28793 
28794 
28795 /// Emit a locked operation on a stack location which does not change any
28796 /// memory location, but does involve a lock prefix.  Location is chosen to be
28797 /// a) very likely accessed only by a single thread to minimize cache traffic,
28798 /// and b) definitely dereferenceable.  Returns the new Chain result.
28799 static SDValue emitLockedStackOp(SelectionDAG &DAG,
28800                                  const X86Subtarget &Subtarget, SDValue Chain,
28801                                  const SDLoc &DL) {
28802   // Implementation notes:
28803   // 1) LOCK prefix creates a full read/write reordering barrier for memory
28804   // operations issued by the current processor.  As such, the location
28805   // referenced is not relevant for the ordering properties of the instruction.
28806   // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
28807   // 8.2.3.9  Loads and Stores Are Not Reordered with Locked Instructions
28808   // 2) Using an immediate operand appears to be the best encoding choice
28809   // here since it doesn't require an extra register.
28810   // 3) OR appears to be very slightly faster than ADD. (Though, the difference
28811   // is small enough it might just be measurement noise.)
28812   // 4) When choosing offsets, there are several contributing factors:
28813   //   a) If there's no redzone, we default to TOS.  (We could allocate a cache
28814   //      line aligned stack object to improve this case.)
28815   //   b) To minimize our chances of introducing a false dependence, we prefer
28816   //      to offset the stack usage from TOS slightly.
28817   //   c) To minimize concerns about cross thread stack usage - in particular,
28818   //      the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
28819   //      captures state in the TOS frame and accesses it from many threads -
28820   //      we want to use an offset such that the offset is in a distinct cache
28821   //      line from the TOS frame.
28822   //
28823   // For a general discussion of the tradeoffs and benchmark results, see:
28824   // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
28825 
28826   auto &MF = DAG.getMachineFunction();
28827   auto &TFL = *Subtarget.getFrameLowering();
28828   const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
28829 
28830   if (Subtarget.is64Bit()) {
28831     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
28832     SDValue Ops[] = {
28833       DAG.getRegister(X86::RSP, MVT::i64),                  // Base
28834       DAG.getTargetConstant(1, DL, MVT::i8),                // Scale
28835       DAG.getRegister(0, MVT::i64),                         // Index
28836       DAG.getTargetConstant(SPOffset, DL, MVT::i32),        // Disp
28837       DAG.getRegister(0, MVT::i16),                         // Segment.
28838       Zero,
28839       Chain};
28840     SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
28841                                      MVT::Other, Ops);
28842     return SDValue(Res, 1);
28843   }
28844 
28845   SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
28846   SDValue Ops[] = {
28847     DAG.getRegister(X86::ESP, MVT::i32),            // Base
28848     DAG.getTargetConstant(1, DL, MVT::i8),          // Scale
28849     DAG.getRegister(0, MVT::i32),                   // Index
28850     DAG.getTargetConstant(SPOffset, DL, MVT::i32),  // Disp
28851     DAG.getRegister(0, MVT::i16),                   // Segment.
28852     Zero,
28853     Chain
28854   };
28855   SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
28856                                    MVT::Other, Ops);
28857   return SDValue(Res, 1);
28858 }
28859 
28860 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
28861                                  SelectionDAG &DAG) {
28862   SDLoc dl(Op);
28863   AtomicOrdering FenceOrdering =
28864       static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
28865   SyncScope::ID FenceSSID =
28866       static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
28867 
28868   // The only fence that needs an instruction is a sequentially-consistent
28869   // cross-thread fence.
28870   if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
28871       FenceSSID == SyncScope::System) {
28872     if (Subtarget.hasMFence())
28873       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
28874 
28875     SDValue Chain = Op.getOperand(0);
28876     return emitLockedStackOp(DAG, Subtarget, Chain, dl);
28877   }
28878 
28879   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
28880   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
28881 }
28882 
28883 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
28884                              SelectionDAG &DAG) {
28885   MVT T = Op.getSimpleValueType();
28886   SDLoc DL(Op);
28887   unsigned Reg = 0;
28888   unsigned size = 0;
28889   switch(T.SimpleTy) {
28890   default: llvm_unreachable("Invalid value type!");
28891   case MVT::i8:  Reg = X86::AL;  size = 1; break;
28892   case MVT::i16: Reg = X86::AX;  size = 2; break;
28893   case MVT::i32: Reg = X86::EAX; size = 4; break;
28894   case MVT::i64:
28895     assert(Subtarget.is64Bit() && "Node not type legal!");
28896     Reg = X86::RAX; size = 8;
28897     break;
28898   }
28899   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
28900                                   Op.getOperand(2), SDValue());
28901   SDValue Ops[] = { cpIn.getValue(0),
28902                     Op.getOperand(1),
28903                     Op.getOperand(3),
28904                     DAG.getTargetConstant(size, DL, MVT::i8),
28905                     cpIn.getValue(1) };
28906   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
28907   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
28908   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
28909                                            Ops, T, MMO);
28910 
28911   SDValue cpOut =
28912     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
28913   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
28914                                       MVT::i32, cpOut.getValue(2));
28915   SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
28916 
28917   return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
28918                      cpOut, Success, EFLAGS.getValue(1));
28919 }
28920 
28921 // Create MOVMSKB, taking into account whether we need to split for AVX1.
28922 static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
28923                            const X86Subtarget &Subtarget) {
28924   MVT InVT = V.getSimpleValueType();
28925 
28926   if (InVT == MVT::v64i8) {
28927     SDValue Lo, Hi;
28928     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
28929     Lo = getPMOVMSKB(DL, Lo, DAG, Subtarget);
28930     Hi = getPMOVMSKB(DL, Hi, DAG, Subtarget);
28931     Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
28932     Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
28933     Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
28934                      DAG.getConstant(32, DL, MVT::i8));
28935     return DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
28936   }
28937   if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
28938     SDValue Lo, Hi;
28939     std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
28940     Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
28941     Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
28942     Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
28943                      DAG.getConstant(16, DL, MVT::i8));
28944     return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
28945   }
28946 
28947   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
28948 }
28949 
28950 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
28951                             SelectionDAG &DAG) {
28952   SDValue Src = Op.getOperand(0);
28953   MVT SrcVT = Src.getSimpleValueType();
28954   MVT DstVT = Op.getSimpleValueType();
28955 
28956   // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
28957   // half to v32i1 and concatenating the result.
28958   if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
28959     assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
28960     assert(Subtarget.hasBWI() && "Expected BWI target");
28961     SDLoc dl(Op);
28962     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
28963                              DAG.getIntPtrConstant(0, dl));
28964     Lo = DAG.getBitcast(MVT::v32i1, Lo);
28965     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
28966                              DAG.getIntPtrConstant(1, dl));
28967     Hi = DAG.getBitcast(MVT::v32i1, Hi);
28968     return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
28969   }
28970 
28971   // Use MOVMSK for vector to scalar conversion to prevent scalarization.
28972   if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
28973     assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512");
28974     MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
28975     SDLoc DL(Op);
28976     SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
28977     V = getPMOVMSKB(DL, V, DAG, Subtarget);
28978     return DAG.getZExtOrTrunc(V, DL, DstVT);
28979   }
28980 
28981   assert((SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
28982           SrcVT == MVT::i64) && "Unexpected VT!");
28983 
28984   assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
28985   if (!(DstVT == MVT::f64 && SrcVT == MVT::i64) &&
28986       !(DstVT == MVT::x86mmx && SrcVT.isVector()))
28987     // This conversion needs to be expanded.
28988     return SDValue();
28989 
28990   SDLoc dl(Op);
28991   if (SrcVT.isVector()) {
28992     // Widen the vector in input in the case of MVT::v2i32.
28993     // Example: from MVT::v2i32 to MVT::v4i32.
28994     MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
28995                                  SrcVT.getVectorNumElements() * 2);
28996     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
28997                       DAG.getUNDEF(SrcVT));
28998   } else {
28999     assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
29000            "Unexpected source type in LowerBITCAST");
29001     Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
29002   }
29003 
29004   MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
29005   Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
29006 
29007   if (DstVT == MVT::x86mmx)
29008     return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
29009 
29010   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
29011                      DAG.getIntPtrConstant(0, dl));
29012 }
29013 
29014 /// Compute the horizontal sum of bytes in V for the elements of VT.
29015 ///
29016 /// Requires V to be a byte vector and VT to be an integer vector type with
29017 /// wider elements than V's type. The width of the elements of VT determines
29018 /// how many bytes of V are summed horizontally to produce each element of the
29019 /// result.
29020 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
29021                                       const X86Subtarget &Subtarget,
29022                                       SelectionDAG &DAG) {
29023   SDLoc DL(V);
29024   MVT ByteVecVT = V.getSimpleValueType();
29025   MVT EltVT = VT.getVectorElementType();
29026   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
29027          "Expected value to have byte element type.");
29028   assert(EltVT != MVT::i8 &&
29029          "Horizontal byte sum only makes sense for wider elements!");
29030   unsigned VecSize = VT.getSizeInBits();
29031   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
29032 
29033   // PSADBW instruction horizontally add all bytes and leave the result in i64
29034   // chunks, thus directly computes the pop count for v2i64 and v4i64.
29035   if (EltVT == MVT::i64) {
29036     SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
29037     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
29038     V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
29039     return DAG.getBitcast(VT, V);
29040   }
29041 
29042   if (EltVT == MVT::i32) {
29043     // We unpack the low half and high half into i32s interleaved with zeros so
29044     // that we can use PSADBW to horizontally sum them. The most useful part of
29045     // this is that it lines up the results of two PSADBW instructions to be
29046     // two v2i64 vectors which concatenated are the 4 population counts. We can
29047     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
29048     SDValue Zeros = DAG.getConstant(0, DL, VT);
29049     SDValue V32 = DAG.getBitcast(VT, V);
29050     SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
29051     SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
29052 
29053     // Do the horizontal sums into two v2i64s.
29054     Zeros = DAG.getConstant(0, DL, ByteVecVT);
29055     MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
29056     Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
29057                       DAG.getBitcast(ByteVecVT, Low), Zeros);
29058     High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
29059                        DAG.getBitcast(ByteVecVT, High), Zeros);
29060 
29061     // Merge them together.
29062     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
29063     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
29064                     DAG.getBitcast(ShortVecVT, Low),
29065                     DAG.getBitcast(ShortVecVT, High));
29066 
29067     return DAG.getBitcast(VT, V);
29068   }
29069 
29070   // The only element type left is i16.
29071   assert(EltVT == MVT::i16 && "Unknown how to handle type");
29072 
29073   // To obtain pop count for each i16 element starting from the pop count for
29074   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
29075   // right by 8. It is important to shift as i16s as i8 vector shift isn't
29076   // directly supported.
29077   SDValue ShifterV = DAG.getConstant(8, DL, VT);
29078   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
29079   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
29080                   DAG.getBitcast(ByteVecVT, V));
29081   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
29082 }
29083 
29084 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
29085                                         const X86Subtarget &Subtarget,
29086                                         SelectionDAG &DAG) {
29087   MVT VT = Op.getSimpleValueType();
29088   MVT EltVT = VT.getVectorElementType();
29089   int NumElts = VT.getVectorNumElements();
29090   (void)EltVT;
29091   assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.");
29092 
29093   // Implement a lookup table in register by using an algorithm based on:
29094   // http://wm.ite.pl/articles/sse-popcount.html
29095   //
29096   // The general idea is that every lower byte nibble in the input vector is an
29097   // index into a in-register pre-computed pop count table. We then split up the
29098   // input vector in two new ones: (1) a vector with only the shifted-right
29099   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
29100   // masked out higher ones) for each byte. PSHUFB is used separately with both
29101   // to index the in-register table. Next, both are added and the result is a
29102   // i8 vector where each element contains the pop count for input byte.
29103   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
29104                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
29105                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
29106                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
29107 
29108   SmallVector<SDValue, 64> LUTVec;
29109   for (int i = 0; i < NumElts; ++i)
29110     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
29111   SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
29112   SDValue M0F = DAG.getConstant(0x0F, DL, VT);
29113 
29114   // High nibbles
29115   SDValue FourV = DAG.getConstant(4, DL, VT);
29116   SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
29117 
29118   // Low nibbles
29119   SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
29120 
29121   // The input vector is used as the shuffle mask that index elements into the
29122   // LUT. After counting low and high nibbles, add the vector to obtain the
29123   // final pop count per i8 element.
29124   SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
29125   SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
29126   return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
29127 }
29128 
29129 // Please ensure that any codegen change from LowerVectorCTPOP is reflected in
29130 // updated cost models in X86TTIImpl::getIntrinsicInstrCost.
29131 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
29132                                 SelectionDAG &DAG) {
29133   MVT VT = Op.getSimpleValueType();
29134   assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&
29135          "Unknown CTPOP type to handle");
29136   SDLoc DL(Op.getNode());
29137   SDValue Op0 = Op.getOperand(0);
29138 
29139   // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
29140   if (Subtarget.hasVPOPCNTDQ()) {
29141     unsigned NumElems = VT.getVectorNumElements();
29142     assert((VT.getVectorElementType() == MVT::i8 ||
29143             VT.getVectorElementType() == MVT::i16) && "Unexpected type");
29144     if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
29145       MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
29146       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
29147       Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
29148       return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
29149     }
29150   }
29151 
29152   // Decompose 256-bit ops into smaller 128-bit ops.
29153   if (VT.is256BitVector() && !Subtarget.hasInt256())
29154     return splitVectorIntUnary(Op, DAG);
29155 
29156   // Decompose 512-bit ops into smaller 256-bit ops.
29157   if (VT.is512BitVector() && !Subtarget.hasBWI())
29158     return splitVectorIntUnary(Op, DAG);
29159 
29160   // For element types greater than i8, do vXi8 pop counts and a bytesum.
29161   if (VT.getScalarType() != MVT::i8) {
29162     MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
29163     SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
29164     SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
29165     return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
29166   }
29167 
29168   // We can't use the fast LUT approach, so fall back on LegalizeDAG.
29169   if (!Subtarget.hasSSSE3())
29170     return SDValue();
29171 
29172   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
29173 }
29174 
29175 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
29176                           SelectionDAG &DAG) {
29177   assert(Op.getSimpleValueType().isVector() &&
29178          "We only do custom lowering for vector population count.");
29179   return LowerVectorCTPOP(Op, Subtarget, DAG);
29180 }
29181 
29182 static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
29183   MVT VT = Op.getSimpleValueType();
29184   SDValue In = Op.getOperand(0);
29185   SDLoc DL(Op);
29186 
29187   // For scalars, its still beneficial to transfer to/from the SIMD unit to
29188   // perform the BITREVERSE.
29189   if (!VT.isVector()) {
29190     MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
29191     SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
29192     Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
29193     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
29194                        DAG.getIntPtrConstant(0, DL));
29195   }
29196 
29197   int NumElts = VT.getVectorNumElements();
29198   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
29199 
29200   // Decompose 256-bit ops into smaller 128-bit ops.
29201   if (VT.is256BitVector())
29202     return splitVectorIntUnary(Op, DAG);
29203 
29204   assert(VT.is128BitVector() &&
29205          "Only 128-bit vector bitreverse lowering supported.");
29206 
29207   // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
29208   // perform the BSWAP in the shuffle.
29209   // Its best to shuffle using the second operand as this will implicitly allow
29210   // memory folding for multiple vectors.
29211   SmallVector<SDValue, 16> MaskElts;
29212   for (int i = 0; i != NumElts; ++i) {
29213     for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
29214       int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
29215       int PermuteByte = SourceByte | (2 << 5);
29216       MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
29217     }
29218   }
29219 
29220   SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
29221   SDValue Res = DAG.getBitcast(MVT::v16i8, In);
29222   Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
29223                     Res, Mask);
29224   return DAG.getBitcast(VT, Res);
29225 }
29226 
29227 static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
29228                                SelectionDAG &DAG) {
29229   MVT VT = Op.getSimpleValueType();
29230 
29231   if (Subtarget.hasXOP() && !VT.is512BitVector())
29232     return LowerBITREVERSE_XOP(Op, DAG);
29233 
29234   assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE");
29235 
29236   SDValue In = Op.getOperand(0);
29237   SDLoc DL(Op);
29238 
29239   assert(VT.getScalarType() == MVT::i8 &&
29240          "Only byte vector BITREVERSE supported");
29241 
29242   // Split v64i8 without BWI so that we can still use the PSHUFB lowering.
29243   if (VT == MVT::v64i8 && !Subtarget.hasBWI())
29244     return splitVectorIntUnary(Op, DAG);
29245 
29246   // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
29247   if (VT == MVT::v32i8 && !Subtarget.hasInt256())
29248     return splitVectorIntUnary(Op, DAG);
29249 
29250   unsigned NumElts = VT.getVectorNumElements();
29251 
29252   // If we have GFNI, we can use GF2P8AFFINEQB to reverse the bits.
29253   if (Subtarget.hasGFNI()) {
29254     MVT MatrixVT = MVT::getVectorVT(MVT::i64, NumElts / 8);
29255     SDValue Matrix = DAG.getConstant(0x8040201008040201ULL, DL, MatrixVT);
29256     Matrix = DAG.getBitcast(VT, Matrix);
29257     return DAG.getNode(X86ISD::GF2P8AFFINEQB, DL, VT, In, Matrix,
29258                        DAG.getTargetConstant(0, DL, MVT::i8));
29259   }
29260 
29261   // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
29262   // two nibbles and a PSHUFB lookup to find the bitreverse of each
29263   // 0-15 value (moved to the other nibble).
29264   SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
29265   SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
29266   SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
29267 
29268   const int LoLUT[16] = {
29269       /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
29270       /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
29271       /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
29272       /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
29273   const int HiLUT[16] = {
29274       /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
29275       /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
29276       /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
29277       /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
29278 
29279   SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
29280   for (unsigned i = 0; i < NumElts; ++i) {
29281     LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
29282     HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
29283   }
29284 
29285   SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
29286   SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
29287   Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
29288   Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
29289   return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
29290 }
29291 
29292 static SDValue LowerPARITY(SDValue Op, const X86Subtarget &Subtarget,
29293                            SelectionDAG &DAG) {
29294   SDLoc DL(Op);
29295   SDValue X = Op.getOperand(0);
29296   MVT VT = Op.getSimpleValueType();
29297 
29298   // Special case. If the input fits in 8-bits we can use a single 8-bit TEST.
29299   if (VT == MVT::i8 ||
29300       DAG.MaskedValueIsZero(X, APInt::getBitsSetFrom(VT.getSizeInBits(), 8))) {
29301     X = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
29302     SDValue Flags = DAG.getNode(X86ISD::CMP, DL, MVT::i32, X,
29303                                 DAG.getConstant(0, DL, MVT::i8));
29304     // Copy the inverse of the parity flag into a register with setcc.
29305     SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
29306     // Extend to the original type.
29307     return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
29308   }
29309 
29310   if (VT == MVT::i64) {
29311     // Xor the high and low 16-bits together using a 32-bit operation.
29312     SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
29313                              DAG.getNode(ISD::SRL, DL, MVT::i64, X,
29314                                          DAG.getConstant(32, DL, MVT::i8)));
29315     SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
29316     X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
29317   }
29318 
29319   if (VT != MVT::i16) {
29320     // Xor the high and low 16-bits together using a 32-bit operation.
29321     SDValue Hi16 = DAG.getNode(ISD::SRL, DL, MVT::i32, X,
29322                                DAG.getConstant(16, DL, MVT::i8));
29323     X = DAG.getNode(ISD::XOR, DL, MVT::i32, X, Hi16);
29324   } else {
29325     // If the input is 16-bits, we need to extend to use an i32 shift below.
29326     X = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, X);
29327   }
29328 
29329   // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
29330   // This should allow an h-reg to be used to save a shift.
29331   SDValue Hi = DAG.getNode(
29332       ISD::TRUNCATE, DL, MVT::i8,
29333       DAG.getNode(ISD::SRL, DL, MVT::i32, X, DAG.getConstant(8, DL, MVT::i8)));
29334   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
29335   SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
29336   SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
29337 
29338   // Copy the inverse of the parity flag into a register with setcc.
29339   SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
29340   // Extend to the original type.
29341   return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Setnp);
29342 }
29343 
29344 static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
29345                                         const X86Subtarget &Subtarget) {
29346   unsigned NewOpc = 0;
29347   switch (N->getOpcode()) {
29348   case ISD::ATOMIC_LOAD_ADD:
29349     NewOpc = X86ISD::LADD;
29350     break;
29351   case ISD::ATOMIC_LOAD_SUB:
29352     NewOpc = X86ISD::LSUB;
29353     break;
29354   case ISD::ATOMIC_LOAD_OR:
29355     NewOpc = X86ISD::LOR;
29356     break;
29357   case ISD::ATOMIC_LOAD_XOR:
29358     NewOpc = X86ISD::LXOR;
29359     break;
29360   case ISD::ATOMIC_LOAD_AND:
29361     NewOpc = X86ISD::LAND;
29362     break;
29363   default:
29364     llvm_unreachable("Unknown ATOMIC_LOAD_ opcode");
29365   }
29366 
29367   MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
29368 
29369   return DAG.getMemIntrinsicNode(
29370       NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
29371       {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
29372       /*MemVT=*/N->getSimpleValueType(0), MMO);
29373 }
29374 
29375 /// Lower atomic_load_ops into LOCK-prefixed operations.
29376 static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
29377                                 const X86Subtarget &Subtarget) {
29378   AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
29379   SDValue Chain = N->getOperand(0);
29380   SDValue LHS = N->getOperand(1);
29381   SDValue RHS = N->getOperand(2);
29382   unsigned Opc = N->getOpcode();
29383   MVT VT = N->getSimpleValueType(0);
29384   SDLoc DL(N);
29385 
29386   // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
29387   // can only be lowered when the result is unused.  They should have already
29388   // been transformed into a cmpxchg loop in AtomicExpand.
29389   if (N->hasAnyUseOfValue(0)) {
29390     // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
29391     // select LXADD if LOCK_SUB can't be selected.
29392     if (Opc == ISD::ATOMIC_LOAD_SUB) {
29393       RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
29394       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
29395                            RHS, AN->getMemOperand());
29396     }
29397     assert(Opc == ISD::ATOMIC_LOAD_ADD &&
29398            "Used AtomicRMW ops other than Add should have been expanded!");
29399     return N;
29400   }
29401 
29402   // Specialized lowering for the canonical form of an idemptotent atomicrmw.
29403   // The core idea here is that since the memory location isn't actually
29404   // changing, all we need is a lowering for the *ordering* impacts of the
29405   // atomicrmw.  As such, we can chose a different operation and memory
29406   // location to minimize impact on other code.
29407   if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
29408     // On X86, the only ordering which actually requires an instruction is
29409     // seq_cst which isn't SingleThread, everything just needs to be preserved
29410     // during codegen and then dropped. Note that we expect (but don't assume),
29411     // that orderings other than seq_cst and acq_rel have been canonicalized to
29412     // a store or load.
29413     if (AN->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
29414         AN->getSyncScopeID() == SyncScope::System) {
29415       // Prefer a locked operation against a stack location to minimize cache
29416       // traffic.  This assumes that stack locations are very likely to be
29417       // accessed only by the owning thread.
29418       SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
29419       assert(!N->hasAnyUseOfValue(0));
29420       // NOTE: The getUNDEF is needed to give something for the unused result 0.
29421       return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
29422                          DAG.getUNDEF(VT), NewChain);
29423     }
29424     // MEMBARRIER is a compiler barrier; it codegens to a no-op.
29425     SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
29426     assert(!N->hasAnyUseOfValue(0));
29427     // NOTE: The getUNDEF is needed to give something for the unused result 0.
29428     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
29429                        DAG.getUNDEF(VT), NewChain);
29430   }
29431 
29432   SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
29433   // RAUW the chain, but don't worry about the result, as it's unused.
29434   assert(!N->hasAnyUseOfValue(0));
29435   // NOTE: The getUNDEF is needed to give something for the unused result 0.
29436   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
29437                      DAG.getUNDEF(VT), LockOp.getValue(1));
29438 }
29439 
29440 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
29441                                  const X86Subtarget &Subtarget) {
29442   auto *Node = cast<AtomicSDNode>(Op.getNode());
29443   SDLoc dl(Node);
29444   EVT VT = Node->getMemoryVT();
29445 
29446   bool IsSeqCst = Node->getOrdering() == AtomicOrdering::SequentiallyConsistent;
29447   bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
29448 
29449   // If this store is not sequentially consistent and the type is legal
29450   // we can just keep it.
29451   if (!IsSeqCst && IsTypeLegal)
29452     return Op;
29453 
29454   if (VT == MVT::i64 && !IsTypeLegal) {
29455     // For illegal i64 atomic_stores, we can try to use MOVQ or MOVLPS if SSE
29456     // is enabled.
29457     bool NoImplicitFloatOps =
29458         DAG.getMachineFunction().getFunction().hasFnAttribute(
29459             Attribute::NoImplicitFloat);
29460     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
29461       SDValue Chain;
29462       if (Subtarget.hasSSE1()) {
29463         SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
29464                                        Node->getOperand(2));
29465         MVT StVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
29466         SclToVec = DAG.getBitcast(StVT, SclToVec);
29467         SDVTList Tys = DAG.getVTList(MVT::Other);
29468         SDValue Ops[] = {Node->getChain(), SclToVec, Node->getBasePtr()};
29469         Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys, Ops,
29470                                         MVT::i64, Node->getMemOperand());
29471       } else if (Subtarget.hasX87()) {
29472         // First load this into an 80-bit X87 register using a stack temporary.
29473         // This will put the whole integer into the significand.
29474         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
29475         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
29476         MachinePointerInfo MPI =
29477             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
29478         Chain =
29479             DAG.getStore(Node->getChain(), dl, Node->getOperand(2), StackPtr,
29480                          MPI, MaybeAlign(), MachineMemOperand::MOStore);
29481         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
29482         SDValue LdOps[] = {Chain, StackPtr};
29483         SDValue Value =
29484             DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, LdOps, MVT::i64, MPI,
29485                                     /*Align*/ None, MachineMemOperand::MOLoad);
29486         Chain = Value.getValue(1);
29487 
29488         // Now use an FIST to do the atomic store.
29489         SDValue StoreOps[] = {Chain, Value, Node->getBasePtr()};
29490         Chain =
29491             DAG.getMemIntrinsicNode(X86ISD::FIST, dl, DAG.getVTList(MVT::Other),
29492                                     StoreOps, MVT::i64, Node->getMemOperand());
29493       }
29494 
29495       if (Chain) {
29496         // If this is a sequentially consistent store, also emit an appropriate
29497         // barrier.
29498         if (IsSeqCst)
29499           Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
29500 
29501         return Chain;
29502       }
29503     }
29504   }
29505 
29506   // Convert seq_cst store -> xchg
29507   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
29508   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
29509   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
29510                                Node->getMemoryVT(),
29511                                Node->getOperand(0),
29512                                Node->getOperand(1), Node->getOperand(2),
29513                                Node->getMemOperand());
29514   return Swap.getValue(1);
29515 }
29516 
29517 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
29518   SDNode *N = Op.getNode();
29519   MVT VT = N->getSimpleValueType(0);
29520   unsigned Opc = Op.getOpcode();
29521 
29522   // Let legalize expand this if it isn't a legal type yet.
29523   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
29524     return SDValue();
29525 
29526   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
29527   SDLoc DL(N);
29528 
29529   // Set the carry flag.
29530   SDValue Carry = Op.getOperand(2);
29531   EVT CarryVT = Carry.getValueType();
29532   Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
29533                       Carry, DAG.getAllOnesConstant(DL, CarryVT));
29534 
29535   bool IsAdd = Opc == ISD::ADDCARRY || Opc == ISD::SADDO_CARRY;
29536   SDValue Sum = DAG.getNode(IsAdd ? X86ISD::ADC : X86ISD::SBB, DL, VTs,
29537                             Op.getOperand(0), Op.getOperand(1),
29538                             Carry.getValue(1));
29539 
29540   bool IsSigned = Opc == ISD::SADDO_CARRY || Opc == ISD::SSUBO_CARRY;
29541   SDValue SetCC = getSETCC(IsSigned ? X86::COND_O : X86::COND_B,
29542                            Sum.getValue(1), DL, DAG);
29543   if (N->getValueType(1) == MVT::i1)
29544     SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
29545 
29546   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
29547 }
29548 
29549 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
29550                             SelectionDAG &DAG) {
29551   assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit());
29552 
29553   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
29554   // which returns the values as { float, float } (in XMM0) or
29555   // { double, double } (which is returned in XMM0, XMM1).
29556   SDLoc dl(Op);
29557   SDValue Arg = Op.getOperand(0);
29558   EVT ArgVT = Arg.getValueType();
29559   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
29560 
29561   TargetLowering::ArgListTy Args;
29562   TargetLowering::ArgListEntry Entry;
29563 
29564   Entry.Node = Arg;
29565   Entry.Ty = ArgTy;
29566   Entry.IsSExt = false;
29567   Entry.IsZExt = false;
29568   Args.push_back(Entry);
29569 
29570   bool isF64 = ArgVT == MVT::f64;
29571   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
29572   // the small struct {f32, f32} is returned in (eax, edx). For f64,
29573   // the results are returned via SRet in memory.
29574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29575   RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
29576   const char *LibcallName = TLI.getLibcallName(LC);
29577   SDValue Callee =
29578       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
29579 
29580   Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
29581                       : (Type *)FixedVectorType::get(ArgTy, 4);
29582 
29583   TargetLowering::CallLoweringInfo CLI(DAG);
29584   CLI.setDebugLoc(dl)
29585       .setChain(DAG.getEntryNode())
29586       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
29587 
29588   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
29589 
29590   if (isF64)
29591     // Returned in xmm0 and xmm1.
29592     return CallResult.first;
29593 
29594   // Returned in bits 0:31 and 32:64 xmm0.
29595   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
29596                                CallResult.first, DAG.getIntPtrConstant(0, dl));
29597   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
29598                                CallResult.first, DAG.getIntPtrConstant(1, dl));
29599   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
29600   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
29601 }
29602 
29603 /// Widen a vector input to a vector of NVT.  The
29604 /// input vector must have the same element type as NVT.
29605 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
29606                             bool FillWithZeroes = false) {
29607   // Check if InOp already has the right width.
29608   MVT InVT = InOp.getSimpleValueType();
29609   if (InVT == NVT)
29610     return InOp;
29611 
29612   if (InOp.isUndef())
29613     return DAG.getUNDEF(NVT);
29614 
29615   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
29616          "input and widen element type must match");
29617 
29618   unsigned InNumElts = InVT.getVectorNumElements();
29619   unsigned WidenNumElts = NVT.getVectorNumElements();
29620   assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
29621          "Unexpected request for vector widening");
29622 
29623   SDLoc dl(InOp);
29624   if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
29625       InOp.getNumOperands() == 2) {
29626     SDValue N1 = InOp.getOperand(1);
29627     if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
29628         N1.isUndef()) {
29629       InOp = InOp.getOperand(0);
29630       InVT = InOp.getSimpleValueType();
29631       InNumElts = InVT.getVectorNumElements();
29632     }
29633   }
29634   if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
29635       ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
29636     SmallVector<SDValue, 16> Ops;
29637     for (unsigned i = 0; i < InNumElts; ++i)
29638       Ops.push_back(InOp.getOperand(i));
29639 
29640     EVT EltVT = InOp.getOperand(0).getValueType();
29641 
29642     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
29643       DAG.getUNDEF(EltVT);
29644     for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
29645       Ops.push_back(FillVal);
29646     return DAG.getBuildVector(NVT, dl, Ops);
29647   }
29648   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
29649     DAG.getUNDEF(NVT);
29650   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
29651                      InOp, DAG.getIntPtrConstant(0, dl));
29652 }
29653 
29654 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
29655                              SelectionDAG &DAG) {
29656   assert(Subtarget.hasAVX512() &&
29657          "MGATHER/MSCATTER are supported on AVX-512 arch only");
29658 
29659   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
29660   SDValue Src = N->getValue();
29661   MVT VT = Src.getSimpleValueType();
29662   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
29663   SDLoc dl(Op);
29664 
29665   SDValue Scale = N->getScale();
29666   SDValue Index = N->getIndex();
29667   SDValue Mask = N->getMask();
29668   SDValue Chain = N->getChain();
29669   SDValue BasePtr = N->getBasePtr();
29670 
29671   if (VT == MVT::v2f32 || VT == MVT::v2i32) {
29672     assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
29673     // If the index is v2i64 and we have VLX we can use xmm for data and index.
29674     if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
29675       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
29676       EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
29677       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Src, DAG.getUNDEF(VT));
29678       SDVTList VTs = DAG.getVTList(MVT::Other);
29679       SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
29680       return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
29681                                      N->getMemoryVT(), N->getMemOperand());
29682     }
29683     return SDValue();
29684   }
29685 
29686   MVT IndexVT = Index.getSimpleValueType();
29687 
29688   // If the index is v2i32, we're being called by type legalization and we
29689   // should just let the default handling take care of it.
29690   if (IndexVT == MVT::v2i32)
29691     return SDValue();
29692 
29693   // If we don't have VLX and neither the passthru or index is 512-bits, we
29694   // need to widen until one is.
29695   if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
29696       !Index.getSimpleValueType().is512BitVector()) {
29697     // Determine how much we need to widen by to get a 512-bit type.
29698     unsigned Factor = std::min(512/VT.getSizeInBits(),
29699                                512/IndexVT.getSizeInBits());
29700     unsigned NumElts = VT.getVectorNumElements() * Factor;
29701 
29702     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
29703     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
29704     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
29705 
29706     Src = ExtendToType(Src, VT, DAG);
29707     Index = ExtendToType(Index, IndexVT, DAG);
29708     Mask = ExtendToType(Mask, MaskVT, DAG, true);
29709   }
29710 
29711   SDVTList VTs = DAG.getVTList(MVT::Other);
29712   SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
29713   return DAG.getMemIntrinsicNode(X86ISD::MSCATTER, dl, VTs, Ops,
29714                                  N->getMemoryVT(), N->getMemOperand());
29715 }
29716 
29717 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
29718                           SelectionDAG &DAG) {
29719 
29720   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
29721   MVT VT = Op.getSimpleValueType();
29722   MVT ScalarVT = VT.getScalarType();
29723   SDValue Mask = N->getMask();
29724   MVT MaskVT = Mask.getSimpleValueType();
29725   SDValue PassThru = N->getPassThru();
29726   SDLoc dl(Op);
29727 
29728   // Handle AVX masked loads which don't support passthru other than 0.
29729   if (MaskVT.getVectorElementType() != MVT::i1) {
29730     // We also allow undef in the isel pattern.
29731     if (PassThru.isUndef() || ISD::isBuildVectorAllZeros(PassThru.getNode()))
29732       return Op;
29733 
29734     SDValue NewLoad = DAG.getMaskedLoad(
29735         VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
29736         getZeroVector(VT, Subtarget, DAG, dl), N->getMemoryVT(),
29737         N->getMemOperand(), N->getAddressingMode(), N->getExtensionType(),
29738         N->isExpandingLoad());
29739     // Emit a blend.
29740     SDValue Select = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
29741     return DAG.getMergeValues({ Select, NewLoad.getValue(1) }, dl);
29742   }
29743 
29744   assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
29745          "Expanding masked load is supported on AVX-512 target only!");
29746 
29747   assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&
29748          "Expanding masked load is supported for 32 and 64-bit types only!");
29749 
29750   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
29751          "Cannot lower masked load op.");
29752 
29753   assert((ScalarVT.getSizeInBits() >= 32 ||
29754           (Subtarget.hasBWI() &&
29755               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
29756          "Unsupported masked load op.");
29757 
29758   // This operation is legal for targets with VLX, but without
29759   // VLX the vector should be widened to 512 bit
29760   unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
29761   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
29762   PassThru = ExtendToType(PassThru, WideDataVT, DAG);
29763 
29764   // Mask element has to be i1.
29765   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
29766          "Unexpected mask type");
29767 
29768   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
29769 
29770   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
29771   SDValue NewLoad = DAG.getMaskedLoad(
29772       WideDataVT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask,
29773       PassThru, N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
29774       N->getExtensionType(), N->isExpandingLoad());
29775 
29776   SDValue Extract =
29777       DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, NewLoad.getValue(0),
29778                   DAG.getIntPtrConstant(0, dl));
29779   SDValue RetOps[] = {Extract, NewLoad.getValue(1)};
29780   return DAG.getMergeValues(RetOps, dl);
29781 }
29782 
29783 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
29784                            SelectionDAG &DAG) {
29785   MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
29786   SDValue DataToStore = N->getValue();
29787   MVT VT = DataToStore.getSimpleValueType();
29788   MVT ScalarVT = VT.getScalarType();
29789   SDValue Mask = N->getMask();
29790   SDLoc dl(Op);
29791 
29792   assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
29793          "Expanding masked load is supported on AVX-512 target only!");
29794 
29795   assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&
29796          "Expanding masked load is supported for 32 and 64-bit types only!");
29797 
29798   assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
29799          "Cannot lower masked store op.");
29800 
29801   assert((ScalarVT.getSizeInBits() >= 32 ||
29802           (Subtarget.hasBWI() &&
29803               (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&
29804           "Unsupported masked store op.");
29805 
29806   // This operation is legal for targets with VLX, but without
29807   // VLX the vector should be widened to 512 bit
29808   unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
29809   MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
29810 
29811   // Mask element has to be i1.
29812   assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
29813          "Unexpected mask type");
29814 
29815   MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
29816 
29817   DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
29818   Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
29819   return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
29820                             N->getOffset(), Mask, N->getMemoryVT(),
29821                             N->getMemOperand(), N->getAddressingMode(),
29822                             N->isTruncatingStore(), N->isCompressingStore());
29823 }
29824 
29825 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
29826                             SelectionDAG &DAG) {
29827   assert(Subtarget.hasAVX2() &&
29828          "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only");
29829 
29830   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
29831   SDLoc dl(Op);
29832   MVT VT = Op.getSimpleValueType();
29833   SDValue Index = N->getIndex();
29834   SDValue Mask = N->getMask();
29835   SDValue PassThru = N->getPassThru();
29836   MVT IndexVT = Index.getSimpleValueType();
29837 
29838   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
29839 
29840   // If the index is v2i32, we're being called by type legalization.
29841   if (IndexVT == MVT::v2i32)
29842     return SDValue();
29843 
29844   // If we don't have VLX and neither the passthru or index is 512-bits, we
29845   // need to widen until one is.
29846   MVT OrigVT = VT;
29847   if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
29848       !IndexVT.is512BitVector()) {
29849     // Determine how much we need to widen by to get a 512-bit type.
29850     unsigned Factor = std::min(512/VT.getSizeInBits(),
29851                                512/IndexVT.getSizeInBits());
29852 
29853     unsigned NumElts = VT.getVectorNumElements() * Factor;
29854 
29855     VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
29856     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
29857     MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
29858 
29859     PassThru = ExtendToType(PassThru, VT, DAG);
29860     Index = ExtendToType(Index, IndexVT, DAG);
29861     Mask = ExtendToType(Mask, MaskVT, DAG, true);
29862   }
29863 
29864   SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
29865                     N->getScale() };
29866   SDValue NewGather = DAG.getMemIntrinsicNode(
29867       X86ISD::MGATHER, dl, DAG.getVTList(VT, MVT::Other), Ops, N->getMemoryVT(),
29868       N->getMemOperand());
29869   SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
29870                                 NewGather, DAG.getIntPtrConstant(0, dl));
29871   return DAG.getMergeValues({Extract, NewGather.getValue(1)}, dl);
29872 }
29873 
29874 static SDValue LowerADDRSPACECAST(SDValue Op, SelectionDAG &DAG) {
29875   SDLoc dl(Op);
29876   SDValue Src = Op.getOperand(0);
29877   MVT DstVT = Op.getSimpleValueType();
29878 
29879   AddrSpaceCastSDNode *N = cast<AddrSpaceCastSDNode>(Op.getNode());
29880   unsigned SrcAS = N->getSrcAddressSpace();
29881 
29882   assert(SrcAS != N->getDestAddressSpace() &&
29883          "addrspacecast must be between different address spaces");
29884 
29885   if (SrcAS == X86AS::PTR32_UPTR && DstVT == MVT::i64) {
29886     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Src);
29887   } else if (DstVT == MVT::i64) {
29888     Op = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Src);
29889   } else if (DstVT == MVT::i32) {
29890     Op = DAG.getNode(ISD::TRUNCATE, dl, DstVT, Src);
29891   } else {
29892     report_fatal_error("Bad address space in addrspacecast");
29893   }
29894   return Op;
29895 }
29896 
29897 SDValue X86TargetLowering::LowerGC_TRANSITION(SDValue Op,
29898                                               SelectionDAG &DAG) const {
29899   // TODO: Eventually, the lowering of these nodes should be informed by or
29900   // deferred to the GC strategy for the function in which they appear. For
29901   // now, however, they must be lowered to something. Since they are logically
29902   // no-ops in the case of a null GC strategy (or a GC strategy which does not
29903   // require special handling for these nodes), lower them as literal NOOPs for
29904   // the time being.
29905   SmallVector<SDValue, 2> Ops;
29906 
29907   Ops.push_back(Op.getOperand(0));
29908   if (Op->getGluedNode())
29909     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
29910 
29911   SDLoc OpDL(Op);
29912   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
29913   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
29914 
29915   return NOOP;
29916 }
29917 
29918 // Custom split CVTPS2PH with wide types.
29919 static SDValue LowerCVTPS2PH(SDValue Op, SelectionDAG &DAG) {
29920   SDLoc dl(Op);
29921   EVT VT = Op.getValueType();
29922   SDValue Lo, Hi;
29923   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
29924   EVT LoVT, HiVT;
29925   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
29926   SDValue RC = Op.getOperand(1);
29927   Lo = DAG.getNode(X86ISD::CVTPS2PH, dl, LoVT, Lo, RC);
29928   Hi = DAG.getNode(X86ISD::CVTPS2PH, dl, HiVT, Hi, RC);
29929   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
29930 }
29931 
29932 /// Provide custom lowering hooks for some operations.
29933 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
29934   switch (Op.getOpcode()) {
29935   default: llvm_unreachable("Should not custom lower this!");
29936   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
29937   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
29938     return LowerCMP_SWAP(Op, Subtarget, DAG);
29939   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
29940   case ISD::ATOMIC_LOAD_ADD:
29941   case ISD::ATOMIC_LOAD_SUB:
29942   case ISD::ATOMIC_LOAD_OR:
29943   case ISD::ATOMIC_LOAD_XOR:
29944   case ISD::ATOMIC_LOAD_AND:    return lowerAtomicArith(Op, DAG, Subtarget);
29945   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op, DAG, Subtarget);
29946   case ISD::BITREVERSE:         return LowerBITREVERSE(Op, Subtarget, DAG);
29947   case ISD::PARITY:             return LowerPARITY(Op, Subtarget, DAG);
29948   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
29949   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
29950   case ISD::VECTOR_SHUFFLE:     return lowerVECTOR_SHUFFLE(Op, Subtarget, DAG);
29951   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
29952   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
29953   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
29954   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
29955   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
29956   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
29957   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
29958   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
29959   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
29960   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
29961   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
29962   case ISD::SHL_PARTS:
29963   case ISD::SRA_PARTS:
29964   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
29965   case ISD::FSHL:
29966   case ISD::FSHR:               return LowerFunnelShift(Op, Subtarget, DAG);
29967   case ISD::STRICT_SINT_TO_FP:
29968   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
29969   case ISD::STRICT_UINT_TO_FP:
29970   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
29971   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
29972   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
29973   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
29974   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
29975   case ISD::ZERO_EXTEND_VECTOR_INREG:
29976   case ISD::SIGN_EXTEND_VECTOR_INREG:
29977     return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
29978   case ISD::FP_TO_SINT:
29979   case ISD::STRICT_FP_TO_SINT:
29980   case ISD::FP_TO_UINT:
29981   case ISD::STRICT_FP_TO_UINT:  return LowerFP_TO_INT(Op, DAG);
29982   case ISD::FP_TO_SINT_SAT:
29983   case ISD::FP_TO_UINT_SAT:     return LowerFP_TO_INT_SAT(Op, DAG);
29984   case ISD::FP_EXTEND:
29985   case ISD::STRICT_FP_EXTEND:   return LowerFP_EXTEND(Op, DAG);
29986   case ISD::FP_ROUND:
29987   case ISD::STRICT_FP_ROUND:    return LowerFP_ROUND(Op, DAG);
29988   case ISD::FP16_TO_FP:
29989   case ISD::STRICT_FP16_TO_FP:  return LowerFP16_TO_FP(Op, DAG);
29990   case ISD::FP_TO_FP16:
29991   case ISD::STRICT_FP_TO_FP16:  return LowerFP_TO_FP16(Op, DAG);
29992   case ISD::LOAD:               return LowerLoad(Op, Subtarget, DAG);
29993   case ISD::STORE:              return LowerStore(Op, Subtarget, DAG);
29994   case ISD::FADD:
29995   case ISD::FSUB:               return lowerFaddFsub(Op, DAG);
29996   case ISD::FROUND:             return LowerFROUND(Op, DAG);
29997   case ISD::FABS:
29998   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
29999   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
30000   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
30001   case ISD::LRINT:
30002   case ISD::LLRINT:             return LowerLRINT_LLRINT(Op, DAG);
30003   case ISD::SETCC:
30004   case ISD::STRICT_FSETCC:
30005   case ISD::STRICT_FSETCCS:     return LowerSETCC(Op, DAG);
30006   case ISD::SETCCCARRY:         return LowerSETCCCARRY(Op, DAG);
30007   case ISD::SELECT:             return LowerSELECT(Op, DAG);
30008   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
30009   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
30010   case ISD::VASTART:            return LowerVASTART(Op, DAG);
30011   case ISD::VAARG:              return LowerVAARG(Op, DAG);
30012   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
30013   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
30014   case ISD::INTRINSIC_VOID:
30015   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
30016   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
30017   case ISD::ADDROFRETURNADDR:   return LowerADDROFRETURNADDR(Op, DAG);
30018   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
30019   case ISD::FRAME_TO_ARGS_OFFSET:
30020                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
30021   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
30022   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
30023   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
30024   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
30025   case ISD::EH_SJLJ_SETUP_DISPATCH:
30026     return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
30027   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
30028   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
30029   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
30030   case ISD::CTLZ:
30031   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ(Op, Subtarget, DAG);
30032   case ISD::CTTZ:
30033   case ISD::CTTZ_ZERO_UNDEF:    return LowerCTTZ(Op, Subtarget, DAG);
30034   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
30035   case ISD::MULHS:
30036   case ISD::MULHU:              return LowerMULH(Op, Subtarget, DAG);
30037   case ISD::ROTL:
30038   case ISD::ROTR:               return LowerRotate(Op, Subtarget, DAG);
30039   case ISD::SRA:
30040   case ISD::SRL:
30041   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
30042   case ISD::SADDO:
30043   case ISD::UADDO:
30044   case ISD::SSUBO:
30045   case ISD::USUBO:
30046   case ISD::SMULO:
30047   case ISD::UMULO:              return LowerXALUO(Op, DAG);
30048   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
30049   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
30050   case ISD::SADDO_CARRY:
30051   case ISD::SSUBO_CARRY:
30052   case ISD::ADDCARRY:
30053   case ISD::SUBCARRY:           return LowerADDSUBCARRY(Op, DAG);
30054   case ISD::ADD:
30055   case ISD::SUB:                return lowerAddSub(Op, DAG, Subtarget);
30056   case ISD::UADDSAT:
30057   case ISD::SADDSAT:
30058   case ISD::USUBSAT:
30059   case ISD::SSUBSAT:            return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
30060   case ISD::SMAX:
30061   case ISD::SMIN:
30062   case ISD::UMAX:
30063   case ISD::UMIN:               return LowerMINMAX(Op, DAG);
30064   case ISD::ABS:                return LowerABS(Op, Subtarget, DAG);
30065   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
30066   case ISD::MLOAD:              return LowerMLOAD(Op, Subtarget, DAG);
30067   case ISD::MSTORE:             return LowerMSTORE(Op, Subtarget, DAG);
30068   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
30069   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
30070   case ISD::GC_TRANSITION_START:
30071   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION(Op, DAG);
30072   case ISD::ADDRSPACECAST:      return LowerADDRSPACECAST(Op, DAG);
30073   case X86ISD::CVTPS2PH:        return LowerCVTPS2PH(Op, DAG);
30074   }
30075 }
30076 
30077 /// Replace a node with an illegal result type with a new node built out of
30078 /// custom code.
30079 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
30080                                            SmallVectorImpl<SDValue>&Results,
30081                                            SelectionDAG &DAG) const {
30082   SDLoc dl(N);
30083   switch (N->getOpcode()) {
30084   default:
30085 #ifndef NDEBUG
30086     dbgs() << "ReplaceNodeResults: ";
30087     N->dump(&DAG);
30088 #endif
30089     llvm_unreachable("Do not know how to custom type legalize this operation!");
30090   case X86ISD::CVTPH2PS: {
30091     EVT VT = N->getValueType(0);
30092     SDValue Lo, Hi;
30093     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
30094     EVT LoVT, HiVT;
30095     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
30096     Lo = DAG.getNode(X86ISD::CVTPH2PS, dl, LoVT, Lo);
30097     Hi = DAG.getNode(X86ISD::CVTPH2PS, dl, HiVT, Hi);
30098     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30099     Results.push_back(Res);
30100     return;
30101   }
30102   case X86ISD::STRICT_CVTPH2PS: {
30103     EVT VT = N->getValueType(0);
30104     SDValue Lo, Hi;
30105     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 1);
30106     EVT LoVT, HiVT;
30107     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
30108     Lo = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {LoVT, MVT::Other},
30109                      {N->getOperand(0), Lo});
30110     Hi = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {HiVT, MVT::Other},
30111                      {N->getOperand(0), Hi});
30112     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
30113                                 Lo.getValue(1), Hi.getValue(1));
30114     SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30115     Results.push_back(Res);
30116     Results.push_back(Chain);
30117     return;
30118   }
30119   case X86ISD::CVTPS2PH:
30120     Results.push_back(LowerCVTPS2PH(SDValue(N, 0), DAG));
30121     return;
30122   case ISD::CTPOP: {
30123     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
30124     // Use a v2i64 if possible.
30125     bool NoImplicitFloatOps =
30126         DAG.getMachineFunction().getFunction().hasFnAttribute(
30127             Attribute::NoImplicitFloat);
30128     if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
30129       SDValue Wide =
30130           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
30131       Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
30132       // Bit count should fit in 32-bits, extract it as that and then zero
30133       // extend to i64. Otherwise we end up extracting bits 63:32 separately.
30134       Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
30135       Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
30136                          DAG.getIntPtrConstant(0, dl));
30137       Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
30138       Results.push_back(Wide);
30139     }
30140     return;
30141   }
30142   case ISD::MUL: {
30143     EVT VT = N->getValueType(0);
30144     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30145            VT.getVectorElementType() == MVT::i8 && "Unexpected VT!");
30146     // Pre-promote these to vXi16 to avoid op legalization thinking all 16
30147     // elements are needed.
30148     MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
30149     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
30150     SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
30151     SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
30152     Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
30153     unsigned NumConcats = 16 / VT.getVectorNumElements();
30154     SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
30155     ConcatOps[0] = Res;
30156     Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
30157     Results.push_back(Res);
30158     return;
30159   }
30160   case X86ISD::VPMADDWD:
30161   case X86ISD::AVG: {
30162     // Legalize types for X86ISD::AVG/VPMADDWD by widening.
30163     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30164 
30165     EVT VT = N->getValueType(0);
30166     EVT InVT = N->getOperand(0).getValueType();
30167     assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&
30168            "Expected a VT that divides into 128 bits.");
30169     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30170            "Unexpected type action!");
30171     unsigned NumConcat = 128 / InVT.getSizeInBits();
30172 
30173     EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
30174                                     InVT.getVectorElementType(),
30175                                     NumConcat * InVT.getVectorNumElements());
30176     EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
30177                                   VT.getVectorElementType(),
30178                                   NumConcat * VT.getVectorNumElements());
30179 
30180     SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
30181     Ops[0] = N->getOperand(0);
30182     SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
30183     Ops[0] = N->getOperand(1);
30184     SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
30185 
30186     SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
30187     Results.push_back(Res);
30188     return;
30189   }
30190   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
30191   case X86ISD::FMINC:
30192   case X86ISD::FMIN:
30193   case X86ISD::FMAXC:
30194   case X86ISD::FMAX: {
30195     EVT VT = N->getValueType(0);
30196     assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
30197     SDValue UNDEF = DAG.getUNDEF(VT);
30198     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
30199                               N->getOperand(0), UNDEF);
30200     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
30201                               N->getOperand(1), UNDEF);
30202     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
30203     return;
30204   }
30205   case ISD::SDIV:
30206   case ISD::UDIV:
30207   case ISD::SREM:
30208   case ISD::UREM: {
30209     EVT VT = N->getValueType(0);
30210     if (VT.isVector()) {
30211       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30212              "Unexpected type action!");
30213       // If this RHS is a constant splat vector we can widen this and let
30214       // division/remainder by constant optimize it.
30215       // TODO: Can we do something for non-splat?
30216       APInt SplatVal;
30217       if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
30218         unsigned NumConcats = 128 / VT.getSizeInBits();
30219         SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
30220         Ops0[0] = N->getOperand(0);
30221         EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
30222         SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
30223         SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
30224         SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
30225         Results.push_back(Res);
30226       }
30227       return;
30228     }
30229 
30230     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
30231     Results.push_back(V);
30232     return;
30233   }
30234   case ISD::TRUNCATE: {
30235     MVT VT = N->getSimpleValueType(0);
30236     if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
30237       return;
30238 
30239     // The generic legalizer will try to widen the input type to the same
30240     // number of elements as the widened result type. But this isn't always
30241     // the best thing so do some custom legalization to avoid some cases.
30242     MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
30243     SDValue In = N->getOperand(0);
30244     EVT InVT = In.getValueType();
30245 
30246     unsigned InBits = InVT.getSizeInBits();
30247     if (128 % InBits == 0) {
30248       // 128 bit and smaller inputs should avoid truncate all together and
30249       // just use a build_vector that will become a shuffle.
30250       // TODO: Widen and use a shuffle directly?
30251       MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
30252       EVT EltVT = VT.getVectorElementType();
30253       unsigned WidenNumElts = WidenVT.getVectorNumElements();
30254       SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
30255       // Use the original element count so we don't do more scalar opts than
30256       // necessary.
30257       unsigned MinElts = VT.getVectorNumElements();
30258       for (unsigned i=0; i < MinElts; ++i) {
30259         SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
30260                                   DAG.getIntPtrConstant(i, dl));
30261         Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
30262       }
30263       Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
30264       return;
30265     }
30266     // With AVX512 there are some cases that can use a target specific
30267     // truncate node to go from 256/512 to less than 128 with zeros in the
30268     // upper elements of the 128 bit result.
30269     if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
30270       // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
30271       if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
30272         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
30273         return;
30274       }
30275       // There's one case we can widen to 512 bits and use VTRUNC.
30276       if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
30277         In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
30278                          DAG.getUNDEF(MVT::v4i64));
30279         Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
30280         return;
30281       }
30282     }
30283     if (Subtarget.hasVLX() && InVT == MVT::v8i64 && VT == MVT::v8i8 &&
30284         getTypeAction(*DAG.getContext(), InVT) == TypeSplitVector &&
30285         isTypeLegal(MVT::v4i64)) {
30286       // Input needs to be split and output needs to widened. Let's use two
30287       // VTRUNCs, and shuffle their results together into the wider type.
30288       SDValue Lo, Hi;
30289       std::tie(Lo, Hi) = DAG.SplitVector(In, dl);
30290 
30291       Lo = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Lo);
30292       Hi = DAG.getNode(X86ISD::VTRUNC, dl, MVT::v16i8, Hi);
30293       SDValue Res = DAG.getVectorShuffle(MVT::v16i8, dl, Lo, Hi,
30294                                          { 0,  1,  2,  3, 16, 17, 18, 19,
30295                                           -1, -1, -1, -1, -1, -1, -1, -1 });
30296       Results.push_back(Res);
30297       return;
30298     }
30299 
30300     return;
30301   }
30302   case ISD::ANY_EXTEND:
30303     // Right now, only MVT::v8i8 has Custom action for an illegal type.
30304     // It's intended to custom handle the input type.
30305     assert(N->getValueType(0) == MVT::v8i8 &&
30306            "Do not know how to legalize this Node");
30307     return;
30308   case ISD::SIGN_EXTEND:
30309   case ISD::ZERO_EXTEND: {
30310     EVT VT = N->getValueType(0);
30311     SDValue In = N->getOperand(0);
30312     EVT InVT = In.getValueType();
30313     if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
30314         (InVT == MVT::v4i16 || InVT == MVT::v4i8)){
30315       assert(getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector &&
30316              "Unexpected type action!");
30317       assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode");
30318       // Custom split this so we can extend i8/i16->i32 invec. This is better
30319       // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
30320       // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
30321       // we allow the sra from the extend to i32 to be shared by the split.
30322       In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
30323 
30324       // Fill a vector with sign bits for each element.
30325       SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
30326       SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
30327 
30328       // Create an unpackl and unpackh to interleave the sign bits then bitcast
30329       // to v2i64.
30330       SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
30331                                         {0, 4, 1, 5});
30332       Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
30333       SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
30334                                         {2, 6, 3, 7});
30335       Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
30336 
30337       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30338       Results.push_back(Res);
30339       return;
30340     }
30341 
30342     if (VT == MVT::v16i32 || VT == MVT::v8i64) {
30343       if (!InVT.is128BitVector()) {
30344         // Not a 128 bit vector, but maybe type legalization will promote
30345         // it to 128 bits.
30346         if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
30347           return;
30348         InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
30349         if (!InVT.is128BitVector())
30350           return;
30351 
30352         // Promote the input to 128 bits. Type legalization will turn this into
30353         // zext_inreg/sext_inreg.
30354         In = DAG.getNode(N->getOpcode(), dl, InVT, In);
30355       }
30356 
30357       // Perform custom splitting instead of the two stage extend we would get
30358       // by default.
30359       EVT LoVT, HiVT;
30360       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
30361       assert(isTypeLegal(LoVT) && "Split VT not legal?");
30362 
30363       SDValue Lo = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, LoVT, In, DAG);
30364 
30365       // We need to shift the input over by half the number of elements.
30366       unsigned NumElts = InVT.getVectorNumElements();
30367       unsigned HalfNumElts = NumElts / 2;
30368       SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
30369       for (unsigned i = 0; i != HalfNumElts; ++i)
30370         ShufMask[i] = i + HalfNumElts;
30371 
30372       SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
30373       Hi = getEXTEND_VECTOR_INREG(N->getOpcode(), dl, HiVT, Hi, DAG);
30374 
30375       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
30376       Results.push_back(Res);
30377     }
30378     return;
30379   }
30380   case ISD::FP_TO_SINT:
30381   case ISD::STRICT_FP_TO_SINT:
30382   case ISD::FP_TO_UINT:
30383   case ISD::STRICT_FP_TO_UINT: {
30384     bool IsStrict = N->isStrictFPOpcode();
30385     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
30386                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
30387     EVT VT = N->getValueType(0);
30388     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
30389     EVT SrcVT = Src.getValueType();
30390 
30391     if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
30392       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30393              "Unexpected type action!");
30394 
30395       // Try to create a 128 bit vector, but don't exceed a 32 bit element.
30396       unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
30397       MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
30398                                        VT.getVectorNumElements());
30399       SDValue Res;
30400       SDValue Chain;
30401       if (IsStrict) {
30402         Res = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, {PromoteVT, MVT::Other},
30403                           {N->getOperand(0), Src});
30404         Chain = Res.getValue(1);
30405       } else
30406         Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
30407 
30408       // Preserve what we know about the size of the original result. Except
30409       // when the result is v2i32 since we can't widen the assert.
30410       if (PromoteVT != MVT::v2i32)
30411         Res = DAG.getNode(!IsSigned ? ISD::AssertZext : ISD::AssertSext,
30412                           dl, PromoteVT, Res,
30413                           DAG.getValueType(VT.getVectorElementType()));
30414 
30415       // Truncate back to the original width.
30416       Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
30417 
30418       // Now widen to 128 bits.
30419       unsigned NumConcats = 128 / VT.getSizeInBits();
30420       MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
30421                                       VT.getVectorNumElements() * NumConcats);
30422       SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
30423       ConcatOps[0] = Res;
30424       Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
30425       Results.push_back(Res);
30426       if (IsStrict)
30427         Results.push_back(Chain);
30428       return;
30429     }
30430 
30431 
30432     if (VT == MVT::v2i32) {
30433       assert((IsSigned || Subtarget.hasAVX512()) &&
30434              "Can only handle signed conversion without AVX512");
30435       assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30436       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30437              "Unexpected type action!");
30438       if (Src.getValueType() == MVT::v2f64) {
30439         unsigned Opc;
30440         if (IsStrict)
30441           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
30442         else
30443           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
30444 
30445         // If we have VLX we can emit a target specific FP_TO_UINT node,.
30446         if (!IsSigned && !Subtarget.hasVLX()) {
30447           // Otherwise we can defer to the generic legalizer which will widen
30448           // the input as well. This will be further widened during op
30449           // legalization to v8i32<-v8f64.
30450           // For strict nodes we'll need to widen ourselves.
30451           // FIXME: Fix the type legalizer to safely widen strict nodes?
30452           if (!IsStrict)
30453             return;
30454           Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64, Src,
30455                             DAG.getConstantFP(0.0, dl, MVT::v2f64));
30456           Opc = N->getOpcode();
30457         }
30458         SDValue Res;
30459         SDValue Chain;
30460         if (IsStrict) {
30461           Res = DAG.getNode(Opc, dl, {MVT::v4i32, MVT::Other},
30462                             {N->getOperand(0), Src});
30463           Chain = Res.getValue(1);
30464         } else {
30465           Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
30466         }
30467         Results.push_back(Res);
30468         if (IsStrict)
30469           Results.push_back(Chain);
30470         return;
30471       }
30472 
30473       // Custom widen strict v2f32->v2i32 by padding with zeros.
30474       // FIXME: Should generic type legalizer do this?
30475       if (Src.getValueType() == MVT::v2f32 && IsStrict) {
30476         Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
30477                           DAG.getConstantFP(0.0, dl, MVT::v2f32));
30478         SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4i32, MVT::Other},
30479                                   {N->getOperand(0), Src});
30480         Results.push_back(Res);
30481         Results.push_back(Res.getValue(1));
30482         return;
30483       }
30484 
30485       // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
30486       // so early out here.
30487       return;
30488     }
30489 
30490     assert(!VT.isVector() && "Vectors should have been handled above!");
30491 
30492     if (Subtarget.hasDQI() && VT == MVT::i64 &&
30493         (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
30494       assert(!Subtarget.is64Bit() && "i64 should be legal");
30495       unsigned NumElts = Subtarget.hasVLX() ? 2 : 8;
30496       // If we use a 128-bit result we might need to use a target specific node.
30497       unsigned SrcElts =
30498           std::max(NumElts, 128U / (unsigned)SrcVT.getSizeInBits());
30499       MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
30500       MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), SrcElts);
30501       unsigned Opc = N->getOpcode();
30502       if (NumElts != SrcElts) {
30503         if (IsStrict)
30504           Opc = IsSigned ? X86ISD::STRICT_CVTTP2SI : X86ISD::STRICT_CVTTP2UI;
30505         else
30506           Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
30507       }
30508 
30509       SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
30510       SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
30511                                 DAG.getConstantFP(0.0, dl, VecInVT), Src,
30512                                 ZeroIdx);
30513       SDValue Chain;
30514       if (IsStrict) {
30515         SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
30516         Res = DAG.getNode(Opc, SDLoc(N), Tys, N->getOperand(0), Res);
30517         Chain = Res.getValue(1);
30518       } else
30519         Res = DAG.getNode(Opc, SDLoc(N), VecVT, Res);
30520       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
30521       Results.push_back(Res);
30522       if (IsStrict)
30523         Results.push_back(Chain);
30524       return;
30525     }
30526 
30527     SDValue Chain;
30528     if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, Chain)) {
30529       Results.push_back(V);
30530       if (IsStrict)
30531         Results.push_back(Chain);
30532     }
30533     return;
30534   }
30535   case ISD::LRINT:
30536   case ISD::LLRINT: {
30537     if (SDValue V = LRINT_LLRINTHelper(N, DAG))
30538       Results.push_back(V);
30539     return;
30540   }
30541 
30542   case ISD::SINT_TO_FP:
30543   case ISD::STRICT_SINT_TO_FP:
30544   case ISD::UINT_TO_FP:
30545   case ISD::STRICT_UINT_TO_FP: {
30546     bool IsStrict = N->isStrictFPOpcode();
30547     bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
30548                     N->getOpcode() == ISD::STRICT_SINT_TO_FP;
30549     EVT VT = N->getValueType(0);
30550     if (VT != MVT::v2f32)
30551       return;
30552     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
30553     EVT SrcVT = Src.getValueType();
30554     if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
30555       if (IsStrict) {
30556         unsigned Opc = IsSigned ? X86ISD::STRICT_CVTSI2P
30557                                 : X86ISD::STRICT_CVTUI2P;
30558         SDValue Res = DAG.getNode(Opc, dl, {MVT::v4f32, MVT::Other},
30559                                   {N->getOperand(0), Src});
30560         Results.push_back(Res);
30561         Results.push_back(Res.getValue(1));
30562       } else {
30563         unsigned Opc = IsSigned ? X86ISD::CVTSI2P : X86ISD::CVTUI2P;
30564         Results.push_back(DAG.getNode(Opc, dl, MVT::v4f32, Src));
30565       }
30566       return;
30567     }
30568     if (SrcVT == MVT::v2i64 && !IsSigned && Subtarget.is64Bit() &&
30569         Subtarget.hasSSE41() && !Subtarget.hasAVX512()) {
30570       SDValue Zero = DAG.getConstant(0, dl, SrcVT);
30571       SDValue One  = DAG.getConstant(1, dl, SrcVT);
30572       SDValue Sign = DAG.getNode(ISD::OR, dl, SrcVT,
30573                                  DAG.getNode(ISD::SRL, dl, SrcVT, Src, One),
30574                                  DAG.getNode(ISD::AND, dl, SrcVT, Src, One));
30575       SDValue IsNeg = DAG.getSetCC(dl, MVT::v2i64, Src, Zero, ISD::SETLT);
30576       SDValue SignSrc = DAG.getSelect(dl, SrcVT, IsNeg, Sign, Src);
30577       SmallVector<SDValue, 4> SignCvts(4, DAG.getConstantFP(0.0, dl, MVT::f32));
30578       for (int i = 0; i != 2; ++i) {
30579         SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
30580                                   SignSrc, DAG.getIntPtrConstant(i, dl));
30581         if (IsStrict)
30582           SignCvts[i] =
30583               DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {MVT::f32, MVT::Other},
30584                           {N->getOperand(0), Elt});
30585         else
30586           SignCvts[i] = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Elt);
30587       };
30588       SDValue SignCvt = DAG.getBuildVector(MVT::v4f32, dl, SignCvts);
30589       SDValue Slow, Chain;
30590       if (IsStrict) {
30591         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
30592                             SignCvts[0].getValue(1), SignCvts[1].getValue(1));
30593         Slow = DAG.getNode(ISD::STRICT_FADD, dl, {MVT::v4f32, MVT::Other},
30594                            {Chain, SignCvt, SignCvt});
30595         Chain = Slow.getValue(1);
30596       } else {
30597         Slow = DAG.getNode(ISD::FADD, dl, MVT::v4f32, SignCvt, SignCvt);
30598       }
30599       IsNeg = DAG.getBitcast(MVT::v4i32, IsNeg);
30600       IsNeg =
30601           DAG.getVectorShuffle(MVT::v4i32, dl, IsNeg, IsNeg, {1, 3, -1, -1});
30602       SDValue Cvt = DAG.getSelect(dl, MVT::v4f32, IsNeg, Slow, SignCvt);
30603       Results.push_back(Cvt);
30604       if (IsStrict)
30605         Results.push_back(Chain);
30606       return;
30607     }
30608 
30609     if (SrcVT != MVT::v2i32)
30610       return;
30611 
30612     if (IsSigned || Subtarget.hasAVX512()) {
30613       if (!IsStrict)
30614         return;
30615 
30616       // Custom widen strict v2i32->v2f32 to avoid scalarization.
30617       // FIXME: Should generic type legalizer do this?
30618       Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
30619                         DAG.getConstant(0, dl, MVT::v2i32));
30620       SDValue Res = DAG.getNode(N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
30621                                 {N->getOperand(0), Src});
30622       Results.push_back(Res);
30623       Results.push_back(Res.getValue(1));
30624       return;
30625     }
30626 
30627     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30628     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
30629     SDValue VBias =
30630         DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
30631     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
30632                              DAG.getBitcast(MVT::v2i64, VBias));
30633     Or = DAG.getBitcast(MVT::v2f64, Or);
30634     if (IsStrict) {
30635       SDValue Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::v2f64, MVT::Other},
30636                                 {N->getOperand(0), Or, VBias});
30637       SDValue Res = DAG.getNode(X86ISD::STRICT_VFPROUND, dl,
30638                                 {MVT::v4f32, MVT::Other},
30639                                 {Sub.getValue(1), Sub});
30640       Results.push_back(Res);
30641       Results.push_back(Res.getValue(1));
30642     } else {
30643       // TODO: Are there any fast-math-flags to propagate here?
30644       SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
30645       Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
30646     }
30647     return;
30648   }
30649   case ISD::STRICT_FP_ROUND:
30650   case ISD::FP_ROUND: {
30651     bool IsStrict = N->isStrictFPOpcode();
30652     SDValue Src = N->getOperand(IsStrict ? 1 : 0);
30653     if (!isTypeLegal(Src.getValueType()))
30654       return;
30655     SDValue V;
30656     if (IsStrict)
30657       V = DAG.getNode(X86ISD::STRICT_VFPROUND, dl, {MVT::v4f32, MVT::Other},
30658                       {N->getOperand(0), N->getOperand(1)});
30659     else
30660       V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
30661     Results.push_back(V);
30662     if (IsStrict)
30663       Results.push_back(V.getValue(1));
30664     return;
30665   }
30666   case ISD::FP_EXTEND:
30667   case ISD::STRICT_FP_EXTEND: {
30668     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
30669     // No other ValueType for FP_EXTEND should reach this point.
30670     assert(N->getValueType(0) == MVT::v2f32 &&
30671            "Do not know how to legalize this Node");
30672     return;
30673   }
30674   case ISD::INTRINSIC_W_CHAIN: {
30675     unsigned IntNo = N->getConstantOperandVal(1);
30676     switch (IntNo) {
30677     default : llvm_unreachable("Do not know how to custom type "
30678                                "legalize this intrinsic operation!");
30679     case Intrinsic::x86_rdtsc:
30680       return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
30681                                      Results);
30682     case Intrinsic::x86_rdtscp:
30683       return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
30684                                      Results);
30685     case Intrinsic::x86_rdpmc:
30686       expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
30687                                   Results);
30688       return;
30689     case Intrinsic::x86_xgetbv:
30690       expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
30691                                   Results);
30692       return;
30693     }
30694   }
30695   case ISD::READCYCLECOUNTER: {
30696     return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
30697   }
30698   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
30699     EVT T = N->getValueType(0);
30700     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
30701     bool Regs64bit = T == MVT::i128;
30702     assert((!Regs64bit || Subtarget.hasCmpxchg16b()) &&
30703            "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B");
30704     MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
30705     SDValue cpInL, cpInH;
30706     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
30707                         DAG.getConstant(0, dl, HalfT));
30708     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
30709                         DAG.getConstant(1, dl, HalfT));
30710     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
30711                              Regs64bit ? X86::RAX : X86::EAX,
30712                              cpInL, SDValue());
30713     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
30714                              Regs64bit ? X86::RDX : X86::EDX,
30715                              cpInH, cpInL.getValue(1));
30716     SDValue swapInL, swapInH;
30717     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
30718                           DAG.getConstant(0, dl, HalfT));
30719     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
30720                           DAG.getConstant(1, dl, HalfT));
30721     swapInH =
30722         DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
30723                          swapInH, cpInH.getValue(1));
30724 
30725     // In 64-bit mode we might need the base pointer in RBX, but we can't know
30726     // until later. So we keep the RBX input in a vreg and use a custom
30727     // inserter.
30728     // Since RBX will be a reserved register the register allocator will not
30729     // make sure its value will be properly saved and restored around this
30730     // live-range.
30731     SDValue Result;
30732     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
30733     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
30734     if (Regs64bit) {
30735       SDValue Ops[] = {swapInH.getValue(0), N->getOperand(1), swapInL,
30736                        swapInH.getValue(1)};
30737       Result =
30738           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG16_DAG, dl, Tys, Ops, T, MMO);
30739     } else {
30740       swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl, X86::EBX, swapInL,
30741                                  swapInH.getValue(1));
30742       SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
30743                        swapInL.getValue(1)};
30744       Result =
30745           DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, T, MMO);
30746     }
30747 
30748     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
30749                                         Regs64bit ? X86::RAX : X86::EAX,
30750                                         HalfT, Result.getValue(1));
30751     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
30752                                         Regs64bit ? X86::RDX : X86::EDX,
30753                                         HalfT, cpOutL.getValue(2));
30754     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
30755 
30756     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
30757                                         MVT::i32, cpOutH.getValue(2));
30758     SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
30759     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
30760 
30761     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
30762     Results.push_back(Success);
30763     Results.push_back(EFLAGS.getValue(1));
30764     return;
30765   }
30766   case ISD::ATOMIC_LOAD: {
30767     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
30768     bool NoImplicitFloatOps =
30769         DAG.getMachineFunction().getFunction().hasFnAttribute(
30770             Attribute::NoImplicitFloat);
30771     if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
30772       auto *Node = cast<AtomicSDNode>(N);
30773       if (Subtarget.hasSSE1()) {
30774         // Use a VZEXT_LOAD which will be selected as MOVQ or XORPS+MOVLPS.
30775         // Then extract the lower 64-bits.
30776         MVT LdVT = Subtarget.hasSSE2() ? MVT::v2i64 : MVT::v4f32;
30777         SDVTList Tys = DAG.getVTList(LdVT, MVT::Other);
30778         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
30779         SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
30780                                              MVT::i64, Node->getMemOperand());
30781         if (Subtarget.hasSSE2()) {
30782           SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
30783                                     DAG.getIntPtrConstant(0, dl));
30784           Results.push_back(Res);
30785           Results.push_back(Ld.getValue(1));
30786           return;
30787         }
30788         // We use an alternative sequence for SSE1 that extracts as v2f32 and
30789         // then casts to i64. This avoids a 128-bit stack temporary being
30790         // created by type legalization if we were to cast v4f32->v2i64.
30791         SDValue Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Ld,
30792                                   DAG.getIntPtrConstant(0, dl));
30793         Res = DAG.getBitcast(MVT::i64, Res);
30794         Results.push_back(Res);
30795         Results.push_back(Ld.getValue(1));
30796         return;
30797       }
30798       if (Subtarget.hasX87()) {
30799         // First load this into an 80-bit X87 register. This will put the whole
30800         // integer into the significand.
30801         SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
30802         SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
30803         SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD,
30804                                                  dl, Tys, Ops, MVT::i64,
30805                                                  Node->getMemOperand());
30806         SDValue Chain = Result.getValue(1);
30807 
30808         // Now store the X87 register to a stack temporary and convert to i64.
30809         // This store is not atomic and doesn't need to be.
30810         // FIXME: We don't need a stack temporary if the result of the load
30811         // is already being stored. We could just directly store there.
30812         SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
30813         int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
30814         MachinePointerInfo MPI =
30815             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
30816         SDValue StoreOps[] = { Chain, Result, StackPtr };
30817         Chain = DAG.getMemIntrinsicNode(
30818             X86ISD::FIST, dl, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
30819             MPI, None /*Align*/, MachineMemOperand::MOStore);
30820 
30821         // Finally load the value back from the stack temporary and return it.
30822         // This load is not atomic and doesn't need to be.
30823         // This load will be further type legalized.
30824         Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
30825         Results.push_back(Result);
30826         Results.push_back(Result.getValue(1));
30827         return;
30828       }
30829     }
30830     // TODO: Use MOVLPS when SSE1 is available?
30831     // Delegate to generic TypeLegalization. Situations we can really handle
30832     // should have already been dealt with by AtomicExpandPass.cpp.
30833     break;
30834   }
30835   case ISD::ATOMIC_SWAP:
30836   case ISD::ATOMIC_LOAD_ADD:
30837   case ISD::ATOMIC_LOAD_SUB:
30838   case ISD::ATOMIC_LOAD_AND:
30839   case ISD::ATOMIC_LOAD_OR:
30840   case ISD::ATOMIC_LOAD_XOR:
30841   case ISD::ATOMIC_LOAD_NAND:
30842   case ISD::ATOMIC_LOAD_MIN:
30843   case ISD::ATOMIC_LOAD_MAX:
30844   case ISD::ATOMIC_LOAD_UMIN:
30845   case ISD::ATOMIC_LOAD_UMAX:
30846     // Delegate to generic TypeLegalization. Situations we can really handle
30847     // should have already been dealt with by AtomicExpandPass.cpp.
30848     break;
30849 
30850   case ISD::BITCAST: {
30851     assert(Subtarget.hasSSE2() && "Requires at least SSE2!");
30852     EVT DstVT = N->getValueType(0);
30853     EVT SrcVT = N->getOperand(0).getValueType();
30854 
30855     // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
30856     // we can split using the k-register rather than memory.
30857     if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
30858       assert(!Subtarget.is64Bit() && "Expected 32-bit mode");
30859       SDValue Lo, Hi;
30860       std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
30861       Lo = DAG.getBitcast(MVT::i32, Lo);
30862       Hi = DAG.getBitcast(MVT::i32, Hi);
30863       SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
30864       Results.push_back(Res);
30865       return;
30866     }
30867 
30868     if (DstVT.isVector() && SrcVT == MVT::x86mmx) {
30869       // FIXME: Use v4f32 for SSE1?
30870       assert(Subtarget.hasSSE2() && "Requires SSE2");
30871       assert(getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector &&
30872              "Unexpected type action!");
30873       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), DstVT);
30874       SDValue Res = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64,
30875                                 N->getOperand(0));
30876       Res = DAG.getBitcast(WideVT, Res);
30877       Results.push_back(Res);
30878       return;
30879     }
30880 
30881     return;
30882   }
30883   case ISD::MGATHER: {
30884     EVT VT = N->getValueType(0);
30885     if ((VT == MVT::v2f32 || VT == MVT::v2i32) &&
30886         (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
30887       auto *Gather = cast<MaskedGatherSDNode>(N);
30888       SDValue Index = Gather->getIndex();
30889       if (Index.getValueType() != MVT::v2i64)
30890         return;
30891       assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30892              "Unexpected type action!");
30893       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
30894       SDValue Mask = Gather->getMask();
30895       assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type");
30896       SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT,
30897                                      Gather->getPassThru(),
30898                                      DAG.getUNDEF(VT));
30899       if (!Subtarget.hasVLX()) {
30900         // We need to widen the mask, but the instruction will only use 2
30901         // of its elements. So we can use undef.
30902         Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
30903                            DAG.getUNDEF(MVT::v2i1));
30904         Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
30905       }
30906       SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
30907                         Gather->getBasePtr(), Index, Gather->getScale() };
30908       SDValue Res = DAG.getMemIntrinsicNode(
30909           X86ISD::MGATHER, dl, DAG.getVTList(WideVT, MVT::Other), Ops,
30910           Gather->getMemoryVT(), Gather->getMemOperand());
30911       Results.push_back(Res);
30912       Results.push_back(Res.getValue(1));
30913       return;
30914     }
30915     return;
30916   }
30917   case ISD::LOAD: {
30918     // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
30919     // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
30920     // cast since type legalization will try to use an i64 load.
30921     MVT VT = N->getSimpleValueType(0);
30922     assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT");
30923     assert(getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
30924            "Unexpected type action!");
30925     if (!ISD::isNON_EXTLoad(N))
30926       return;
30927     auto *Ld = cast<LoadSDNode>(N);
30928     if (Subtarget.hasSSE2()) {
30929       MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
30930       SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
30931                                 Ld->getPointerInfo(), Ld->getOriginalAlign(),
30932                                 Ld->getMemOperand()->getFlags());
30933       SDValue Chain = Res.getValue(1);
30934       MVT VecVT = MVT::getVectorVT(LdVT, 2);
30935       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Res);
30936       EVT WideVT = getTypeToTransformTo(*DAG.getContext(), VT);
30937       Res = DAG.getBitcast(WideVT, Res);
30938       Results.push_back(Res);
30939       Results.push_back(Chain);
30940       return;
30941     }
30942     assert(Subtarget.hasSSE1() && "Expected SSE");
30943     SDVTList Tys = DAG.getVTList(MVT::v4f32, MVT::Other);
30944     SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
30945     SDValue Res = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
30946                                           MVT::i64, Ld->getMemOperand());
30947     Results.push_back(Res);
30948     Results.push_back(Res.getValue(1));
30949     return;
30950   }
30951   case ISD::ADDRSPACECAST: {
30952     SDValue V = LowerADDRSPACECAST(SDValue(N,0), DAG);
30953     Results.push_back(V);
30954     return;
30955   }
30956   case ISD::BITREVERSE:
30957     assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!");
30958     assert(Subtarget.hasXOP() && "Expected XOP");
30959     // We can use VPPERM by copying to a vector register and back. We'll need
30960     // to move the scalar in two i32 pieces.
30961     Results.push_back(LowerBITREVERSE(SDValue(N, 0), Subtarget, DAG));
30962     return;
30963   }
30964 }
30965 
30966 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
30967   switch ((X86ISD::NodeType)Opcode) {
30968   case X86ISD::FIRST_NUMBER:       break;
30969 #define NODE_NAME_CASE(NODE) case X86ISD::NODE: return "X86ISD::" #NODE;
30970   NODE_NAME_CASE(BSF)
30971   NODE_NAME_CASE(BSR)
30972   NODE_NAME_CASE(FSHL)
30973   NODE_NAME_CASE(FSHR)
30974   NODE_NAME_CASE(FAND)
30975   NODE_NAME_CASE(FANDN)
30976   NODE_NAME_CASE(FOR)
30977   NODE_NAME_CASE(FXOR)
30978   NODE_NAME_CASE(FILD)
30979   NODE_NAME_CASE(FIST)
30980   NODE_NAME_CASE(FP_TO_INT_IN_MEM)
30981   NODE_NAME_CASE(FLD)
30982   NODE_NAME_CASE(FST)
30983   NODE_NAME_CASE(CALL)
30984   NODE_NAME_CASE(BT)
30985   NODE_NAME_CASE(CMP)
30986   NODE_NAME_CASE(FCMP)
30987   NODE_NAME_CASE(STRICT_FCMP)
30988   NODE_NAME_CASE(STRICT_FCMPS)
30989   NODE_NAME_CASE(COMI)
30990   NODE_NAME_CASE(UCOMI)
30991   NODE_NAME_CASE(CMPM)
30992   NODE_NAME_CASE(CMPMM)
30993   NODE_NAME_CASE(STRICT_CMPM)
30994   NODE_NAME_CASE(CMPMM_SAE)
30995   NODE_NAME_CASE(SETCC)
30996   NODE_NAME_CASE(SETCC_CARRY)
30997   NODE_NAME_CASE(FSETCC)
30998   NODE_NAME_CASE(FSETCCM)
30999   NODE_NAME_CASE(FSETCCM_SAE)
31000   NODE_NAME_CASE(CMOV)
31001   NODE_NAME_CASE(BRCOND)
31002   NODE_NAME_CASE(RET_FLAG)
31003   NODE_NAME_CASE(IRET)
31004   NODE_NAME_CASE(REP_STOS)
31005   NODE_NAME_CASE(REP_MOVS)
31006   NODE_NAME_CASE(GlobalBaseReg)
31007   NODE_NAME_CASE(Wrapper)
31008   NODE_NAME_CASE(WrapperRIP)
31009   NODE_NAME_CASE(MOVQ2DQ)
31010   NODE_NAME_CASE(MOVDQ2Q)
31011   NODE_NAME_CASE(MMX_MOVD2W)
31012   NODE_NAME_CASE(MMX_MOVW2D)
31013   NODE_NAME_CASE(PEXTRB)
31014   NODE_NAME_CASE(PEXTRW)
31015   NODE_NAME_CASE(INSERTPS)
31016   NODE_NAME_CASE(PINSRB)
31017   NODE_NAME_CASE(PINSRW)
31018   NODE_NAME_CASE(PSHUFB)
31019   NODE_NAME_CASE(ANDNP)
31020   NODE_NAME_CASE(BLENDI)
31021   NODE_NAME_CASE(BLENDV)
31022   NODE_NAME_CASE(HADD)
31023   NODE_NAME_CASE(HSUB)
31024   NODE_NAME_CASE(FHADD)
31025   NODE_NAME_CASE(FHSUB)
31026   NODE_NAME_CASE(CONFLICT)
31027   NODE_NAME_CASE(FMAX)
31028   NODE_NAME_CASE(FMAXS)
31029   NODE_NAME_CASE(FMAX_SAE)
31030   NODE_NAME_CASE(FMAXS_SAE)
31031   NODE_NAME_CASE(FMIN)
31032   NODE_NAME_CASE(FMINS)
31033   NODE_NAME_CASE(FMIN_SAE)
31034   NODE_NAME_CASE(FMINS_SAE)
31035   NODE_NAME_CASE(FMAXC)
31036   NODE_NAME_CASE(FMINC)
31037   NODE_NAME_CASE(FRSQRT)
31038   NODE_NAME_CASE(FRCP)
31039   NODE_NAME_CASE(EXTRQI)
31040   NODE_NAME_CASE(INSERTQI)
31041   NODE_NAME_CASE(TLSADDR)
31042   NODE_NAME_CASE(TLSBASEADDR)
31043   NODE_NAME_CASE(TLSCALL)
31044   NODE_NAME_CASE(EH_SJLJ_SETJMP)
31045   NODE_NAME_CASE(EH_SJLJ_LONGJMP)
31046   NODE_NAME_CASE(EH_SJLJ_SETUP_DISPATCH)
31047   NODE_NAME_CASE(EH_RETURN)
31048   NODE_NAME_CASE(TC_RETURN)
31049   NODE_NAME_CASE(FNSTCW16m)
31050   NODE_NAME_CASE(LCMPXCHG_DAG)
31051   NODE_NAME_CASE(LCMPXCHG8_DAG)
31052   NODE_NAME_CASE(LCMPXCHG16_DAG)
31053   NODE_NAME_CASE(LCMPXCHG16_SAVE_RBX_DAG)
31054   NODE_NAME_CASE(LADD)
31055   NODE_NAME_CASE(LSUB)
31056   NODE_NAME_CASE(LOR)
31057   NODE_NAME_CASE(LXOR)
31058   NODE_NAME_CASE(LAND)
31059   NODE_NAME_CASE(VZEXT_MOVL)
31060   NODE_NAME_CASE(VZEXT_LOAD)
31061   NODE_NAME_CASE(VEXTRACT_STORE)
31062   NODE_NAME_CASE(VTRUNC)
31063   NODE_NAME_CASE(VTRUNCS)
31064   NODE_NAME_CASE(VTRUNCUS)
31065   NODE_NAME_CASE(VMTRUNC)
31066   NODE_NAME_CASE(VMTRUNCS)
31067   NODE_NAME_CASE(VMTRUNCUS)
31068   NODE_NAME_CASE(VTRUNCSTORES)
31069   NODE_NAME_CASE(VTRUNCSTOREUS)
31070   NODE_NAME_CASE(VMTRUNCSTORES)
31071   NODE_NAME_CASE(VMTRUNCSTOREUS)
31072   NODE_NAME_CASE(VFPEXT)
31073   NODE_NAME_CASE(STRICT_VFPEXT)
31074   NODE_NAME_CASE(VFPEXT_SAE)
31075   NODE_NAME_CASE(VFPEXTS)
31076   NODE_NAME_CASE(VFPEXTS_SAE)
31077   NODE_NAME_CASE(VFPROUND)
31078   NODE_NAME_CASE(STRICT_VFPROUND)
31079   NODE_NAME_CASE(VMFPROUND)
31080   NODE_NAME_CASE(VFPROUND_RND)
31081   NODE_NAME_CASE(VFPROUNDS)
31082   NODE_NAME_CASE(VFPROUNDS_RND)
31083   NODE_NAME_CASE(VSHLDQ)
31084   NODE_NAME_CASE(VSRLDQ)
31085   NODE_NAME_CASE(VSHL)
31086   NODE_NAME_CASE(VSRL)
31087   NODE_NAME_CASE(VSRA)
31088   NODE_NAME_CASE(VSHLI)
31089   NODE_NAME_CASE(VSRLI)
31090   NODE_NAME_CASE(VSRAI)
31091   NODE_NAME_CASE(VSHLV)
31092   NODE_NAME_CASE(VSRLV)
31093   NODE_NAME_CASE(VSRAV)
31094   NODE_NAME_CASE(VROTLI)
31095   NODE_NAME_CASE(VROTRI)
31096   NODE_NAME_CASE(VPPERM)
31097   NODE_NAME_CASE(CMPP)
31098   NODE_NAME_CASE(STRICT_CMPP)
31099   NODE_NAME_CASE(PCMPEQ)
31100   NODE_NAME_CASE(PCMPGT)
31101   NODE_NAME_CASE(PHMINPOS)
31102   NODE_NAME_CASE(ADD)
31103   NODE_NAME_CASE(SUB)
31104   NODE_NAME_CASE(ADC)
31105   NODE_NAME_CASE(SBB)
31106   NODE_NAME_CASE(SMUL)
31107   NODE_NAME_CASE(UMUL)
31108   NODE_NAME_CASE(OR)
31109   NODE_NAME_CASE(XOR)
31110   NODE_NAME_CASE(AND)
31111   NODE_NAME_CASE(BEXTR)
31112   NODE_NAME_CASE(BEXTRI)
31113   NODE_NAME_CASE(BZHI)
31114   NODE_NAME_CASE(PDEP)
31115   NODE_NAME_CASE(PEXT)
31116   NODE_NAME_CASE(MUL_IMM)
31117   NODE_NAME_CASE(MOVMSK)
31118   NODE_NAME_CASE(PTEST)
31119   NODE_NAME_CASE(TESTP)
31120   NODE_NAME_CASE(KORTEST)
31121   NODE_NAME_CASE(KTEST)
31122   NODE_NAME_CASE(KADD)
31123   NODE_NAME_CASE(KSHIFTL)
31124   NODE_NAME_CASE(KSHIFTR)
31125   NODE_NAME_CASE(PACKSS)
31126   NODE_NAME_CASE(PACKUS)
31127   NODE_NAME_CASE(PALIGNR)
31128   NODE_NAME_CASE(VALIGN)
31129   NODE_NAME_CASE(VSHLD)
31130   NODE_NAME_CASE(VSHRD)
31131   NODE_NAME_CASE(VSHLDV)
31132   NODE_NAME_CASE(VSHRDV)
31133   NODE_NAME_CASE(PSHUFD)
31134   NODE_NAME_CASE(PSHUFHW)
31135   NODE_NAME_CASE(PSHUFLW)
31136   NODE_NAME_CASE(SHUFP)
31137   NODE_NAME_CASE(SHUF128)
31138   NODE_NAME_CASE(MOVLHPS)
31139   NODE_NAME_CASE(MOVHLPS)
31140   NODE_NAME_CASE(MOVDDUP)
31141   NODE_NAME_CASE(MOVSHDUP)
31142   NODE_NAME_CASE(MOVSLDUP)
31143   NODE_NAME_CASE(MOVSD)
31144   NODE_NAME_CASE(MOVSS)
31145   NODE_NAME_CASE(UNPCKL)
31146   NODE_NAME_CASE(UNPCKH)
31147   NODE_NAME_CASE(VBROADCAST)
31148   NODE_NAME_CASE(VBROADCAST_LOAD)
31149   NODE_NAME_CASE(VBROADCASTM)
31150   NODE_NAME_CASE(SUBV_BROADCAST_LOAD)
31151   NODE_NAME_CASE(VPERMILPV)
31152   NODE_NAME_CASE(VPERMILPI)
31153   NODE_NAME_CASE(VPERM2X128)
31154   NODE_NAME_CASE(VPERMV)
31155   NODE_NAME_CASE(VPERMV3)
31156   NODE_NAME_CASE(VPERMI)
31157   NODE_NAME_CASE(VPTERNLOG)
31158   NODE_NAME_CASE(VFIXUPIMM)
31159   NODE_NAME_CASE(VFIXUPIMM_SAE)
31160   NODE_NAME_CASE(VFIXUPIMMS)
31161   NODE_NAME_CASE(VFIXUPIMMS_SAE)
31162   NODE_NAME_CASE(VRANGE)
31163   NODE_NAME_CASE(VRANGE_SAE)
31164   NODE_NAME_CASE(VRANGES)
31165   NODE_NAME_CASE(VRANGES_SAE)
31166   NODE_NAME_CASE(PMULUDQ)
31167   NODE_NAME_CASE(PMULDQ)
31168   NODE_NAME_CASE(PSADBW)
31169   NODE_NAME_CASE(DBPSADBW)
31170   NODE_NAME_CASE(VASTART_SAVE_XMM_REGS)
31171   NODE_NAME_CASE(VAARG_64)
31172   NODE_NAME_CASE(VAARG_X32)
31173   NODE_NAME_CASE(WIN_ALLOCA)
31174   NODE_NAME_CASE(MEMBARRIER)
31175   NODE_NAME_CASE(MFENCE)
31176   NODE_NAME_CASE(SEG_ALLOCA)
31177   NODE_NAME_CASE(PROBED_ALLOCA)
31178   NODE_NAME_CASE(RDRAND)
31179   NODE_NAME_CASE(RDSEED)
31180   NODE_NAME_CASE(RDPKRU)
31181   NODE_NAME_CASE(WRPKRU)
31182   NODE_NAME_CASE(VPMADDUBSW)
31183   NODE_NAME_CASE(VPMADDWD)
31184   NODE_NAME_CASE(VPSHA)
31185   NODE_NAME_CASE(VPSHL)
31186   NODE_NAME_CASE(VPCOM)
31187   NODE_NAME_CASE(VPCOMU)
31188   NODE_NAME_CASE(VPERMIL2)
31189   NODE_NAME_CASE(FMSUB)
31190   NODE_NAME_CASE(STRICT_FMSUB)
31191   NODE_NAME_CASE(FNMADD)
31192   NODE_NAME_CASE(STRICT_FNMADD)
31193   NODE_NAME_CASE(FNMSUB)
31194   NODE_NAME_CASE(STRICT_FNMSUB)
31195   NODE_NAME_CASE(FMADDSUB)
31196   NODE_NAME_CASE(FMSUBADD)
31197   NODE_NAME_CASE(FMADD_RND)
31198   NODE_NAME_CASE(FNMADD_RND)
31199   NODE_NAME_CASE(FMSUB_RND)
31200   NODE_NAME_CASE(FNMSUB_RND)
31201   NODE_NAME_CASE(FMADDSUB_RND)
31202   NODE_NAME_CASE(FMSUBADD_RND)
31203   NODE_NAME_CASE(VPMADD52H)
31204   NODE_NAME_CASE(VPMADD52L)
31205   NODE_NAME_CASE(VRNDSCALE)
31206   NODE_NAME_CASE(STRICT_VRNDSCALE)
31207   NODE_NAME_CASE(VRNDSCALE_SAE)
31208   NODE_NAME_CASE(VRNDSCALES)
31209   NODE_NAME_CASE(VRNDSCALES_SAE)
31210   NODE_NAME_CASE(VREDUCE)
31211   NODE_NAME_CASE(VREDUCE_SAE)
31212   NODE_NAME_CASE(VREDUCES)
31213   NODE_NAME_CASE(VREDUCES_SAE)
31214   NODE_NAME_CASE(VGETMANT)
31215   NODE_NAME_CASE(VGETMANT_SAE)
31216   NODE_NAME_CASE(VGETMANTS)
31217   NODE_NAME_CASE(VGETMANTS_SAE)
31218   NODE_NAME_CASE(PCMPESTR)
31219   NODE_NAME_CASE(PCMPISTR)
31220   NODE_NAME_CASE(XTEST)
31221   NODE_NAME_CASE(COMPRESS)
31222   NODE_NAME_CASE(EXPAND)
31223   NODE_NAME_CASE(SELECTS)
31224   NODE_NAME_CASE(ADDSUB)
31225   NODE_NAME_CASE(RCP14)
31226   NODE_NAME_CASE(RCP14S)
31227   NODE_NAME_CASE(RCP28)
31228   NODE_NAME_CASE(RCP28_SAE)
31229   NODE_NAME_CASE(RCP28S)
31230   NODE_NAME_CASE(RCP28S_SAE)
31231   NODE_NAME_CASE(EXP2)
31232   NODE_NAME_CASE(EXP2_SAE)
31233   NODE_NAME_CASE(RSQRT14)
31234   NODE_NAME_CASE(RSQRT14S)
31235   NODE_NAME_CASE(RSQRT28)
31236   NODE_NAME_CASE(RSQRT28_SAE)
31237   NODE_NAME_CASE(RSQRT28S)
31238   NODE_NAME_CASE(RSQRT28S_SAE)
31239   NODE_NAME_CASE(FADD_RND)
31240   NODE_NAME_CASE(FADDS)
31241   NODE_NAME_CASE(FADDS_RND)
31242   NODE_NAME_CASE(FSUB_RND)
31243   NODE_NAME_CASE(FSUBS)
31244   NODE_NAME_CASE(FSUBS_RND)
31245   NODE_NAME_CASE(FMUL_RND)
31246   NODE_NAME_CASE(FMULS)
31247   NODE_NAME_CASE(FMULS_RND)
31248   NODE_NAME_CASE(FDIV_RND)
31249   NODE_NAME_CASE(FDIVS)
31250   NODE_NAME_CASE(FDIVS_RND)
31251   NODE_NAME_CASE(FSQRT_RND)
31252   NODE_NAME_CASE(FSQRTS)
31253   NODE_NAME_CASE(FSQRTS_RND)
31254   NODE_NAME_CASE(FGETEXP)
31255   NODE_NAME_CASE(FGETEXP_SAE)
31256   NODE_NAME_CASE(FGETEXPS)
31257   NODE_NAME_CASE(FGETEXPS_SAE)
31258   NODE_NAME_CASE(SCALEF)
31259   NODE_NAME_CASE(SCALEF_RND)
31260   NODE_NAME_CASE(SCALEFS)
31261   NODE_NAME_CASE(SCALEFS_RND)
31262   NODE_NAME_CASE(AVG)
31263   NODE_NAME_CASE(MULHRS)
31264   NODE_NAME_CASE(SINT_TO_FP_RND)
31265   NODE_NAME_CASE(UINT_TO_FP_RND)
31266   NODE_NAME_CASE(CVTTP2SI)
31267   NODE_NAME_CASE(CVTTP2UI)
31268   NODE_NAME_CASE(STRICT_CVTTP2SI)
31269   NODE_NAME_CASE(STRICT_CVTTP2UI)
31270   NODE_NAME_CASE(MCVTTP2SI)
31271   NODE_NAME_CASE(MCVTTP2UI)
31272   NODE_NAME_CASE(CVTTP2SI_SAE)
31273   NODE_NAME_CASE(CVTTP2UI_SAE)
31274   NODE_NAME_CASE(CVTTS2SI)
31275   NODE_NAME_CASE(CVTTS2UI)
31276   NODE_NAME_CASE(CVTTS2SI_SAE)
31277   NODE_NAME_CASE(CVTTS2UI_SAE)
31278   NODE_NAME_CASE(CVTSI2P)
31279   NODE_NAME_CASE(CVTUI2P)
31280   NODE_NAME_CASE(STRICT_CVTSI2P)
31281   NODE_NAME_CASE(STRICT_CVTUI2P)
31282   NODE_NAME_CASE(MCVTSI2P)
31283   NODE_NAME_CASE(MCVTUI2P)
31284   NODE_NAME_CASE(VFPCLASS)
31285   NODE_NAME_CASE(VFPCLASSS)
31286   NODE_NAME_CASE(MULTISHIFT)
31287   NODE_NAME_CASE(SCALAR_SINT_TO_FP)
31288   NODE_NAME_CASE(SCALAR_SINT_TO_FP_RND)
31289   NODE_NAME_CASE(SCALAR_UINT_TO_FP)
31290   NODE_NAME_CASE(SCALAR_UINT_TO_FP_RND)
31291   NODE_NAME_CASE(CVTPS2PH)
31292   NODE_NAME_CASE(STRICT_CVTPS2PH)
31293   NODE_NAME_CASE(MCVTPS2PH)
31294   NODE_NAME_CASE(CVTPH2PS)
31295   NODE_NAME_CASE(STRICT_CVTPH2PS)
31296   NODE_NAME_CASE(CVTPH2PS_SAE)
31297   NODE_NAME_CASE(CVTP2SI)
31298   NODE_NAME_CASE(CVTP2UI)
31299   NODE_NAME_CASE(MCVTP2SI)
31300   NODE_NAME_CASE(MCVTP2UI)
31301   NODE_NAME_CASE(CVTP2SI_RND)
31302   NODE_NAME_CASE(CVTP2UI_RND)
31303   NODE_NAME_CASE(CVTS2SI)
31304   NODE_NAME_CASE(CVTS2UI)
31305   NODE_NAME_CASE(CVTS2SI_RND)
31306   NODE_NAME_CASE(CVTS2UI_RND)
31307   NODE_NAME_CASE(CVTNE2PS2BF16)
31308   NODE_NAME_CASE(CVTNEPS2BF16)
31309   NODE_NAME_CASE(MCVTNEPS2BF16)
31310   NODE_NAME_CASE(DPBF16PS)
31311   NODE_NAME_CASE(LWPINS)
31312   NODE_NAME_CASE(MGATHER)
31313   NODE_NAME_CASE(MSCATTER)
31314   NODE_NAME_CASE(VPDPBUSD)
31315   NODE_NAME_CASE(VPDPBUSDS)
31316   NODE_NAME_CASE(VPDPWSSD)
31317   NODE_NAME_CASE(VPDPWSSDS)
31318   NODE_NAME_CASE(VPSHUFBITQMB)
31319   NODE_NAME_CASE(GF2P8MULB)
31320   NODE_NAME_CASE(GF2P8AFFINEQB)
31321   NODE_NAME_CASE(GF2P8AFFINEINVQB)
31322   NODE_NAME_CASE(NT_CALL)
31323   NODE_NAME_CASE(NT_BRIND)
31324   NODE_NAME_CASE(UMWAIT)
31325   NODE_NAME_CASE(TPAUSE)
31326   NODE_NAME_CASE(ENQCMD)
31327   NODE_NAME_CASE(ENQCMDS)
31328   NODE_NAME_CASE(VP2INTERSECT)
31329   NODE_NAME_CASE(AESENC128KL)
31330   NODE_NAME_CASE(AESDEC128KL)
31331   NODE_NAME_CASE(AESENC256KL)
31332   NODE_NAME_CASE(AESDEC256KL)
31333   NODE_NAME_CASE(AESENCWIDE128KL)
31334   NODE_NAME_CASE(AESDECWIDE128KL)
31335   NODE_NAME_CASE(AESENCWIDE256KL)
31336   NODE_NAME_CASE(AESDECWIDE256KL)
31337   NODE_NAME_CASE(TESTUI)
31338   }
31339   return nullptr;
31340 #undef NODE_NAME_CASE
31341 }
31342 
31343 /// Return true if the addressing mode represented by AM is legal for this
31344 /// target, for a load/store of the specified type.
31345 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
31346                                               const AddrMode &AM, Type *Ty,
31347                                               unsigned AS,
31348                                               Instruction *I) const {
31349   // X86 supports extremely general addressing modes.
31350   CodeModel::Model M = getTargetMachine().getCodeModel();
31351 
31352   // X86 allows a sign-extended 32-bit immediate field as a displacement.
31353   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
31354     return false;
31355 
31356   if (AM.BaseGV) {
31357     unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
31358 
31359     // If a reference to this global requires an extra load, we can't fold it.
31360     if (isGlobalStubReference(GVFlags))
31361       return false;
31362 
31363     // If BaseGV requires a register for the PIC base, we cannot also have a
31364     // BaseReg specified.
31365     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
31366       return false;
31367 
31368     // If lower 4G is not available, then we must use rip-relative addressing.
31369     if ((M != CodeModel::Small || isPositionIndependent()) &&
31370         Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
31371       return false;
31372   }
31373 
31374   switch (AM.Scale) {
31375   case 0:
31376   case 1:
31377   case 2:
31378   case 4:
31379   case 8:
31380     // These scales always work.
31381     break;
31382   case 3:
31383   case 5:
31384   case 9:
31385     // These scales are formed with basereg+scalereg.  Only accept if there is
31386     // no basereg yet.
31387     if (AM.HasBaseReg)
31388       return false;
31389     break;
31390   default:  // Other stuff never works.
31391     return false;
31392   }
31393 
31394   return true;
31395 }
31396 
31397 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
31398   unsigned Bits = Ty->getScalarSizeInBits();
31399 
31400   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
31401   // particularly cheaper than those without.
31402   if (Bits == 8)
31403     return false;
31404 
31405   // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
31406   // Splitting for v32i8/v16i16 on XOP+AVX2 targets is still preferred.
31407   if (Subtarget.hasXOP() &&
31408       (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
31409     return false;
31410 
31411   // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
31412   // shifts just as cheap as scalar ones.
31413   if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
31414     return false;
31415 
31416   // AVX512BW has shifts such as vpsllvw.
31417   if (Subtarget.hasBWI() && Bits == 16)
31418       return false;
31419 
31420   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
31421   // fully general vector.
31422   return true;
31423 }
31424 
31425 bool X86TargetLowering::isBinOp(unsigned Opcode) const {
31426   switch (Opcode) {
31427   // These are non-commutative binops.
31428   // TODO: Add more X86ISD opcodes once we have test coverage.
31429   case X86ISD::ANDNP:
31430   case X86ISD::PCMPGT:
31431   case X86ISD::FMAX:
31432   case X86ISD::FMIN:
31433   case X86ISD::FANDN:
31434     return true;
31435   }
31436 
31437   return TargetLoweringBase::isBinOp(Opcode);
31438 }
31439 
31440 bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
31441   switch (Opcode) {
31442   // TODO: Add more X86ISD opcodes once we have test coverage.
31443   case X86ISD::PCMPEQ:
31444   case X86ISD::PMULDQ:
31445   case X86ISD::PMULUDQ:
31446   case X86ISD::FMAXC:
31447   case X86ISD::FMINC:
31448   case X86ISD::FAND:
31449   case X86ISD::FOR:
31450   case X86ISD::FXOR:
31451     return true;
31452   }
31453 
31454   return TargetLoweringBase::isCommutativeBinOp(Opcode);
31455 }
31456 
31457 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
31458   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
31459     return false;
31460   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
31461   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
31462   return NumBits1 > NumBits2;
31463 }
31464 
31465 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
31466   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
31467     return false;
31468 
31469   if (!isTypeLegal(EVT::getEVT(Ty1)))
31470     return false;
31471 
31472   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
31473 
31474   // Assuming the caller doesn't have a zeroext or signext return parameter,
31475   // truncation all the way down to i1 is valid.
31476   return true;
31477 }
31478 
31479 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
31480   return isInt<32>(Imm);
31481 }
31482 
31483 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
31484   // Can also use sub to handle negated immediates.
31485   return isInt<32>(Imm);
31486 }
31487 
31488 bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
31489   return isInt<32>(Imm);
31490 }
31491 
31492 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
31493   if (!VT1.isScalarInteger() || !VT2.isScalarInteger())
31494     return false;
31495   unsigned NumBits1 = VT1.getSizeInBits();
31496   unsigned NumBits2 = VT2.getSizeInBits();
31497   return NumBits1 > NumBits2;
31498 }
31499 
31500 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
31501   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
31502   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
31503 }
31504 
31505 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
31506   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
31507   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
31508 }
31509 
31510 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
31511   EVT VT1 = Val.getValueType();
31512   if (isZExtFree(VT1, VT2))
31513     return true;
31514 
31515   if (Val.getOpcode() != ISD::LOAD)
31516     return false;
31517 
31518   if (!VT1.isSimple() || !VT1.isInteger() ||
31519       !VT2.isSimple() || !VT2.isInteger())
31520     return false;
31521 
31522   switch (VT1.getSimpleVT().SimpleTy) {
31523   default: break;
31524   case MVT::i8:
31525   case MVT::i16:
31526   case MVT::i32:
31527     // X86 has 8, 16, and 32-bit zero-extending loads.
31528     return true;
31529   }
31530 
31531   return false;
31532 }
31533 
31534 bool X86TargetLowering::shouldSinkOperands(Instruction *I,
31535                                            SmallVectorImpl<Use *> &Ops) const {
31536   // A uniform shift amount in a vector shift or funnel shift may be much
31537   // cheaper than a generic variable vector shift, so make that pattern visible
31538   // to SDAG by sinking the shuffle instruction next to the shift.
31539   int ShiftAmountOpNum = -1;
31540   if (I->isShift())
31541     ShiftAmountOpNum = 1;
31542   else if (auto *II = dyn_cast<IntrinsicInst>(I)) {
31543     if (II->getIntrinsicID() == Intrinsic::fshl ||
31544         II->getIntrinsicID() == Intrinsic::fshr)
31545       ShiftAmountOpNum = 2;
31546   }
31547 
31548   if (ShiftAmountOpNum == -1)
31549     return false;
31550 
31551   auto *Shuf = dyn_cast<ShuffleVectorInst>(I->getOperand(ShiftAmountOpNum));
31552   if (Shuf && getSplatIndex(Shuf->getShuffleMask()) >= 0 &&
31553       isVectorShiftByScalarCheap(I->getType())) {
31554     Ops.push_back(&I->getOperandUse(ShiftAmountOpNum));
31555     return true;
31556   }
31557 
31558   return false;
31559 }
31560 
31561 bool X86TargetLowering::shouldConvertPhiType(Type *From, Type *To) const {
31562   if (!Subtarget.is64Bit())
31563     return false;
31564   return TargetLowering::shouldConvertPhiType(From, To);
31565 }
31566 
31567 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
31568   if (isa<MaskedLoadSDNode>(ExtVal.getOperand(0)))
31569     return false;
31570 
31571   EVT SrcVT = ExtVal.getOperand(0).getValueType();
31572 
31573   // There is no extending load for vXi1.
31574   if (SrcVT.getScalarType() == MVT::i1)
31575     return false;
31576 
31577   return true;
31578 }
31579 
31580 bool X86TargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
31581                                                    EVT VT) const {
31582   if (!Subtarget.hasAnyFMA())
31583     return false;
31584 
31585   VT = VT.getScalarType();
31586 
31587   if (!VT.isSimple())
31588     return false;
31589 
31590   switch (VT.getSimpleVT().SimpleTy) {
31591   case MVT::f32:
31592   case MVT::f64:
31593     return true;
31594   default:
31595     break;
31596   }
31597 
31598   return false;
31599 }
31600 
31601 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
31602   // i16 instructions are longer (0x66 prefix) and potentially slower.
31603   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
31604 }
31605 
31606 /// Targets can use this to indicate that they only support *some*
31607 /// VECTOR_SHUFFLE operations, those with specific masks.
31608 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
31609 /// are assumed to be legal.
31610 bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
31611   if (!VT.isSimple())
31612     return false;
31613 
31614   // Not for i1 vectors
31615   if (VT.getSimpleVT().getScalarType() == MVT::i1)
31616     return false;
31617 
31618   // Very little shuffling can be done for 64-bit vectors right now.
31619   if (VT.getSimpleVT().getSizeInBits() == 64)
31620     return false;
31621 
31622   // We only care that the types being shuffled are legal. The lowering can
31623   // handle any possible shuffle mask that results.
31624   return isTypeLegal(VT.getSimpleVT());
31625 }
31626 
31627 bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
31628                                                EVT VT) const {
31629   // Don't convert an 'and' into a shuffle that we don't directly support.
31630   // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
31631   if (!Subtarget.hasAVX2())
31632     if (VT == MVT::v32i8 || VT == MVT::v16i16)
31633       return false;
31634 
31635   // Just delegate to the generic legality, clear masks aren't special.
31636   return isShuffleMaskLegal(Mask, VT);
31637 }
31638 
31639 bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
31640   // If the subtarget is using thunks, we need to not generate jump tables.
31641   if (Subtarget.useIndirectThunkBranches())
31642     return false;
31643 
31644   // Otherwise, fallback on the generic logic.
31645   return TargetLowering::areJTsAllowed(Fn);
31646 }
31647 
31648 //===----------------------------------------------------------------------===//
31649 //                           X86 Scheduler Hooks
31650 //===----------------------------------------------------------------------===//
31651 
31652 // Returns true if EFLAG is consumed after this iterator in the rest of the
31653 // basic block or any successors of the basic block.
31654 static bool isEFLAGSLiveAfter(MachineBasicBlock::iterator Itr,
31655                               MachineBasicBlock *BB) {
31656   // Scan forward through BB for a use/def of EFLAGS.
31657   for (MachineBasicBlock::iterator miI = std::next(Itr), miE = BB->end();
31658          miI != miE; ++miI) {
31659     const MachineInstr& mi = *miI;
31660     if (mi.readsRegister(X86::EFLAGS))
31661       return true;
31662     // If we found a def, we can stop searching.
31663     if (mi.definesRegister(X86::EFLAGS))
31664       return false;
31665   }
31666 
31667   // If we hit the end of the block, check whether EFLAGS is live into a
31668   // successor.
31669   for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
31670                                         sEnd = BB->succ_end();
31671        sItr != sEnd; ++sItr) {
31672     MachineBasicBlock* succ = *sItr;
31673     if (succ->isLiveIn(X86::EFLAGS))
31674       return true;
31675   }
31676 
31677   return false;
31678 }
31679 
31680 /// Utility function to emit xbegin specifying the start of an RTM region.
31681 static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
31682                                      const TargetInstrInfo *TII) {
31683   const DebugLoc &DL = MI.getDebugLoc();
31684 
31685   const BasicBlock *BB = MBB->getBasicBlock();
31686   MachineFunction::iterator I = ++MBB->getIterator();
31687 
31688   // For the v = xbegin(), we generate
31689   //
31690   // thisMBB:
31691   //  xbegin sinkMBB
31692   //
31693   // mainMBB:
31694   //  s0 = -1
31695   //
31696   // fallBB:
31697   //  eax = # XABORT_DEF
31698   //  s1 = eax
31699   //
31700   // sinkMBB:
31701   //  v = phi(s0/mainBB, s1/fallBB)
31702 
31703   MachineBasicBlock *thisMBB = MBB;
31704   MachineFunction *MF = MBB->getParent();
31705   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
31706   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
31707   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
31708   MF->insert(I, mainMBB);
31709   MF->insert(I, fallMBB);
31710   MF->insert(I, sinkMBB);
31711 
31712   if (isEFLAGSLiveAfter(MI, MBB)) {
31713     mainMBB->addLiveIn(X86::EFLAGS);
31714     fallMBB->addLiveIn(X86::EFLAGS);
31715     sinkMBB->addLiveIn(X86::EFLAGS);
31716   }
31717 
31718   // Transfer the remainder of BB and its successor edges to sinkMBB.
31719   sinkMBB->splice(sinkMBB->begin(), MBB,
31720                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
31721   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
31722 
31723   MachineRegisterInfo &MRI = MF->getRegInfo();
31724   Register DstReg = MI.getOperand(0).getReg();
31725   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
31726   Register mainDstReg = MRI.createVirtualRegister(RC);
31727   Register fallDstReg = MRI.createVirtualRegister(RC);
31728 
31729   // thisMBB:
31730   //  xbegin fallMBB
31731   //  # fallthrough to mainMBB
31732   //  # abortion to fallMBB
31733   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
31734   thisMBB->addSuccessor(mainMBB);
31735   thisMBB->addSuccessor(fallMBB);
31736 
31737   // mainMBB:
31738   //  mainDstReg := -1
31739   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
31740   BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
31741   mainMBB->addSuccessor(sinkMBB);
31742 
31743   // fallMBB:
31744   //  ; pseudo instruction to model hardware's definition from XABORT
31745   //  EAX := XABORT_DEF
31746   //  fallDstReg := EAX
31747   BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
31748   BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
31749       .addReg(X86::EAX);
31750   fallMBB->addSuccessor(sinkMBB);
31751 
31752   // sinkMBB:
31753   //  DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
31754   BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
31755       .addReg(mainDstReg).addMBB(mainMBB)
31756       .addReg(fallDstReg).addMBB(fallMBB);
31757 
31758   MI.eraseFromParent();
31759   return sinkMBB;
31760 }
31761 
31762 MachineBasicBlock *
31763 X86TargetLowering::EmitVAARGWithCustomInserter(MachineInstr &MI,
31764                                                MachineBasicBlock *MBB) const {
31765   // Emit va_arg instruction on X86-64.
31766 
31767   // Operands to this pseudo-instruction:
31768   // 0  ) Output        : destination address (reg)
31769   // 1-5) Input         : va_list address (addr, i64mem)
31770   // 6  ) ArgSize       : Size (in bytes) of vararg type
31771   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
31772   // 8  ) Align         : Alignment of type
31773   // 9  ) EFLAGS (implicit-def)
31774 
31775   assert(MI.getNumOperands() == 10 && "VAARG should have 10 operands!");
31776   static_assert(X86::AddrNumOperands == 5, "VAARG assumes 5 address operands");
31777 
31778   Register DestReg = MI.getOperand(0).getReg();
31779   MachineOperand &Base = MI.getOperand(1);
31780   MachineOperand &Scale = MI.getOperand(2);
31781   MachineOperand &Index = MI.getOperand(3);
31782   MachineOperand &Disp = MI.getOperand(4);
31783   MachineOperand &Segment = MI.getOperand(5);
31784   unsigned ArgSize = MI.getOperand(6).getImm();
31785   unsigned ArgMode = MI.getOperand(7).getImm();
31786   Align Alignment = Align(MI.getOperand(8).getImm());
31787 
31788   MachineFunction *MF = MBB->getParent();
31789 
31790   // Memory Reference
31791   assert(MI.hasOneMemOperand() && "Expected VAARG to have one memoperand");
31792 
31793   MachineMemOperand *OldMMO = MI.memoperands().front();
31794 
31795   // Clone the MMO into two separate MMOs for loading and storing
31796   MachineMemOperand *LoadOnlyMMO = MF->getMachineMemOperand(
31797       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOStore);
31798   MachineMemOperand *StoreOnlyMMO = MF->getMachineMemOperand(
31799       OldMMO, OldMMO->getFlags() & ~MachineMemOperand::MOLoad);
31800 
31801   // Machine Information
31802   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
31803   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
31804   const TargetRegisterClass *AddrRegClass =
31805       getRegClassFor(getPointerTy(MBB->getParent()->getDataLayout()));
31806   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
31807   const DebugLoc &DL = MI.getDebugLoc();
31808 
31809   // struct va_list {
31810   //   i32   gp_offset
31811   //   i32   fp_offset
31812   //   i64   overflow_area (address)
31813   //   i64   reg_save_area (address)
31814   // }
31815   // sizeof(va_list) = 24
31816   // alignment(va_list) = 8
31817 
31818   unsigned TotalNumIntRegs = 6;
31819   unsigned TotalNumXMMRegs = 8;
31820   bool UseGPOffset = (ArgMode == 1);
31821   bool UseFPOffset = (ArgMode == 2);
31822   unsigned MaxOffset = TotalNumIntRegs * 8 +
31823                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
31824 
31825   /* Align ArgSize to a multiple of 8 */
31826   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
31827   bool NeedsAlign = (Alignment > 8);
31828 
31829   MachineBasicBlock *thisMBB = MBB;
31830   MachineBasicBlock *overflowMBB;
31831   MachineBasicBlock *offsetMBB;
31832   MachineBasicBlock *endMBB;
31833 
31834   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
31835   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
31836   unsigned OffsetReg = 0;
31837 
31838   if (!UseGPOffset && !UseFPOffset) {
31839     // If we only pull from the overflow region, we don't create a branch.
31840     // We don't need to alter control flow.
31841     OffsetDestReg = 0; // unused
31842     OverflowDestReg = DestReg;
31843 
31844     offsetMBB = nullptr;
31845     overflowMBB = thisMBB;
31846     endMBB = thisMBB;
31847   } else {
31848     // First emit code to check if gp_offset (or fp_offset) is below the bound.
31849     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
31850     // If not, pull from overflow_area. (branch to overflowMBB)
31851     //
31852     //       thisMBB
31853     //         |     .
31854     //         |        .
31855     //     offsetMBB   overflowMBB
31856     //         |        .
31857     //         |     .
31858     //        endMBB
31859 
31860     // Registers for the PHI in endMBB
31861     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
31862     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
31863 
31864     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
31865     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31866     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31867     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
31868 
31869     MachineFunction::iterator MBBIter = ++MBB->getIterator();
31870 
31871     // Insert the new basic blocks
31872     MF->insert(MBBIter, offsetMBB);
31873     MF->insert(MBBIter, overflowMBB);
31874     MF->insert(MBBIter, endMBB);
31875 
31876     // Transfer the remainder of MBB and its successor edges to endMBB.
31877     endMBB->splice(endMBB->begin(), thisMBB,
31878                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
31879     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
31880 
31881     // Make offsetMBB and overflowMBB successors of thisMBB
31882     thisMBB->addSuccessor(offsetMBB);
31883     thisMBB->addSuccessor(overflowMBB);
31884 
31885     // endMBB is a successor of both offsetMBB and overflowMBB
31886     offsetMBB->addSuccessor(endMBB);
31887     overflowMBB->addSuccessor(endMBB);
31888 
31889     // Load the offset value into a register
31890     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
31891     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
31892         .add(Base)
31893         .add(Scale)
31894         .add(Index)
31895         .addDisp(Disp, UseFPOffset ? 4 : 0)
31896         .add(Segment)
31897         .setMemRefs(LoadOnlyMMO);
31898 
31899     // Check if there is enough room left to pull this argument.
31900     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
31901       .addReg(OffsetReg)
31902       .addImm(MaxOffset + 8 - ArgSizeA8);
31903 
31904     // Branch to "overflowMBB" if offset >= max
31905     // Fall through to "offsetMBB" otherwise
31906     BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
31907       .addMBB(overflowMBB).addImm(X86::COND_AE);
31908   }
31909 
31910   // In offsetMBB, emit code to use the reg_save_area.
31911   if (offsetMBB) {
31912     assert(OffsetReg != 0);
31913 
31914     // Read the reg_save_area address.
31915     Register RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
31916     BuildMI(
31917         offsetMBB, DL,
31918         TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
31919         RegSaveReg)
31920         .add(Base)
31921         .add(Scale)
31922         .add(Index)
31923         .addDisp(Disp, Subtarget.isTarget64BitLP64() ? 16 : 12)
31924         .add(Segment)
31925         .setMemRefs(LoadOnlyMMO);
31926 
31927     if (Subtarget.isTarget64BitLP64()) {
31928       // Zero-extend the offset
31929       Register OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
31930       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
31931           .addImm(0)
31932           .addReg(OffsetReg)
31933           .addImm(X86::sub_32bit);
31934 
31935       // Add the offset to the reg_save_area to get the final address.
31936       BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
31937           .addReg(OffsetReg64)
31938           .addReg(RegSaveReg);
31939     } else {
31940       // Add the offset to the reg_save_area to get the final address.
31941       BuildMI(offsetMBB, DL, TII->get(X86::ADD32rr), OffsetDestReg)
31942           .addReg(OffsetReg)
31943           .addReg(RegSaveReg);
31944     }
31945 
31946     // Compute the offset for the next argument
31947     Register NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
31948     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
31949       .addReg(OffsetReg)
31950       .addImm(UseFPOffset ? 16 : 8);
31951 
31952     // Store it back into the va_list.
31953     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
31954         .add(Base)
31955         .add(Scale)
31956         .add(Index)
31957         .addDisp(Disp, UseFPOffset ? 4 : 0)
31958         .add(Segment)
31959         .addReg(NextOffsetReg)
31960         .setMemRefs(StoreOnlyMMO);
31961 
31962     // Jump to endMBB
31963     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
31964       .addMBB(endMBB);
31965   }
31966 
31967   //
31968   // Emit code to use overflow area
31969   //
31970 
31971   // Load the overflow_area address into a register.
31972   Register OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
31973   BuildMI(overflowMBB, DL,
31974           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64rm : X86::MOV32rm),
31975           OverflowAddrReg)
31976       .add(Base)
31977       .add(Scale)
31978       .add(Index)
31979       .addDisp(Disp, 8)
31980       .add(Segment)
31981       .setMemRefs(LoadOnlyMMO);
31982 
31983   // If we need to align it, do so. Otherwise, just copy the address
31984   // to OverflowDestReg.
31985   if (NeedsAlign) {
31986     // Align the overflow address
31987     Register TmpReg = MRI.createVirtualRegister(AddrRegClass);
31988 
31989     // aligned_addr = (addr + (align-1)) & ~(align-1)
31990     BuildMI(
31991         overflowMBB, DL,
31992         TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
31993         TmpReg)
31994         .addReg(OverflowAddrReg)
31995         .addImm(Alignment.value() - 1);
31996 
31997     BuildMI(
31998         overflowMBB, DL,
31999         TII->get(Subtarget.isTarget64BitLP64() ? X86::AND64ri32 : X86::AND32ri),
32000         OverflowDestReg)
32001         .addReg(TmpReg)
32002         .addImm(~(uint64_t)(Alignment.value() - 1));
32003   } else {
32004     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
32005       .addReg(OverflowAddrReg);
32006   }
32007 
32008   // Compute the next overflow address after this argument.
32009   // (the overflow address should be kept 8-byte aligned)
32010   Register NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
32011   BuildMI(
32012       overflowMBB, DL,
32013       TII->get(Subtarget.isTarget64BitLP64() ? X86::ADD64ri32 : X86::ADD32ri),
32014       NextAddrReg)
32015       .addReg(OverflowDestReg)
32016       .addImm(ArgSizeA8);
32017 
32018   // Store the new overflow address.
32019   BuildMI(overflowMBB, DL,
32020           TII->get(Subtarget.isTarget64BitLP64() ? X86::MOV64mr : X86::MOV32mr))
32021       .add(Base)
32022       .add(Scale)
32023       .add(Index)
32024       .addDisp(Disp, 8)
32025       .add(Segment)
32026       .addReg(NextAddrReg)
32027       .setMemRefs(StoreOnlyMMO);
32028 
32029   // If we branched, emit the PHI to the front of endMBB.
32030   if (offsetMBB) {
32031     BuildMI(*endMBB, endMBB->begin(), DL,
32032             TII->get(X86::PHI), DestReg)
32033       .addReg(OffsetDestReg).addMBB(offsetMBB)
32034       .addReg(OverflowDestReg).addMBB(overflowMBB);
32035   }
32036 
32037   // Erase the pseudo instruction
32038   MI.eraseFromParent();
32039 
32040   return endMBB;
32041 }
32042 
32043 MachineBasicBlock *X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
32044     MachineInstr &MI, MachineBasicBlock *MBB) const {
32045   // Emit code to save XMM registers to the stack. The ABI says that the
32046   // number of registers to save is given in %al, so it's theoretically
32047   // possible to do an indirect jump trick to avoid saving all of them,
32048   // however this code takes a simpler approach and just executes all
32049   // of the stores if %al is non-zero. It's less code, and it's probably
32050   // easier on the hardware branch predictor, and stores aren't all that
32051   // expensive anyway.
32052 
32053   // Create the new basic blocks. One block contains all the XMM stores,
32054   // and one block is the final destination regardless of whether any
32055   // stores were performed.
32056   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
32057   MachineFunction *F = MBB->getParent();
32058   MachineFunction::iterator MBBIter = ++MBB->getIterator();
32059   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
32060   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
32061   F->insert(MBBIter, XMMSaveMBB);
32062   F->insert(MBBIter, EndMBB);
32063 
32064   // Transfer the remainder of MBB and its successor edges to EndMBB.
32065   EndMBB->splice(EndMBB->begin(), MBB,
32066                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
32067   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
32068 
32069   // The original block will now fall through to the XMM save block.
32070   MBB->addSuccessor(XMMSaveMBB);
32071   // The XMMSaveMBB will fall through to the end block.
32072   XMMSaveMBB->addSuccessor(EndMBB);
32073 
32074   // Now add the instructions.
32075   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32076   const DebugLoc &DL = MI.getDebugLoc();
32077 
32078   Register CountReg = MI.getOperand(0).getReg();
32079   int RegSaveFrameIndex = MI.getOperand(1).getImm();
32080   int64_t VarArgsFPOffset = MI.getOperand(2).getImm();
32081 
32082   if (!Subtarget.isCallingConvWin64(F->getFunction().getCallingConv())) {
32083     // If %al is 0, branch around the XMM save block.
32084     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
32085     BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(EndMBB).addImm(X86::COND_E);
32086     MBB->addSuccessor(EndMBB);
32087   }
32088 
32089   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
32090   // that was just emitted, but clearly shouldn't be "saved".
32091   assert((MI.getNumOperands() <= 3 ||
32092           !MI.getOperand(MI.getNumOperands() - 1).isReg() ||
32093           MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) &&
32094          "Expected last argument to be EFLAGS");
32095   unsigned MOVOpc = Subtarget.hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
32096   // In the XMM save block, save all the XMM argument registers.
32097   for (int i = 3, e = MI.getNumOperands() - 1; i != e; ++i) {
32098     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
32099     MachineMemOperand *MMO = F->getMachineMemOperand(
32100         MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
32101         MachineMemOperand::MOStore,
32102         /*Size=*/16, Align(16));
32103     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
32104         .addFrameIndex(RegSaveFrameIndex)
32105         .addImm(/*Scale=*/1)
32106         .addReg(/*IndexReg=*/0)
32107         .addImm(/*Disp=*/Offset)
32108         .addReg(/*Segment=*/0)
32109         .addReg(MI.getOperand(i).getReg())
32110         .addMemOperand(MMO);
32111   }
32112 
32113   MI.eraseFromParent(); // The pseudo instruction is gone now.
32114 
32115   return EndMBB;
32116 }
32117 
32118 // The EFLAGS operand of SelectItr might be missing a kill marker
32119 // because there were multiple uses of EFLAGS, and ISel didn't know
32120 // which to mark. Figure out whether SelectItr should have had a
32121 // kill marker, and set it if it should. Returns the correct kill
32122 // marker value.
32123 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
32124                                      MachineBasicBlock* BB,
32125                                      const TargetRegisterInfo* TRI) {
32126   if (isEFLAGSLiveAfter(SelectItr, BB))
32127     return false;
32128 
32129   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
32130   // out. SelectMI should have a kill flag on EFLAGS.
32131   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
32132   return true;
32133 }
32134 
32135 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
32136 // together with other CMOV pseudo-opcodes into a single basic-block with
32137 // conditional jump around it.
32138 static bool isCMOVPseudo(MachineInstr &MI) {
32139   switch (MI.getOpcode()) {
32140   case X86::CMOV_FR32:
32141   case X86::CMOV_FR32X:
32142   case X86::CMOV_FR64:
32143   case X86::CMOV_FR64X:
32144   case X86::CMOV_GR8:
32145   case X86::CMOV_GR16:
32146   case X86::CMOV_GR32:
32147   case X86::CMOV_RFP32:
32148   case X86::CMOV_RFP64:
32149   case X86::CMOV_RFP80:
32150   case X86::CMOV_VR64:
32151   case X86::CMOV_VR128:
32152   case X86::CMOV_VR128X:
32153   case X86::CMOV_VR256:
32154   case X86::CMOV_VR256X:
32155   case X86::CMOV_VR512:
32156   case X86::CMOV_VK1:
32157   case X86::CMOV_VK2:
32158   case X86::CMOV_VK4:
32159   case X86::CMOV_VK8:
32160   case X86::CMOV_VK16:
32161   case X86::CMOV_VK32:
32162   case X86::CMOV_VK64:
32163     return true;
32164 
32165   default:
32166     return false;
32167   }
32168 }
32169 
32170 // Helper function, which inserts PHI functions into SinkMBB:
32171 //   %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
32172 // where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
32173 // in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
32174 // the last PHI function inserted.
32175 static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
32176     MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
32177     MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
32178     MachineBasicBlock *SinkMBB) {
32179   MachineFunction *MF = TrueMBB->getParent();
32180   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
32181   DebugLoc DL = MIItBegin->getDebugLoc();
32182 
32183   X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
32184   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
32185 
32186   MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
32187 
32188   // As we are creating the PHIs, we have to be careful if there is more than
32189   // one.  Later CMOVs may reference the results of earlier CMOVs, but later
32190   // PHIs have to reference the individual true/false inputs from earlier PHIs.
32191   // That also means that PHI construction must work forward from earlier to
32192   // later, and that the code must maintain a mapping from earlier PHI's
32193   // destination registers, and the registers that went into the PHI.
32194   DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
32195   MachineInstrBuilder MIB;
32196 
32197   for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
32198     Register DestReg = MIIt->getOperand(0).getReg();
32199     Register Op1Reg = MIIt->getOperand(1).getReg();
32200     Register Op2Reg = MIIt->getOperand(2).getReg();
32201 
32202     // If this CMOV we are generating is the opposite condition from
32203     // the jump we generated, then we have to swap the operands for the
32204     // PHI that is going to be generated.
32205     if (MIIt->getOperand(3).getImm() == OppCC)
32206       std::swap(Op1Reg, Op2Reg);
32207 
32208     if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
32209       Op1Reg = RegRewriteTable[Op1Reg].first;
32210 
32211     if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
32212       Op2Reg = RegRewriteTable[Op2Reg].second;
32213 
32214     MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
32215               .addReg(Op1Reg)
32216               .addMBB(FalseMBB)
32217               .addReg(Op2Reg)
32218               .addMBB(TrueMBB);
32219 
32220     // Add this PHI to the rewrite table.
32221     RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
32222   }
32223 
32224   return MIB;
32225 }
32226 
32227 // Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
32228 MachineBasicBlock *
32229 X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
32230                                              MachineInstr &SecondCascadedCMOV,
32231                                              MachineBasicBlock *ThisMBB) const {
32232   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32233   DebugLoc DL = FirstCMOV.getDebugLoc();
32234 
32235   // We lower cascaded CMOVs such as
32236   //
32237   //   (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
32238   //
32239   // to two successive branches.
32240   //
32241   // Without this, we would add a PHI between the two jumps, which ends up
32242   // creating a few copies all around. For instance, for
32243   //
32244   //    (sitofp (zext (fcmp une)))
32245   //
32246   // we would generate:
32247   //
32248   //         ucomiss %xmm1, %xmm0
32249   //         movss  <1.0f>, %xmm0
32250   //         movaps  %xmm0, %xmm1
32251   //         jne     .LBB5_2
32252   //         xorps   %xmm1, %xmm1
32253   // .LBB5_2:
32254   //         jp      .LBB5_4
32255   //         movaps  %xmm1, %xmm0
32256   // .LBB5_4:
32257   //         retq
32258   //
32259   // because this custom-inserter would have generated:
32260   //
32261   //   A
32262   //   | \
32263   //   |  B
32264   //   | /
32265   //   C
32266   //   | \
32267   //   |  D
32268   //   | /
32269   //   E
32270   //
32271   // A: X = ...; Y = ...
32272   // B: empty
32273   // C: Z = PHI [X, A], [Y, B]
32274   // D: empty
32275   // E: PHI [X, C], [Z, D]
32276   //
32277   // If we lower both CMOVs in a single step, we can instead generate:
32278   //
32279   //   A
32280   //   | \
32281   //   |  C
32282   //   | /|
32283   //   |/ |
32284   //   |  |
32285   //   |  D
32286   //   | /
32287   //   E
32288   //
32289   // A: X = ...; Y = ...
32290   // D: empty
32291   // E: PHI [X, A], [X, C], [Y, D]
32292   //
32293   // Which, in our sitofp/fcmp example, gives us something like:
32294   //
32295   //         ucomiss %xmm1, %xmm0
32296   //         movss  <1.0f>, %xmm0
32297   //         jne     .LBB5_4
32298   //         jp      .LBB5_4
32299   //         xorps   %xmm0, %xmm0
32300   // .LBB5_4:
32301   //         retq
32302   //
32303 
32304   // We lower cascaded CMOV into two successive branches to the same block.
32305   // EFLAGS is used by both, so mark it as live in the second.
32306   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
32307   MachineFunction *F = ThisMBB->getParent();
32308   MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
32309   MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
32310   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
32311 
32312   MachineFunction::iterator It = ++ThisMBB->getIterator();
32313   F->insert(It, FirstInsertedMBB);
32314   F->insert(It, SecondInsertedMBB);
32315   F->insert(It, SinkMBB);
32316 
32317   // For a cascaded CMOV, we lower it to two successive branches to
32318   // the same block (SinkMBB).  EFLAGS is used by both, so mark it as live in
32319   // the FirstInsertedMBB.
32320   FirstInsertedMBB->addLiveIn(X86::EFLAGS);
32321 
32322   // If the EFLAGS register isn't dead in the terminator, then claim that it's
32323   // live into the sink and copy blocks.
32324   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
32325   if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
32326       !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
32327     SecondInsertedMBB->addLiveIn(X86::EFLAGS);
32328     SinkMBB->addLiveIn(X86::EFLAGS);
32329   }
32330 
32331   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
32332   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
32333                   std::next(MachineBasicBlock::iterator(FirstCMOV)),
32334                   ThisMBB->end());
32335   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
32336 
32337   // Fallthrough block for ThisMBB.
32338   ThisMBB->addSuccessor(FirstInsertedMBB);
32339   // The true block target of the first branch is always SinkMBB.
32340   ThisMBB->addSuccessor(SinkMBB);
32341   // Fallthrough block for FirstInsertedMBB.
32342   FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
32343   // The true block for the branch of FirstInsertedMBB.
32344   FirstInsertedMBB->addSuccessor(SinkMBB);
32345   // This is fallthrough.
32346   SecondInsertedMBB->addSuccessor(SinkMBB);
32347 
32348   // Create the conditional branch instructions.
32349   X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
32350   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
32351 
32352   X86::CondCode SecondCC =
32353       X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
32354   BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
32355 
32356   //  SinkMBB:
32357   //   %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
32358   Register DestReg = FirstCMOV.getOperand(0).getReg();
32359   Register Op1Reg = FirstCMOV.getOperand(1).getReg();
32360   Register Op2Reg = FirstCMOV.getOperand(2).getReg();
32361   MachineInstrBuilder MIB =
32362       BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
32363           .addReg(Op1Reg)
32364           .addMBB(SecondInsertedMBB)
32365           .addReg(Op2Reg)
32366           .addMBB(ThisMBB);
32367 
32368   // The second SecondInsertedMBB provides the same incoming value as the
32369   // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
32370   MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
32371   // Copy the PHI result to the register defined by the second CMOV.
32372   BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
32373           TII->get(TargetOpcode::COPY),
32374           SecondCascadedCMOV.getOperand(0).getReg())
32375       .addReg(FirstCMOV.getOperand(0).getReg());
32376 
32377   // Now remove the CMOVs.
32378   FirstCMOV.eraseFromParent();
32379   SecondCascadedCMOV.eraseFromParent();
32380 
32381   return SinkMBB;
32382 }
32383 
32384 MachineBasicBlock *
32385 X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
32386                                      MachineBasicBlock *ThisMBB) const {
32387   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32388   const DebugLoc &DL = MI.getDebugLoc();
32389 
32390   // To "insert" a SELECT_CC instruction, we actually have to insert the
32391   // diamond control-flow pattern.  The incoming instruction knows the
32392   // destination vreg to set, the condition code register to branch on, the
32393   // true/false values to select between and a branch opcode to use.
32394 
32395   //  ThisMBB:
32396   //  ...
32397   //   TrueVal = ...
32398   //   cmpTY ccX, r1, r2
32399   //   bCC copy1MBB
32400   //   fallthrough --> FalseMBB
32401 
32402   // This code lowers all pseudo-CMOV instructions. Generally it lowers these
32403   // as described above, by inserting a BB, and then making a PHI at the join
32404   // point to select the true and false operands of the CMOV in the PHI.
32405   //
32406   // The code also handles two different cases of multiple CMOV opcodes
32407   // in a row.
32408   //
32409   // Case 1:
32410   // In this case, there are multiple CMOVs in a row, all which are based on
32411   // the same condition setting (or the exact opposite condition setting).
32412   // In this case we can lower all the CMOVs using a single inserted BB, and
32413   // then make a number of PHIs at the join point to model the CMOVs. The only
32414   // trickiness here, is that in a case like:
32415   //
32416   // t2 = CMOV cond1 t1, f1
32417   // t3 = CMOV cond1 t2, f2
32418   //
32419   // when rewriting this into PHIs, we have to perform some renaming on the
32420   // temps since you cannot have a PHI operand refer to a PHI result earlier
32421   // in the same block.  The "simple" but wrong lowering would be:
32422   //
32423   // t2 = PHI t1(BB1), f1(BB2)
32424   // t3 = PHI t2(BB1), f2(BB2)
32425   //
32426   // but clearly t2 is not defined in BB1, so that is incorrect. The proper
32427   // renaming is to note that on the path through BB1, t2 is really just a
32428   // copy of t1, and do that renaming, properly generating:
32429   //
32430   // t2 = PHI t1(BB1), f1(BB2)
32431   // t3 = PHI t1(BB1), f2(BB2)
32432   //
32433   // Case 2:
32434   // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
32435   // function - EmitLoweredCascadedSelect.
32436 
32437   X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
32438   X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
32439   MachineInstr *LastCMOV = &MI;
32440   MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
32441 
32442   // Check for case 1, where there are multiple CMOVs with the same condition
32443   // first.  Of the two cases of multiple CMOV lowerings, case 1 reduces the
32444   // number of jumps the most.
32445 
32446   if (isCMOVPseudo(MI)) {
32447     // See if we have a string of CMOVS with the same condition. Skip over
32448     // intervening debug insts.
32449     while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
32450            (NextMIIt->getOperand(3).getImm() == CC ||
32451             NextMIIt->getOperand(3).getImm() == OppCC)) {
32452       LastCMOV = &*NextMIIt;
32453       NextMIIt = next_nodbg(NextMIIt, ThisMBB->end());
32454     }
32455   }
32456 
32457   // This checks for case 2, but only do this if we didn't already find
32458   // case 1, as indicated by LastCMOV == MI.
32459   if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
32460       NextMIIt->getOpcode() == MI.getOpcode() &&
32461       NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
32462       NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
32463       NextMIIt->getOperand(1).isKill()) {
32464     return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
32465   }
32466 
32467   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
32468   MachineFunction *F = ThisMBB->getParent();
32469   MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
32470   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
32471 
32472   MachineFunction::iterator It = ++ThisMBB->getIterator();
32473   F->insert(It, FalseMBB);
32474   F->insert(It, SinkMBB);
32475 
32476   // If the EFLAGS register isn't dead in the terminator, then claim that it's
32477   // live into the sink and copy blocks.
32478   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
32479   if (!LastCMOV->killsRegister(X86::EFLAGS) &&
32480       !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
32481     FalseMBB->addLiveIn(X86::EFLAGS);
32482     SinkMBB->addLiveIn(X86::EFLAGS);
32483   }
32484 
32485   // Transfer any debug instructions inside the CMOV sequence to the sunk block.
32486   auto DbgEnd = MachineBasicBlock::iterator(LastCMOV);
32487   auto DbgIt = MachineBasicBlock::iterator(MI);
32488   while (DbgIt != DbgEnd) {
32489     auto Next = std::next(DbgIt);
32490     if (DbgIt->isDebugInstr())
32491       SinkMBB->push_back(DbgIt->removeFromParent());
32492     DbgIt = Next;
32493   }
32494 
32495   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
32496   SinkMBB->splice(SinkMBB->end(), ThisMBB,
32497                   std::next(MachineBasicBlock::iterator(LastCMOV)),
32498                   ThisMBB->end());
32499   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
32500 
32501   // Fallthrough block for ThisMBB.
32502   ThisMBB->addSuccessor(FalseMBB);
32503   // The true block target of the first (or only) branch is always a SinkMBB.
32504   ThisMBB->addSuccessor(SinkMBB);
32505   // Fallthrough block for FalseMBB.
32506   FalseMBB->addSuccessor(SinkMBB);
32507 
32508   // Create the conditional branch instruction.
32509   BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
32510 
32511   //  SinkMBB:
32512   //   %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
32513   //  ...
32514   MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
32515   MachineBasicBlock::iterator MIItEnd =
32516       std::next(MachineBasicBlock::iterator(LastCMOV));
32517   createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
32518 
32519   // Now remove the CMOV(s).
32520   ThisMBB->erase(MIItBegin, MIItEnd);
32521 
32522   return SinkMBB;
32523 }
32524 
32525 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
32526   if (IsLP64) {
32527     if (isInt<8>(Imm))
32528       return X86::SUB64ri8;
32529     return X86::SUB64ri32;
32530   } else {
32531     if (isInt<8>(Imm))
32532       return X86::SUB32ri8;
32533     return X86::SUB32ri;
32534   }
32535 }
32536 
32537 MachineBasicBlock *
32538 X86TargetLowering::EmitLoweredProbedAlloca(MachineInstr &MI,
32539                                            MachineBasicBlock *MBB) const {
32540   MachineFunction *MF = MBB->getParent();
32541   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32542   const X86FrameLowering &TFI = *Subtarget.getFrameLowering();
32543   const DebugLoc &DL = MI.getDebugLoc();
32544   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
32545 
32546   const unsigned ProbeSize = getStackProbeSize(*MF);
32547 
32548   MachineRegisterInfo &MRI = MF->getRegInfo();
32549   MachineBasicBlock *testMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32550   MachineBasicBlock *tailMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32551   MachineBasicBlock *blockMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32552 
32553   MachineFunction::iterator MBBIter = ++MBB->getIterator();
32554   MF->insert(MBBIter, testMBB);
32555   MF->insert(MBBIter, blockMBB);
32556   MF->insert(MBBIter, tailMBB);
32557 
32558   Register sizeVReg = MI.getOperand(1).getReg();
32559 
32560   Register physSPReg = TFI.Uses64BitFramePtr ? X86::RSP : X86::ESP;
32561 
32562   Register TmpStackPtr = MRI.createVirtualRegister(
32563       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
32564   Register FinalStackPtr = MRI.createVirtualRegister(
32565       TFI.Uses64BitFramePtr ? &X86::GR64RegClass : &X86::GR32RegClass);
32566 
32567   BuildMI(*MBB, {MI}, DL, TII->get(TargetOpcode::COPY), TmpStackPtr)
32568       .addReg(physSPReg);
32569   {
32570     const unsigned Opc = TFI.Uses64BitFramePtr ? X86::SUB64rr : X86::SUB32rr;
32571     BuildMI(*MBB, {MI}, DL, TII->get(Opc), FinalStackPtr)
32572         .addReg(TmpStackPtr)
32573         .addReg(sizeVReg);
32574   }
32575 
32576   // test rsp size
32577 
32578   BuildMI(testMBB, DL,
32579           TII->get(TFI.Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
32580       .addReg(FinalStackPtr)
32581       .addReg(physSPReg);
32582 
32583   BuildMI(testMBB, DL, TII->get(X86::JCC_1))
32584       .addMBB(tailMBB)
32585       .addImm(X86::COND_GE);
32586   testMBB->addSuccessor(blockMBB);
32587   testMBB->addSuccessor(tailMBB);
32588 
32589   // Touch the block then extend it. This is done on the opposite side of
32590   // static probe where we allocate then touch, to avoid the need of probing the
32591   // tail of the static alloca. Possible scenarios are:
32592   //
32593   //       + ---- <- ------------ <- ------------- <- ------------ +
32594   //       |                                                       |
32595   // [free probe] -> [page alloc] -> [alloc probe] -> [tail alloc] + -> [dyn probe] -> [page alloc] -> [dyn probe] -> [tail alloc] +
32596   //                                                               |                                                               |
32597   //                                                               + <- ----------- <- ------------ <- ----------- <- ------------ +
32598   //
32599   // The property we want to enforce is to never have more than [page alloc] between two probes.
32600 
32601   const unsigned XORMIOpc =
32602       TFI.Uses64BitFramePtr ? X86::XOR64mi8 : X86::XOR32mi8;
32603   addRegOffset(BuildMI(blockMBB, DL, TII->get(XORMIOpc)), physSPReg, false, 0)
32604       .addImm(0);
32605 
32606   BuildMI(blockMBB, DL,
32607           TII->get(getSUBriOpcode(TFI.Uses64BitFramePtr, ProbeSize)), physSPReg)
32608       .addReg(physSPReg)
32609       .addImm(ProbeSize);
32610 
32611 
32612   BuildMI(blockMBB, DL, TII->get(X86::JMP_1)).addMBB(testMBB);
32613   blockMBB->addSuccessor(testMBB);
32614 
32615   // Replace original instruction by the expected stack ptr
32616   BuildMI(tailMBB, DL, TII->get(TargetOpcode::COPY), MI.getOperand(0).getReg())
32617       .addReg(FinalStackPtr);
32618 
32619   tailMBB->splice(tailMBB->end(), MBB,
32620                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
32621   tailMBB->transferSuccessorsAndUpdatePHIs(MBB);
32622   MBB->addSuccessor(testMBB);
32623 
32624   // Delete the original pseudo instruction.
32625   MI.eraseFromParent();
32626 
32627   // And we're done.
32628   return tailMBB;
32629 }
32630 
32631 MachineBasicBlock *
32632 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
32633                                         MachineBasicBlock *BB) const {
32634   MachineFunction *MF = BB->getParent();
32635   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
32636   const DebugLoc &DL = MI.getDebugLoc();
32637   const BasicBlock *LLVM_BB = BB->getBasicBlock();
32638 
32639   assert(MF->shouldSplitStack());
32640 
32641   const bool Is64Bit = Subtarget.is64Bit();
32642   const bool IsLP64 = Subtarget.isTarget64BitLP64();
32643 
32644   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
32645   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
32646 
32647   // BB:
32648   //  ... [Till the alloca]
32649   // If stacklet is not large enough, jump to mallocMBB
32650   //
32651   // bumpMBB:
32652   //  Allocate by subtracting from RSP
32653   //  Jump to continueMBB
32654   //
32655   // mallocMBB:
32656   //  Allocate by call to runtime
32657   //
32658   // continueMBB:
32659   //  ...
32660   //  [rest of original BB]
32661   //
32662 
32663   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32664   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32665   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
32666 
32667   MachineRegisterInfo &MRI = MF->getRegInfo();
32668   const TargetRegisterClass *AddrRegClass =
32669       getRegClassFor(getPointerTy(MF->getDataLayout()));
32670 
32671   Register mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
32672            bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
32673            tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
32674            SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
32675            sizeVReg = MI.getOperand(1).getReg(),
32676            physSPReg =
32677                IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
32678 
32679   MachineFunction::iterator MBBIter = ++BB->getIterator();
32680 
32681   MF->insert(MBBIter, bumpMBB);
32682   MF->insert(MBBIter, mallocMBB);
32683   MF->insert(MBBIter, continueMBB);
32684 
32685   continueMBB->splice(continueMBB->begin(), BB,
32686                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
32687   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
32688 
32689   // Add code to the main basic block to check if the stack limit has been hit,
32690   // and if so, jump to mallocMBB otherwise to bumpMBB.
32691   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
32692   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
32693     .addReg(tmpSPVReg).addReg(sizeVReg);
32694   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
32695     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
32696     .addReg(SPLimitVReg);
32697   BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
32698 
32699   // bumpMBB simply decreases the stack pointer, since we know the current
32700   // stacklet has enough space.
32701   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
32702     .addReg(SPLimitVReg);
32703   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
32704     .addReg(SPLimitVReg);
32705   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
32706 
32707   // Calls into a routine in libgcc to allocate more space from the heap.
32708   const uint32_t *RegMask =
32709       Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
32710   if (IsLP64) {
32711     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
32712       .addReg(sizeVReg);
32713     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
32714       .addExternalSymbol("__morestack_allocate_stack_space")
32715       .addRegMask(RegMask)
32716       .addReg(X86::RDI, RegState::Implicit)
32717       .addReg(X86::RAX, RegState::ImplicitDefine);
32718   } else if (Is64Bit) {
32719     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
32720       .addReg(sizeVReg);
32721     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
32722       .addExternalSymbol("__morestack_allocate_stack_space")
32723       .addRegMask(RegMask)
32724       .addReg(X86::EDI, RegState::Implicit)
32725       .addReg(X86::EAX, RegState::ImplicitDefine);
32726   } else {
32727     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
32728       .addImm(12);
32729     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
32730     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
32731       .addExternalSymbol("__morestack_allocate_stack_space")
32732       .addRegMask(RegMask)
32733       .addReg(X86::EAX, RegState::ImplicitDefine);
32734   }
32735 
32736   if (!Is64Bit)
32737     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
32738       .addImm(16);
32739 
32740   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
32741     .addReg(IsLP64 ? X86::RAX : X86::EAX);
32742   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
32743 
32744   // Set up the CFG correctly.
32745   BB->addSuccessor(bumpMBB);
32746   BB->addSuccessor(mallocMBB);
32747   mallocMBB->addSuccessor(continueMBB);
32748   bumpMBB->addSuccessor(continueMBB);
32749 
32750   // Take care of the PHI nodes.
32751   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
32752           MI.getOperand(0).getReg())
32753       .addReg(mallocPtrVReg)
32754       .addMBB(mallocMBB)
32755       .addReg(bumpSPPtrVReg)
32756       .addMBB(bumpMBB);
32757 
32758   // Delete the original pseudo instruction.
32759   MI.eraseFromParent();
32760 
32761   // And we're done.
32762   return continueMBB;
32763 }
32764 
32765 MachineBasicBlock *
32766 X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
32767                                        MachineBasicBlock *BB) const {
32768   MachineFunction *MF = BB->getParent();
32769   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
32770   MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
32771   const DebugLoc &DL = MI.getDebugLoc();
32772 
32773   assert(!isAsynchronousEHPersonality(
32774              classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&
32775          "SEH does not use catchret!");
32776 
32777   // Only 32-bit EH needs to worry about manually restoring stack pointers.
32778   if (!Subtarget.is32Bit())
32779     return BB;
32780 
32781   // C++ EH creates a new target block to hold the restore code, and wires up
32782   // the new block to the return destination with a normal JMP_4.
32783   MachineBasicBlock *RestoreMBB =
32784       MF->CreateMachineBasicBlock(BB->getBasicBlock());
32785   assert(BB->succ_size() == 1);
32786   MF->insert(std::next(BB->getIterator()), RestoreMBB);
32787   RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
32788   BB->addSuccessor(RestoreMBB);
32789   MI.getOperand(0).setMBB(RestoreMBB);
32790 
32791   // Marking this as an EH pad but not a funclet entry block causes PEI to
32792   // restore stack pointers in the block.
32793   RestoreMBB->setIsEHPad(true);
32794 
32795   auto RestoreMBBI = RestoreMBB->begin();
32796   BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
32797   return BB;
32798 }
32799 
32800 MachineBasicBlock *
32801 X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
32802                                       MachineBasicBlock *BB) const {
32803   // So, here we replace TLSADDR with the sequence:
32804   // adjust_stackdown -> TLSADDR -> adjust_stackup.
32805   // We need this because TLSADDR is lowered into calls
32806   // inside MC, therefore without the two markers shrink-wrapping
32807   // may push the prologue/epilogue pass them.
32808   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
32809   const DebugLoc &DL = MI.getDebugLoc();
32810   MachineFunction &MF = *BB->getParent();
32811 
32812   // Emit CALLSEQ_START right before the instruction.
32813   unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
32814   MachineInstrBuilder CallseqStart =
32815     BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
32816   BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
32817 
32818   // Emit CALLSEQ_END right after the instruction.
32819   // We don't call erase from parent because we want to keep the
32820   // original instruction around.
32821   unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
32822   MachineInstrBuilder CallseqEnd =
32823     BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
32824   BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
32825 
32826   return BB;
32827 }
32828 
32829 MachineBasicBlock *
32830 X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
32831                                       MachineBasicBlock *BB) const {
32832   // This is pretty easy.  We're taking the value that we received from
32833   // our load from the relocation, sticking it in either RDI (x86-64)
32834   // or EAX and doing an indirect call.  The return value will then
32835   // be in the normal return register.
32836   MachineFunction *F = BB->getParent();
32837   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32838   const DebugLoc &DL = MI.getDebugLoc();
32839 
32840   assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?");
32841   assert(MI.getOperand(3).isGlobal() && "This should be a global");
32842 
32843   // Get a register mask for the lowered call.
32844   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
32845   // proper register mask.
32846   const uint32_t *RegMask =
32847       Subtarget.is64Bit() ?
32848       Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
32849       Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
32850   if (Subtarget.is64Bit()) {
32851     MachineInstrBuilder MIB =
32852         BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
32853             .addReg(X86::RIP)
32854             .addImm(0)
32855             .addReg(0)
32856             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
32857                               MI.getOperand(3).getTargetFlags())
32858             .addReg(0);
32859     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
32860     addDirectMem(MIB, X86::RDI);
32861     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
32862   } else if (!isPositionIndependent()) {
32863     MachineInstrBuilder MIB =
32864         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
32865             .addReg(0)
32866             .addImm(0)
32867             .addReg(0)
32868             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
32869                               MI.getOperand(3).getTargetFlags())
32870             .addReg(0);
32871     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
32872     addDirectMem(MIB, X86::EAX);
32873     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
32874   } else {
32875     MachineInstrBuilder MIB =
32876         BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
32877             .addReg(TII->getGlobalBaseReg(F))
32878             .addImm(0)
32879             .addReg(0)
32880             .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
32881                               MI.getOperand(3).getTargetFlags())
32882             .addReg(0);
32883     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
32884     addDirectMem(MIB, X86::EAX);
32885     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
32886   }
32887 
32888   MI.eraseFromParent(); // The pseudo instruction is gone now.
32889   return BB;
32890 }
32891 
32892 static unsigned getOpcodeForIndirectThunk(unsigned RPOpc) {
32893   switch (RPOpc) {
32894   case X86::INDIRECT_THUNK_CALL32:
32895     return X86::CALLpcrel32;
32896   case X86::INDIRECT_THUNK_CALL64:
32897     return X86::CALL64pcrel32;
32898   case X86::INDIRECT_THUNK_TCRETURN32:
32899     return X86::TCRETURNdi;
32900   case X86::INDIRECT_THUNK_TCRETURN64:
32901     return X86::TCRETURNdi64;
32902   }
32903   llvm_unreachable("not indirect thunk opcode");
32904 }
32905 
32906 static const char *getIndirectThunkSymbol(const X86Subtarget &Subtarget,
32907                                           unsigned Reg) {
32908   if (Subtarget.useRetpolineExternalThunk()) {
32909     // When using an external thunk for retpolines, we pick names that match the
32910     // names GCC happens to use as well. This helps simplify the implementation
32911     // of the thunks for kernels where they have no easy ability to create
32912     // aliases and are doing non-trivial configuration of the thunk's body. For
32913     // example, the Linux kernel will do boot-time hot patching of the thunk
32914     // bodies and cannot easily export aliases of these to loaded modules.
32915     //
32916     // Note that at any point in the future, we may need to change the semantics
32917     // of how we implement retpolines and at that time will likely change the
32918     // name of the called thunk. Essentially, there is no hard guarantee that
32919     // LLVM will generate calls to specific thunks, we merely make a best-effort
32920     // attempt to help out kernels and other systems where duplicating the
32921     // thunks is costly.
32922     switch (Reg) {
32923     case X86::EAX:
32924       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32925       return "__x86_indirect_thunk_eax";
32926     case X86::ECX:
32927       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32928       return "__x86_indirect_thunk_ecx";
32929     case X86::EDX:
32930       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32931       return "__x86_indirect_thunk_edx";
32932     case X86::EDI:
32933       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32934       return "__x86_indirect_thunk_edi";
32935     case X86::R11:
32936       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
32937       return "__x86_indirect_thunk_r11";
32938     }
32939     llvm_unreachable("unexpected reg for external indirect thunk");
32940   }
32941 
32942   if (Subtarget.useRetpolineIndirectCalls() ||
32943       Subtarget.useRetpolineIndirectBranches()) {
32944     // When targeting an internal COMDAT thunk use an LLVM-specific name.
32945     switch (Reg) {
32946     case X86::EAX:
32947       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32948       return "__llvm_retpoline_eax";
32949     case X86::ECX:
32950       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32951       return "__llvm_retpoline_ecx";
32952     case X86::EDX:
32953       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32954       return "__llvm_retpoline_edx";
32955     case X86::EDI:
32956       assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!");
32957       return "__llvm_retpoline_edi";
32958     case X86::R11:
32959       assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
32960       return "__llvm_retpoline_r11";
32961     }
32962     llvm_unreachable("unexpected reg for retpoline");
32963   }
32964 
32965   if (Subtarget.useLVIControlFlowIntegrity()) {
32966     assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!");
32967     return "__llvm_lvi_thunk_r11";
32968   }
32969   llvm_unreachable("getIndirectThunkSymbol() invoked without thunk feature");
32970 }
32971 
32972 MachineBasicBlock *
32973 X86TargetLowering::EmitLoweredIndirectThunk(MachineInstr &MI,
32974                                             MachineBasicBlock *BB) const {
32975   // Copy the virtual register into the R11 physical register and
32976   // call the retpoline thunk.
32977   const DebugLoc &DL = MI.getDebugLoc();
32978   const X86InstrInfo *TII = Subtarget.getInstrInfo();
32979   Register CalleeVReg = MI.getOperand(0).getReg();
32980   unsigned Opc = getOpcodeForIndirectThunk(MI.getOpcode());
32981 
32982   // Find an available scratch register to hold the callee. On 64-bit, we can
32983   // just use R11, but we scan for uses anyway to ensure we don't generate
32984   // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
32985   // already a register use operand to the call to hold the callee. If none
32986   // are available, use EDI instead. EDI is chosen because EBX is the PIC base
32987   // register and ESI is the base pointer to realigned stack frames with VLAs.
32988   SmallVector<unsigned, 3> AvailableRegs;
32989   if (Subtarget.is64Bit())
32990     AvailableRegs.push_back(X86::R11);
32991   else
32992     AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
32993 
32994   // Zero out any registers that are already used.
32995   for (const auto &MO : MI.operands()) {
32996     if (MO.isReg() && MO.isUse())
32997       for (unsigned &Reg : AvailableRegs)
32998         if (Reg == MO.getReg())
32999           Reg = 0;
33000   }
33001 
33002   // Choose the first remaining non-zero available register.
33003   unsigned AvailableReg = 0;
33004   for (unsigned MaybeReg : AvailableRegs) {
33005     if (MaybeReg) {
33006       AvailableReg = MaybeReg;
33007       break;
33008     }
33009   }
33010   if (!AvailableReg)
33011     report_fatal_error("calling convention incompatible with retpoline, no "
33012                        "available registers");
33013 
33014   const char *Symbol = getIndirectThunkSymbol(Subtarget, AvailableReg);
33015 
33016   BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
33017       .addReg(CalleeVReg);
33018   MI.getOperand(0).ChangeToES(Symbol);
33019   MI.setDesc(TII->get(Opc));
33020   MachineInstrBuilder(*BB->getParent(), &MI)
33021       .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
33022   return BB;
33023 }
33024 
33025 /// SetJmp implies future control flow change upon calling the corresponding
33026 /// LongJmp.
33027 /// Instead of using the 'return' instruction, the long jump fixes the stack and
33028 /// performs an indirect branch. To do so it uses the registers that were stored
33029 /// in the jump buffer (when calling SetJmp).
33030 /// In case the shadow stack is enabled we need to fix it as well, because some
33031 /// return addresses will be skipped.
33032 /// The function will save the SSP for future fixing in the function
33033 /// emitLongJmpShadowStackFix.
33034 /// \sa emitLongJmpShadowStackFix
33035 /// \param [in] MI The temporary Machine Instruction for the builtin.
33036 /// \param [in] MBB The Machine Basic Block that will be modified.
33037 void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
33038                                                  MachineBasicBlock *MBB) const {
33039   const DebugLoc &DL = MI.getDebugLoc();
33040   MachineFunction *MF = MBB->getParent();
33041   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33042   MachineRegisterInfo &MRI = MF->getRegInfo();
33043   MachineInstrBuilder MIB;
33044 
33045   // Memory Reference.
33046   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33047                                            MI.memoperands_end());
33048 
33049   // Initialize a register with zero.
33050   MVT PVT = getPointerTy(MF->getDataLayout());
33051   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
33052   Register ZReg = MRI.createVirtualRegister(PtrRC);
33053   unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
33054   BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
33055       .addDef(ZReg)
33056       .addReg(ZReg, RegState::Undef)
33057       .addReg(ZReg, RegState::Undef);
33058 
33059   // Read the current SSP Register value to the zeroed register.
33060   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
33061   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
33062   BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
33063 
33064   // Write the SSP register value to offset 3 in input memory buffer.
33065   unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
33066   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
33067   const int64_t SSPOffset = 3 * PVT.getStoreSize();
33068   const unsigned MemOpndSlot = 1;
33069   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33070     if (i == X86::AddrDisp)
33071       MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
33072     else
33073       MIB.add(MI.getOperand(MemOpndSlot + i));
33074   }
33075   MIB.addReg(SSPCopyReg);
33076   MIB.setMemRefs(MMOs);
33077 }
33078 
33079 MachineBasicBlock *
33080 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
33081                                     MachineBasicBlock *MBB) const {
33082   const DebugLoc &DL = MI.getDebugLoc();
33083   MachineFunction *MF = MBB->getParent();
33084   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33085   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
33086   MachineRegisterInfo &MRI = MF->getRegInfo();
33087 
33088   const BasicBlock *BB = MBB->getBasicBlock();
33089   MachineFunction::iterator I = ++MBB->getIterator();
33090 
33091   // Memory Reference
33092   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33093                                            MI.memoperands_end());
33094 
33095   unsigned DstReg;
33096   unsigned MemOpndSlot = 0;
33097 
33098   unsigned CurOp = 0;
33099 
33100   DstReg = MI.getOperand(CurOp++).getReg();
33101   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
33102   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
33103   (void)TRI;
33104   Register mainDstReg = MRI.createVirtualRegister(RC);
33105   Register restoreDstReg = MRI.createVirtualRegister(RC);
33106 
33107   MemOpndSlot = CurOp;
33108 
33109   MVT PVT = getPointerTy(MF->getDataLayout());
33110   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
33111          "Invalid Pointer Size!");
33112 
33113   // For v = setjmp(buf), we generate
33114   //
33115   // thisMBB:
33116   //  buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
33117   //  SjLjSetup restoreMBB
33118   //
33119   // mainMBB:
33120   //  v_main = 0
33121   //
33122   // sinkMBB:
33123   //  v = phi(main, restore)
33124   //
33125   // restoreMBB:
33126   //  if base pointer being used, load it from frame
33127   //  v_restore = 1
33128 
33129   MachineBasicBlock *thisMBB = MBB;
33130   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
33131   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
33132   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
33133   MF->insert(I, mainMBB);
33134   MF->insert(I, sinkMBB);
33135   MF->push_back(restoreMBB);
33136   restoreMBB->setHasAddressTaken();
33137 
33138   MachineInstrBuilder MIB;
33139 
33140   // Transfer the remainder of BB and its successor edges to sinkMBB.
33141   sinkMBB->splice(sinkMBB->begin(), MBB,
33142                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
33143   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
33144 
33145   // thisMBB:
33146   unsigned PtrStoreOpc = 0;
33147   unsigned LabelReg = 0;
33148   const int64_t LabelOffset = 1 * PVT.getStoreSize();
33149   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
33150                      !isPositionIndependent();
33151 
33152   // Prepare IP either in reg or imm.
33153   if (!UseImmLabel) {
33154     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
33155     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
33156     LabelReg = MRI.createVirtualRegister(PtrRC);
33157     if (Subtarget.is64Bit()) {
33158       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
33159               .addReg(X86::RIP)
33160               .addImm(0)
33161               .addReg(0)
33162               .addMBB(restoreMBB)
33163               .addReg(0);
33164     } else {
33165       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
33166       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
33167               .addReg(XII->getGlobalBaseReg(MF))
33168               .addImm(0)
33169               .addReg(0)
33170               .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
33171               .addReg(0);
33172     }
33173   } else
33174     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
33175   // Store IP
33176   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
33177   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33178     if (i == X86::AddrDisp)
33179       MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
33180     else
33181       MIB.add(MI.getOperand(MemOpndSlot + i));
33182   }
33183   if (!UseImmLabel)
33184     MIB.addReg(LabelReg);
33185   else
33186     MIB.addMBB(restoreMBB);
33187   MIB.setMemRefs(MMOs);
33188 
33189   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
33190     emitSetJmpShadowStackFix(MI, thisMBB);
33191   }
33192 
33193   // Setup
33194   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
33195           .addMBB(restoreMBB);
33196 
33197   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
33198   MIB.addRegMask(RegInfo->getNoPreservedMask());
33199   thisMBB->addSuccessor(mainMBB);
33200   thisMBB->addSuccessor(restoreMBB);
33201 
33202   // mainMBB:
33203   //  EAX = 0
33204   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
33205   mainMBB->addSuccessor(sinkMBB);
33206 
33207   // sinkMBB:
33208   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
33209           TII->get(X86::PHI), DstReg)
33210     .addReg(mainDstReg).addMBB(mainMBB)
33211     .addReg(restoreDstReg).addMBB(restoreMBB);
33212 
33213   // restoreMBB:
33214   if (RegInfo->hasBasePointer(*MF)) {
33215     const bool Uses64BitFramePtr =
33216         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
33217     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
33218     X86FI->setRestoreBasePointer(MF);
33219     Register FramePtr = RegInfo->getFrameRegister(*MF);
33220     Register BasePtr = RegInfo->getBaseRegister();
33221     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
33222     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
33223                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
33224       .setMIFlag(MachineInstr::FrameSetup);
33225   }
33226   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
33227   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
33228   restoreMBB->addSuccessor(sinkMBB);
33229 
33230   MI.eraseFromParent();
33231   return sinkMBB;
33232 }
33233 
33234 /// Fix the shadow stack using the previously saved SSP pointer.
33235 /// \sa emitSetJmpShadowStackFix
33236 /// \param [in] MI The temporary Machine Instruction for the builtin.
33237 /// \param [in] MBB The Machine Basic Block that will be modified.
33238 /// \return The sink MBB that will perform the future indirect branch.
33239 MachineBasicBlock *
33240 X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
33241                                              MachineBasicBlock *MBB) const {
33242   const DebugLoc &DL = MI.getDebugLoc();
33243   MachineFunction *MF = MBB->getParent();
33244   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33245   MachineRegisterInfo &MRI = MF->getRegInfo();
33246 
33247   // Memory Reference
33248   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33249                                            MI.memoperands_end());
33250 
33251   MVT PVT = getPointerTy(MF->getDataLayout());
33252   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
33253 
33254   // checkSspMBB:
33255   //         xor vreg1, vreg1
33256   //         rdssp vreg1
33257   //         test vreg1, vreg1
33258   //         je sinkMBB   # Jump if Shadow Stack is not supported
33259   // fallMBB:
33260   //         mov buf+24/12(%rip), vreg2
33261   //         sub vreg1, vreg2
33262   //         jbe sinkMBB  # No need to fix the Shadow Stack
33263   // fixShadowMBB:
33264   //         shr 3/2, vreg2
33265   //         incssp vreg2  # fix the SSP according to the lower 8 bits
33266   //         shr 8, vreg2
33267   //         je sinkMBB
33268   // fixShadowLoopPrepareMBB:
33269   //         shl vreg2
33270   //         mov 128, vreg3
33271   // fixShadowLoopMBB:
33272   //         incssp vreg3
33273   //         dec vreg2
33274   //         jne fixShadowLoopMBB # Iterate until you finish fixing
33275   //                              # the Shadow Stack
33276   // sinkMBB:
33277 
33278   MachineFunction::iterator I = ++MBB->getIterator();
33279   const BasicBlock *BB = MBB->getBasicBlock();
33280 
33281   MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
33282   MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
33283   MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
33284   MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
33285   MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
33286   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
33287   MF->insert(I, checkSspMBB);
33288   MF->insert(I, fallMBB);
33289   MF->insert(I, fixShadowMBB);
33290   MF->insert(I, fixShadowLoopPrepareMBB);
33291   MF->insert(I, fixShadowLoopMBB);
33292   MF->insert(I, sinkMBB);
33293 
33294   // Transfer the remainder of BB and its successor edges to sinkMBB.
33295   sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
33296                   MBB->end());
33297   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
33298 
33299   MBB->addSuccessor(checkSspMBB);
33300 
33301   // Initialize a register with zero.
33302   Register ZReg = MRI.createVirtualRegister(&X86::GR32RegClass);
33303   BuildMI(checkSspMBB, DL, TII->get(X86::MOV32r0), ZReg);
33304 
33305   if (PVT == MVT::i64) {
33306     Register TmpZReg = MRI.createVirtualRegister(PtrRC);
33307     BuildMI(checkSspMBB, DL, TII->get(X86::SUBREG_TO_REG), TmpZReg)
33308       .addImm(0)
33309       .addReg(ZReg)
33310       .addImm(X86::sub_32bit);
33311     ZReg = TmpZReg;
33312   }
33313 
33314   // Read the current SSP Register value to the zeroed register.
33315   Register SSPCopyReg = MRI.createVirtualRegister(PtrRC);
33316   unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
33317   BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
33318 
33319   // Check whether the result of the SSP register is zero and jump directly
33320   // to the sink.
33321   unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
33322   BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
33323       .addReg(SSPCopyReg)
33324       .addReg(SSPCopyReg);
33325   BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
33326   checkSspMBB->addSuccessor(sinkMBB);
33327   checkSspMBB->addSuccessor(fallMBB);
33328 
33329   // Reload the previously saved SSP register value.
33330   Register PrevSSPReg = MRI.createVirtualRegister(PtrRC);
33331   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
33332   const int64_t SPPOffset = 3 * PVT.getStoreSize();
33333   MachineInstrBuilder MIB =
33334       BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
33335   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33336     const MachineOperand &MO = MI.getOperand(i);
33337     if (i == X86::AddrDisp)
33338       MIB.addDisp(MO, SPPOffset);
33339     else if (MO.isReg()) // Don't add the whole operand, we don't want to
33340                          // preserve kill flags.
33341       MIB.addReg(MO.getReg());
33342     else
33343       MIB.add(MO);
33344   }
33345   MIB.setMemRefs(MMOs);
33346 
33347   // Subtract the current SSP from the previous SSP.
33348   Register SspSubReg = MRI.createVirtualRegister(PtrRC);
33349   unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
33350   BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
33351       .addReg(PrevSSPReg)
33352       .addReg(SSPCopyReg);
33353 
33354   // Jump to sink in case PrevSSPReg <= SSPCopyReg.
33355   BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
33356   fallMBB->addSuccessor(sinkMBB);
33357   fallMBB->addSuccessor(fixShadowMBB);
33358 
33359   // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
33360   unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
33361   unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
33362   Register SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
33363   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
33364       .addReg(SspSubReg)
33365       .addImm(Offset);
33366 
33367   // Increase SSP when looking only on the lower 8 bits of the delta.
33368   unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
33369   BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
33370 
33371   // Reset the lower 8 bits.
33372   Register SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
33373   BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
33374       .addReg(SspFirstShrReg)
33375       .addImm(8);
33376 
33377   // Jump if the result of the shift is zero.
33378   BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
33379   fixShadowMBB->addSuccessor(sinkMBB);
33380   fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
33381 
33382   // Do a single shift left.
33383   unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
33384   Register SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
33385   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
33386       .addReg(SspSecondShrReg);
33387 
33388   // Save the value 128 to a register (will be used next with incssp).
33389   Register Value128InReg = MRI.createVirtualRegister(PtrRC);
33390   unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
33391   BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
33392       .addImm(128);
33393   fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
33394 
33395   // Since incssp only looks at the lower 8 bits, we might need to do several
33396   // iterations of incssp until we finish fixing the shadow stack.
33397   Register DecReg = MRI.createVirtualRegister(PtrRC);
33398   Register CounterReg = MRI.createVirtualRegister(PtrRC);
33399   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
33400       .addReg(SspAfterShlReg)
33401       .addMBB(fixShadowLoopPrepareMBB)
33402       .addReg(DecReg)
33403       .addMBB(fixShadowLoopMBB);
33404 
33405   // Every iteration we increase the SSP by 128.
33406   BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
33407 
33408   // Every iteration we decrement the counter by 1.
33409   unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
33410   BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
33411 
33412   // Jump if the counter is not zero yet.
33413   BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
33414   fixShadowLoopMBB->addSuccessor(sinkMBB);
33415   fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
33416 
33417   return sinkMBB;
33418 }
33419 
33420 MachineBasicBlock *
33421 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
33422                                      MachineBasicBlock *MBB) const {
33423   const DebugLoc &DL = MI.getDebugLoc();
33424   MachineFunction *MF = MBB->getParent();
33425   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33426   MachineRegisterInfo &MRI = MF->getRegInfo();
33427 
33428   // Memory Reference
33429   SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
33430                                            MI.memoperands_end());
33431 
33432   MVT PVT = getPointerTy(MF->getDataLayout());
33433   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
33434          "Invalid Pointer Size!");
33435 
33436   const TargetRegisterClass *RC =
33437     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
33438   Register Tmp = MRI.createVirtualRegister(RC);
33439   // Since FP is only updated here but NOT referenced, it's treated as GPR.
33440   const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
33441   Register FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
33442   Register SP = RegInfo->getStackRegister();
33443 
33444   MachineInstrBuilder MIB;
33445 
33446   const int64_t LabelOffset = 1 * PVT.getStoreSize();
33447   const int64_t SPOffset = 2 * PVT.getStoreSize();
33448 
33449   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
33450   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
33451 
33452   MachineBasicBlock *thisMBB = MBB;
33453 
33454   // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
33455   if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
33456     thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
33457   }
33458 
33459   // Reload FP
33460   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
33461   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33462     const MachineOperand &MO = MI.getOperand(i);
33463     if (MO.isReg()) // Don't add the whole operand, we don't want to
33464                     // preserve kill flags.
33465       MIB.addReg(MO.getReg());
33466     else
33467       MIB.add(MO);
33468   }
33469   MIB.setMemRefs(MMOs);
33470 
33471   // Reload IP
33472   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
33473   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33474     const MachineOperand &MO = MI.getOperand(i);
33475     if (i == X86::AddrDisp)
33476       MIB.addDisp(MO, LabelOffset);
33477     else if (MO.isReg()) // Don't add the whole operand, we don't want to
33478                          // preserve kill flags.
33479       MIB.addReg(MO.getReg());
33480     else
33481       MIB.add(MO);
33482   }
33483   MIB.setMemRefs(MMOs);
33484 
33485   // Reload SP
33486   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
33487   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
33488     if (i == X86::AddrDisp)
33489       MIB.addDisp(MI.getOperand(i), SPOffset);
33490     else
33491       MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
33492                                  // the last instruction of the expansion.
33493   }
33494   MIB.setMemRefs(MMOs);
33495 
33496   // Jump
33497   BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
33498 
33499   MI.eraseFromParent();
33500   return thisMBB;
33501 }
33502 
33503 void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
33504                                                MachineBasicBlock *MBB,
33505                                                MachineBasicBlock *DispatchBB,
33506                                                int FI) const {
33507   const DebugLoc &DL = MI.getDebugLoc();
33508   MachineFunction *MF = MBB->getParent();
33509   MachineRegisterInfo *MRI = &MF->getRegInfo();
33510   const X86InstrInfo *TII = Subtarget.getInstrInfo();
33511 
33512   MVT PVT = getPointerTy(MF->getDataLayout());
33513   assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
33514 
33515   unsigned Op = 0;
33516   unsigned VR = 0;
33517 
33518   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
33519                      !isPositionIndependent();
33520 
33521   if (UseImmLabel) {
33522     Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
33523   } else {
33524     const TargetRegisterClass *TRC =
33525         (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
33526     VR = MRI->createVirtualRegister(TRC);
33527     Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
33528 
33529     if (Subtarget.is64Bit())
33530       BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
33531           .addReg(X86::RIP)
33532           .addImm(1)
33533           .addReg(0)
33534           .addMBB(DispatchBB)
33535           .addReg(0);
33536     else
33537       BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
33538           .addReg(0) /* TII->getGlobalBaseReg(MF) */
33539           .addImm(1)
33540           .addReg(0)
33541           .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
33542           .addReg(0);
33543   }
33544 
33545   MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
33546   addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
33547   if (UseImmLabel)
33548     MIB.addMBB(DispatchBB);
33549   else
33550     MIB.addReg(VR);
33551 }
33552 
33553 MachineBasicBlock *
33554 X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
33555                                          MachineBasicBlock *BB) const {
33556   const DebugLoc &DL = MI.getDebugLoc();
33557   MachineFunction *MF = BB->getParent();
33558   MachineRegisterInfo *MRI = &MF->getRegInfo();
33559   const X86InstrInfo *TII = Subtarget.getInstrInfo();
33560   int FI = MF->getFrameInfo().getFunctionContextIndex();
33561 
33562   // Get a mapping of the call site numbers to all of the landing pads they're
33563   // associated with.
33564   DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
33565   unsigned MaxCSNum = 0;
33566   for (auto &MBB : *MF) {
33567     if (!MBB.isEHPad())
33568       continue;
33569 
33570     MCSymbol *Sym = nullptr;
33571     for (const auto &MI : MBB) {
33572       if (MI.isDebugInstr())
33573         continue;
33574 
33575       assert(MI.isEHLabel() && "expected EH_LABEL");
33576       Sym = MI.getOperand(0).getMCSymbol();
33577       break;
33578     }
33579 
33580     if (!MF->hasCallSiteLandingPad(Sym))
33581       continue;
33582 
33583     for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
33584       CallSiteNumToLPad[CSI].push_back(&MBB);
33585       MaxCSNum = std::max(MaxCSNum, CSI);
33586     }
33587   }
33588 
33589   // Get an ordered list of the machine basic blocks for the jump table.
33590   std::vector<MachineBasicBlock *> LPadList;
33591   SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
33592   LPadList.reserve(CallSiteNumToLPad.size());
33593 
33594   for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
33595     for (auto &LP : CallSiteNumToLPad[CSI]) {
33596       LPadList.push_back(LP);
33597       InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
33598     }
33599   }
33600 
33601   assert(!LPadList.empty() &&
33602          "No landing pad destinations for the dispatch jump table!");
33603 
33604   // Create the MBBs for the dispatch code.
33605 
33606   // Shove the dispatch's address into the return slot in the function context.
33607   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
33608   DispatchBB->setIsEHPad(true);
33609 
33610   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
33611   BuildMI(TrapBB, DL, TII->get(X86::TRAP));
33612   DispatchBB->addSuccessor(TrapBB);
33613 
33614   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
33615   DispatchBB->addSuccessor(DispContBB);
33616 
33617   // Insert MBBs.
33618   MF->push_back(DispatchBB);
33619   MF->push_back(DispContBB);
33620   MF->push_back(TrapBB);
33621 
33622   // Insert code into the entry block that creates and registers the function
33623   // context.
33624   SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
33625 
33626   // Create the jump table and associated information
33627   unsigned JTE = getJumpTableEncoding();
33628   MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
33629   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
33630 
33631   const X86RegisterInfo &RI = TII->getRegisterInfo();
33632   // Add a register mask with no preserved registers.  This results in all
33633   // registers being marked as clobbered.
33634   if (RI.hasBasePointer(*MF)) {
33635     const bool FPIs64Bit =
33636         Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
33637     X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
33638     MFI->setRestoreBasePointer(MF);
33639 
33640     Register FP = RI.getFrameRegister(*MF);
33641     Register BP = RI.getBaseRegister();
33642     unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
33643     addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
33644                  MFI->getRestoreBasePointerOffset())
33645         .addRegMask(RI.getNoPreservedMask());
33646   } else {
33647     BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
33648         .addRegMask(RI.getNoPreservedMask());
33649   }
33650 
33651   // IReg is used as an index in a memory operand and therefore can't be SP
33652   Register IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
33653   addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
33654                     Subtarget.is64Bit() ? 8 : 4);
33655   BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
33656       .addReg(IReg)
33657       .addImm(LPadList.size());
33658   BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
33659 
33660   if (Subtarget.is64Bit()) {
33661     Register BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
33662     Register IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
33663 
33664     // leaq .LJTI0_0(%rip), BReg
33665     BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
33666         .addReg(X86::RIP)
33667         .addImm(1)
33668         .addReg(0)
33669         .addJumpTableIndex(MJTI)
33670         .addReg(0);
33671     // movzx IReg64, IReg
33672     BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
33673         .addImm(0)
33674         .addReg(IReg)
33675         .addImm(X86::sub_32bit);
33676 
33677     switch (JTE) {
33678     case MachineJumpTableInfo::EK_BlockAddress:
33679       // jmpq *(BReg,IReg64,8)
33680       BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
33681           .addReg(BReg)
33682           .addImm(8)
33683           .addReg(IReg64)
33684           .addImm(0)
33685           .addReg(0);
33686       break;
33687     case MachineJumpTableInfo::EK_LabelDifference32: {
33688       Register OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
33689       Register OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
33690       Register TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
33691 
33692       // movl (BReg,IReg64,4), OReg
33693       BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
33694           .addReg(BReg)
33695           .addImm(4)
33696           .addReg(IReg64)
33697           .addImm(0)
33698           .addReg(0);
33699       // movsx OReg64, OReg
33700       BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
33701       // addq BReg, OReg64, TReg
33702       BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
33703           .addReg(OReg64)
33704           .addReg(BReg);
33705       // jmpq *TReg
33706       BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
33707       break;
33708     }
33709     default:
33710       llvm_unreachable("Unexpected jump table encoding");
33711     }
33712   } else {
33713     // jmpl *.LJTI0_0(,IReg,4)
33714     BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
33715         .addReg(0)
33716         .addImm(4)
33717         .addReg(IReg)
33718         .addJumpTableIndex(MJTI)
33719         .addReg(0);
33720   }
33721 
33722   // Add the jump table entries as successors to the MBB.
33723   SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
33724   for (auto &LP : LPadList)
33725     if (SeenMBBs.insert(LP).second)
33726       DispContBB->addSuccessor(LP);
33727 
33728   // N.B. the order the invoke BBs are processed in doesn't matter here.
33729   SmallVector<MachineBasicBlock *, 64> MBBLPads;
33730   const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
33731   for (MachineBasicBlock *MBB : InvokeBBs) {
33732     // Remove the landing pad successor from the invoke block and replace it
33733     // with the new dispatch block.
33734     // Keep a copy of Successors since it's modified inside the loop.
33735     SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
33736                                                    MBB->succ_rend());
33737     // FIXME: Avoid quadratic complexity.
33738     for (auto MBBS : Successors) {
33739       if (MBBS->isEHPad()) {
33740         MBB->removeSuccessor(MBBS);
33741         MBBLPads.push_back(MBBS);
33742       }
33743     }
33744 
33745     MBB->addSuccessor(DispatchBB);
33746 
33747     // Find the invoke call and mark all of the callee-saved registers as
33748     // 'implicit defined' so that they're spilled.  This prevents code from
33749     // moving instructions to before the EH block, where they will never be
33750     // executed.
33751     for (auto &II : reverse(*MBB)) {
33752       if (!II.isCall())
33753         continue;
33754 
33755       DenseMap<unsigned, bool> DefRegs;
33756       for (auto &MOp : II.operands())
33757         if (MOp.isReg())
33758           DefRegs[MOp.getReg()] = true;
33759 
33760       MachineInstrBuilder MIB(*MF, &II);
33761       for (unsigned RegIdx = 0; SavedRegs[RegIdx]; ++RegIdx) {
33762         unsigned Reg = SavedRegs[RegIdx];
33763         if (!DefRegs[Reg])
33764           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
33765       }
33766 
33767       break;
33768     }
33769   }
33770 
33771   // Mark all former landing pads as non-landing pads.  The dispatch is the only
33772   // landing pad now.
33773   for (auto &LP : MBBLPads)
33774     LP->setIsEHPad(false);
33775 
33776   // The instruction is gone now.
33777   MI.eraseFromParent();
33778   return BB;
33779 }
33780 
33781 MachineBasicBlock *
33782 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
33783                                                MachineBasicBlock *BB) const {
33784   MachineFunction *MF = BB->getParent();
33785   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
33786   const DebugLoc &DL = MI.getDebugLoc();
33787 
33788   auto TMMImmToTMMReg = [](unsigned Imm) {
33789     assert (Imm < 8 && "Illegal tmm index");
33790     return X86::TMM0 + Imm;
33791   };
33792   switch (MI.getOpcode()) {
33793   default: llvm_unreachable("Unexpected instr type to insert");
33794   case X86::TLS_addr32:
33795   case X86::TLS_addr64:
33796   case X86::TLS_addrX32:
33797   case X86::TLS_base_addr32:
33798   case X86::TLS_base_addr64:
33799   case X86::TLS_base_addrX32:
33800     return EmitLoweredTLSAddr(MI, BB);
33801   case X86::INDIRECT_THUNK_CALL32:
33802   case X86::INDIRECT_THUNK_CALL64:
33803   case X86::INDIRECT_THUNK_TCRETURN32:
33804   case X86::INDIRECT_THUNK_TCRETURN64:
33805     return EmitLoweredIndirectThunk(MI, BB);
33806   case X86::CATCHRET:
33807     return EmitLoweredCatchRet(MI, BB);
33808   case X86::SEG_ALLOCA_32:
33809   case X86::SEG_ALLOCA_64:
33810     return EmitLoweredSegAlloca(MI, BB);
33811   case X86::PROBED_ALLOCA_32:
33812   case X86::PROBED_ALLOCA_64:
33813     return EmitLoweredProbedAlloca(MI, BB);
33814   case X86::TLSCall_32:
33815   case X86::TLSCall_64:
33816     return EmitLoweredTLSCall(MI, BB);
33817   case X86::CMOV_FR32:
33818   case X86::CMOV_FR32X:
33819   case X86::CMOV_FR64:
33820   case X86::CMOV_FR64X:
33821   case X86::CMOV_GR8:
33822   case X86::CMOV_GR16:
33823   case X86::CMOV_GR32:
33824   case X86::CMOV_RFP32:
33825   case X86::CMOV_RFP64:
33826   case X86::CMOV_RFP80:
33827   case X86::CMOV_VR64:
33828   case X86::CMOV_VR128:
33829   case X86::CMOV_VR128X:
33830   case X86::CMOV_VR256:
33831   case X86::CMOV_VR256X:
33832   case X86::CMOV_VR512:
33833   case X86::CMOV_VK1:
33834   case X86::CMOV_VK2:
33835   case X86::CMOV_VK4:
33836   case X86::CMOV_VK8:
33837   case X86::CMOV_VK16:
33838   case X86::CMOV_VK32:
33839   case X86::CMOV_VK64:
33840     return EmitLoweredSelect(MI, BB);
33841 
33842   case X86::RDFLAGS32:
33843   case X86::RDFLAGS64: {
33844     unsigned PushF =
33845         MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
33846     unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
33847     MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
33848     // Permit reads of the EFLAGS and DF registers without them being defined.
33849     // This intrinsic exists to read external processor state in flags, such as
33850     // the trap flag, interrupt flag, and direction flag, none of which are
33851     // modeled by the backend.
33852     assert(Push->getOperand(2).getReg() == X86::EFLAGS &&
33853            "Unexpected register in operand!");
33854     Push->getOperand(2).setIsUndef();
33855     assert(Push->getOperand(3).getReg() == X86::DF &&
33856            "Unexpected register in operand!");
33857     Push->getOperand(3).setIsUndef();
33858     BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
33859 
33860     MI.eraseFromParent(); // The pseudo is gone now.
33861     return BB;
33862   }
33863 
33864   case X86::WRFLAGS32:
33865   case X86::WRFLAGS64: {
33866     unsigned Push =
33867         MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
33868     unsigned PopF =
33869         MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
33870     BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
33871     BuildMI(*BB, MI, DL, TII->get(PopF));
33872 
33873     MI.eraseFromParent(); // The pseudo is gone now.
33874     return BB;
33875   }
33876 
33877   case X86::FP32_TO_INT16_IN_MEM:
33878   case X86::FP32_TO_INT32_IN_MEM:
33879   case X86::FP32_TO_INT64_IN_MEM:
33880   case X86::FP64_TO_INT16_IN_MEM:
33881   case X86::FP64_TO_INT32_IN_MEM:
33882   case X86::FP64_TO_INT64_IN_MEM:
33883   case X86::FP80_TO_INT16_IN_MEM:
33884   case X86::FP80_TO_INT32_IN_MEM:
33885   case X86::FP80_TO_INT64_IN_MEM: {
33886     // Change the floating point control register to use "round towards zero"
33887     // mode when truncating to an integer value.
33888     int OrigCWFrameIdx =
33889         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
33890     addFrameReference(BuildMI(*BB, MI, DL,
33891                               TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
33892 
33893     // Load the old value of the control word...
33894     Register OldCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
33895     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
33896                       OrigCWFrameIdx);
33897 
33898     // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
33899     Register NewCW = MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
33900     BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
33901       .addReg(OldCW, RegState::Kill).addImm(0xC00);
33902 
33903     // Extract to 16 bits.
33904     Register NewCW16 =
33905         MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
33906     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
33907       .addReg(NewCW, RegState::Kill, X86::sub_16bit);
33908 
33909     // Prepare memory for FLDCW.
33910     int NewCWFrameIdx =
33911         MF->getFrameInfo().CreateStackObject(2, Align(2), false);
33912     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
33913                       NewCWFrameIdx)
33914       .addReg(NewCW16, RegState::Kill);
33915 
33916     // Reload the modified control word now...
33917     addFrameReference(BuildMI(*BB, MI, DL,
33918                               TII->get(X86::FLDCW16m)), NewCWFrameIdx);
33919 
33920     // Get the X86 opcode to use.
33921     unsigned Opc;
33922     switch (MI.getOpcode()) {
33923     default: llvm_unreachable("illegal opcode!");
33924     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
33925     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
33926     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
33927     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
33928     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
33929     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
33930     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
33931     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
33932     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
33933     }
33934 
33935     X86AddressMode AM = getAddressFromInstr(&MI, 0);
33936     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
33937         .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
33938 
33939     // Reload the original control word now.
33940     addFrameReference(BuildMI(*BB, MI, DL,
33941                               TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
33942 
33943     MI.eraseFromParent(); // The pseudo instruction is gone now.
33944     return BB;
33945   }
33946 
33947   // xbegin
33948   case X86::XBEGIN:
33949     return emitXBegin(MI, BB, Subtarget.getInstrInfo());
33950 
33951   case X86::VASTART_SAVE_XMM_REGS:
33952     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
33953 
33954   case X86::VAARG_64:
33955   case X86::VAARG_X32:
33956     return EmitVAARGWithCustomInserter(MI, BB);
33957 
33958   case X86::EH_SjLj_SetJmp32:
33959   case X86::EH_SjLj_SetJmp64:
33960     return emitEHSjLjSetJmp(MI, BB);
33961 
33962   case X86::EH_SjLj_LongJmp32:
33963   case X86::EH_SjLj_LongJmp64:
33964     return emitEHSjLjLongJmp(MI, BB);
33965 
33966   case X86::Int_eh_sjlj_setup_dispatch:
33967     return EmitSjLjDispatchBlock(MI, BB);
33968 
33969   case TargetOpcode::STATEPOINT:
33970     // As an implementation detail, STATEPOINT shares the STACKMAP format at
33971     // this point in the process.  We diverge later.
33972     return emitPatchPoint(MI, BB);
33973 
33974   case TargetOpcode::STACKMAP:
33975   case TargetOpcode::PATCHPOINT:
33976     return emitPatchPoint(MI, BB);
33977 
33978   case TargetOpcode::PATCHABLE_EVENT_CALL:
33979   case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
33980     return BB;
33981 
33982   case X86::LCMPXCHG8B: {
33983     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
33984     // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
33985     // requires a memory operand. If it happens that current architecture is
33986     // i686 and for current function we need a base pointer
33987     // - which is ESI for i686 - register allocator would not be able to
33988     // allocate registers for an address in form of X(%reg, %reg, Y)
33989     // - there never would be enough unreserved registers during regalloc
33990     // (without the need for base ptr the only option would be X(%edi, %esi, Y).
33991     // We are giving a hand to register allocator by precomputing the address in
33992     // a new vreg using LEA.
33993 
33994     // If it is not i686 or there is no base pointer - nothing to do here.
33995     if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
33996       return BB;
33997 
33998     // Even though this code does not necessarily needs the base pointer to
33999     // be ESI, we check for that. The reason: if this assert fails, there are
34000     // some changes happened in the compiler base pointer handling, which most
34001     // probably have to be addressed somehow here.
34002     assert(TRI->getBaseRegister() == X86::ESI &&
34003            "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
34004            "base pointer in mind");
34005 
34006     MachineRegisterInfo &MRI = MF->getRegInfo();
34007     MVT SPTy = getPointerTy(MF->getDataLayout());
34008     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
34009     Register computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
34010 
34011     X86AddressMode AM = getAddressFromInstr(&MI, 0);
34012     // Regalloc does not need any help when the memory operand of CMPXCHG8B
34013     // does not use index register.
34014     if (AM.IndexReg == X86::NoRegister)
34015       return BB;
34016 
34017     // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
34018     // four operand definitions that are E[ABCD] registers. We skip them and
34019     // then insert the LEA.
34020     MachineBasicBlock::reverse_iterator RMBBI(MI.getReverseIterator());
34021     while (RMBBI != BB->rend() && (RMBBI->definesRegister(X86::EAX) ||
34022                                    RMBBI->definesRegister(X86::EBX) ||
34023                                    RMBBI->definesRegister(X86::ECX) ||
34024                                    RMBBI->definesRegister(X86::EDX))) {
34025       ++RMBBI;
34026     }
34027     MachineBasicBlock::iterator MBBI(RMBBI);
34028     addFullAddress(
34029         BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
34030 
34031     setDirectAddressInInstr(&MI, 0, computedAddrVReg);
34032 
34033     return BB;
34034   }
34035   case X86::LCMPXCHG16B_NO_RBX: {
34036     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
34037     Register BasePtr = TRI->getBaseRegister();
34038     if (TRI->hasBasePointer(*MF) &&
34039         (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
34040       if (!BB->isLiveIn(BasePtr))
34041         BB->addLiveIn(BasePtr);
34042       // Save RBX into a virtual register.
34043       Register SaveRBX =
34044           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34045       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
34046           .addReg(X86::RBX);
34047       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34048       MachineInstrBuilder MIB =
34049           BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B_SAVE_RBX), Dst);
34050       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
34051         MIB.add(MI.getOperand(Idx));
34052       MIB.add(MI.getOperand(X86::AddrNumOperands));
34053       MIB.addReg(SaveRBX);
34054     } else {
34055       // Simple case, just copy the virtual register to RBX.
34056       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::RBX)
34057           .add(MI.getOperand(X86::AddrNumOperands));
34058       MachineInstrBuilder MIB =
34059           BuildMI(*BB, MI, DL, TII->get(X86::LCMPXCHG16B));
34060       for (unsigned Idx = 0; Idx < X86::AddrNumOperands; ++Idx)
34061         MIB.add(MI.getOperand(Idx));
34062     }
34063     MI.eraseFromParent();
34064     return BB;
34065   }
34066   case X86::MWAITX: {
34067     const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
34068     Register BasePtr = TRI->getBaseRegister();
34069     bool IsRBX = (BasePtr == X86::RBX || BasePtr == X86::EBX);
34070     // If no need to save the base pointer, we generate MWAITXrrr,
34071     // else we generate pseudo MWAITX_SAVE_RBX.
34072     if (!IsRBX || !TRI->hasBasePointer(*MF)) {
34073       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
34074           .addReg(MI.getOperand(0).getReg());
34075       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
34076           .addReg(MI.getOperand(1).getReg());
34077       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EBX)
34078           .addReg(MI.getOperand(2).getReg());
34079       BuildMI(*BB, MI, DL, TII->get(X86::MWAITXrrr));
34080       MI.eraseFromParent();
34081     } else {
34082       if (!BB->isLiveIn(BasePtr)) {
34083         BB->addLiveIn(BasePtr);
34084       }
34085       // Parameters can be copied into ECX and EAX but not EBX yet.
34086       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::ECX)
34087           .addReg(MI.getOperand(0).getReg());
34088       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), X86::EAX)
34089           .addReg(MI.getOperand(1).getReg());
34090       assert(Subtarget.is64Bit() && "Expected 64-bit mode!");
34091       // Save RBX into a virtual register.
34092       Register SaveRBX =
34093           MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34094       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), SaveRBX)
34095           .addReg(X86::RBX);
34096       // Generate mwaitx pseudo.
34097       Register Dst = MF->getRegInfo().createVirtualRegister(&X86::GR64RegClass);
34098       BuildMI(*BB, MI, DL, TII->get(X86::MWAITX_SAVE_RBX))
34099           .addDef(Dst) // Destination tied in with SaveRBX.
34100           .addReg(MI.getOperand(2).getReg()) // input value of EBX.
34101           .addUse(SaveRBX);                  // Save of base pointer.
34102       MI.eraseFromParent();
34103     }
34104     return BB;
34105   }
34106   case TargetOpcode::PREALLOCATED_SETUP: {
34107     assert(Subtarget.is32Bit() && "preallocated only used in 32-bit");
34108     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
34109     MFI->setHasPreallocatedCall(true);
34110     int64_t PreallocatedId = MI.getOperand(0).getImm();
34111     size_t StackAdjustment = MFI->getPreallocatedStackSize(PreallocatedId);
34112     assert(StackAdjustment != 0 && "0 stack adjustment");
34113     LLVM_DEBUG(dbgs() << "PREALLOCATED_SETUP stack adjustment "
34114                       << StackAdjustment << "\n");
34115     BuildMI(*BB, MI, DL, TII->get(X86::SUB32ri), X86::ESP)
34116         .addReg(X86::ESP)
34117         .addImm(StackAdjustment);
34118     MI.eraseFromParent();
34119     return BB;
34120   }
34121   case TargetOpcode::PREALLOCATED_ARG: {
34122     assert(Subtarget.is32Bit() && "preallocated calls only used in 32-bit");
34123     int64_t PreallocatedId = MI.getOperand(1).getImm();
34124     int64_t ArgIdx = MI.getOperand(2).getImm();
34125     auto MFI = MF->getInfo<X86MachineFunctionInfo>();
34126     size_t ArgOffset = MFI->getPreallocatedArgOffsets(PreallocatedId)[ArgIdx];
34127     LLVM_DEBUG(dbgs() << "PREALLOCATED_ARG arg index " << ArgIdx
34128                       << ", arg offset " << ArgOffset << "\n");
34129     // stack pointer + offset
34130     addRegOffset(
34131         BuildMI(*BB, MI, DL, TII->get(X86::LEA32r), MI.getOperand(0).getReg()),
34132         X86::ESP, false, ArgOffset);
34133     MI.eraseFromParent();
34134     return BB;
34135   }
34136   case X86::PTDPBSSD:
34137   case X86::PTDPBSUD:
34138   case X86::PTDPBUSD:
34139   case X86::PTDPBUUD:
34140   case X86::PTDPBF16PS: {
34141     unsigned Opc;
34142     switch (MI.getOpcode()) {
34143     case X86::PTDPBSSD: Opc = X86::TDPBSSD; break;
34144     case X86::PTDPBSUD: Opc = X86::TDPBSUD; break;
34145     case X86::PTDPBUSD: Opc = X86::TDPBUSD; break;
34146     case X86::PTDPBUUD: Opc = X86::TDPBUUD; break;
34147     case X86::PTDPBF16PS: Opc = X86::TDPBF16PS; break;
34148     }
34149 
34150     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
34151     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Define);
34152     MIB.addReg(TMMImmToTMMReg(MI.getOperand(0).getImm()), RegState::Undef);
34153     MIB.addReg(TMMImmToTMMReg(MI.getOperand(1).getImm()), RegState::Undef);
34154     MIB.addReg(TMMImmToTMMReg(MI.getOperand(2).getImm()), RegState::Undef);
34155 
34156     MI.eraseFromParent(); // The pseudo is gone now.
34157     return BB;
34158   }
34159   case X86::PTILEZERO: {
34160     unsigned Imm = MI.getOperand(0).getImm();
34161     BuildMI(*BB, MI, DL, TII->get(X86::TILEZERO), TMMImmToTMMReg(Imm));
34162     MI.eraseFromParent(); // The pseudo is gone now.
34163     return BB;
34164   }
34165   case X86::PTILELOADD:
34166   case X86::PTILELOADDT1:
34167   case X86::PTILESTORED: {
34168     unsigned Opc;
34169     switch (MI.getOpcode()) {
34170     case X86::PTILELOADD:   Opc = X86::TILELOADD;   break;
34171     case X86::PTILELOADDT1: Opc = X86::TILELOADDT1; break;
34172     case X86::PTILESTORED:  Opc = X86::TILESTORED;  break;
34173     }
34174 
34175     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL, TII->get(Opc));
34176     unsigned CurOp = 0;
34177     if (Opc != X86::TILESTORED)
34178       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
34179                  RegState::Define);
34180 
34181     MIB.add(MI.getOperand(CurOp++)); // base
34182     MIB.add(MI.getOperand(CurOp++)); // scale
34183     MIB.add(MI.getOperand(CurOp++)); // index -- stride
34184     MIB.add(MI.getOperand(CurOp++)); // displacement
34185     MIB.add(MI.getOperand(CurOp++)); // segment
34186 
34187     if (Opc == X86::TILESTORED)
34188       MIB.addReg(TMMImmToTMMReg(MI.getOperand(CurOp++).getImm()),
34189                  RegState::Undef);
34190 
34191     MI.eraseFromParent(); // The pseudo is gone now.
34192     return BB;
34193   }
34194   }
34195 }
34196 
34197 //===----------------------------------------------------------------------===//
34198 //                           X86 Optimization Hooks
34199 //===----------------------------------------------------------------------===//
34200 
34201 bool
34202 X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
34203                                                 const APInt &DemandedBits,
34204                                                 const APInt &DemandedElts,
34205                                                 TargetLoweringOpt &TLO) const {
34206   EVT VT = Op.getValueType();
34207   unsigned Opcode = Op.getOpcode();
34208   unsigned EltSize = VT.getScalarSizeInBits();
34209 
34210   if (VT.isVector()) {
34211     // If the constant is only all signbits in the active bits, then we should
34212     // extend it to the entire constant to allow it act as a boolean constant
34213     // vector.
34214     auto NeedsSignExtension = [&](SDValue V, unsigned ActiveBits) {
34215       if (!ISD::isBuildVectorOfConstantSDNodes(V.getNode()))
34216         return false;
34217       for (unsigned i = 0, e = V.getNumOperands(); i != e; ++i) {
34218         if (!DemandedElts[i] || V.getOperand(i).isUndef())
34219           continue;
34220         const APInt &Val = V.getConstantOperandAPInt(i);
34221         if (Val.getBitWidth() > Val.getNumSignBits() &&
34222             Val.trunc(ActiveBits).getNumSignBits() == ActiveBits)
34223           return true;
34224       }
34225       return false;
34226     };
34227     // For vectors - if we have a constant, then try to sign extend.
34228     // TODO: Handle AND/ANDN cases.
34229     unsigned ActiveBits = DemandedBits.getActiveBits();
34230     if (EltSize > ActiveBits && EltSize > 1 && isTypeLegal(VT) &&
34231         (Opcode == ISD::OR || Opcode == ISD::XOR) &&
34232         NeedsSignExtension(Op.getOperand(1), ActiveBits)) {
34233       EVT ExtSVT = EVT::getIntegerVT(*TLO.DAG.getContext(), ActiveBits);
34234       EVT ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtSVT,
34235                                     VT.getVectorNumElements());
34236       SDValue NewC =
34237           TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(Op), VT,
34238                           Op.getOperand(1), TLO.DAG.getValueType(ExtVT));
34239       SDValue NewOp =
34240           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, Op.getOperand(0), NewC);
34241       return TLO.CombineTo(Op, NewOp);
34242     }
34243     return false;
34244   }
34245 
34246   // Only optimize Ands to prevent shrinking a constant that could be
34247   // matched by movzx.
34248   if (Opcode != ISD::AND)
34249     return false;
34250 
34251   // Make sure the RHS really is a constant.
34252   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
34253   if (!C)
34254     return false;
34255 
34256   const APInt &Mask = C->getAPIntValue();
34257 
34258   // Clear all non-demanded bits initially.
34259   APInt ShrunkMask = Mask & DemandedBits;
34260 
34261   // Find the width of the shrunk mask.
34262   unsigned Width = ShrunkMask.getActiveBits();
34263 
34264   // If the mask is all 0s there's nothing to do here.
34265   if (Width == 0)
34266     return false;
34267 
34268   // Find the next power of 2 width, rounding up to a byte.
34269   Width = PowerOf2Ceil(std::max(Width, 8U));
34270   // Truncate the width to size to handle illegal types.
34271   Width = std::min(Width, EltSize);
34272 
34273   // Calculate a possible zero extend mask for this constant.
34274   APInt ZeroExtendMask = APInt::getLowBitsSet(EltSize, Width);
34275 
34276   // If we aren't changing the mask, just return true to keep it and prevent
34277   // the caller from optimizing.
34278   if (ZeroExtendMask == Mask)
34279     return true;
34280 
34281   // Make sure the new mask can be represented by a combination of mask bits
34282   // and non-demanded bits.
34283   if (!ZeroExtendMask.isSubsetOf(Mask | ~DemandedBits))
34284     return false;
34285 
34286   // Replace the constant with the zero extend mask.
34287   SDLoc DL(Op);
34288   SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
34289   SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
34290   return TLO.CombineTo(Op, NewOp);
34291 }
34292 
34293 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
34294                                                       KnownBits &Known,
34295                                                       const APInt &DemandedElts,
34296                                                       const SelectionDAG &DAG,
34297                                                       unsigned Depth) const {
34298   unsigned BitWidth = Known.getBitWidth();
34299   unsigned NumElts = DemandedElts.getBitWidth();
34300   unsigned Opc = Op.getOpcode();
34301   EVT VT = Op.getValueType();
34302   assert((Opc >= ISD::BUILTIN_OP_END ||
34303           Opc == ISD::INTRINSIC_WO_CHAIN ||
34304           Opc == ISD::INTRINSIC_W_CHAIN ||
34305           Opc == ISD::INTRINSIC_VOID) &&
34306          "Should use MaskedValueIsZero if you don't know whether Op"
34307          " is a target node!");
34308 
34309   Known.resetAll();
34310   switch (Opc) {
34311   default: break;
34312   case X86ISD::SETCC:
34313     Known.Zero.setBitsFrom(1);
34314     break;
34315   case X86ISD::MOVMSK: {
34316     unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
34317     Known.Zero.setBitsFrom(NumLoBits);
34318     break;
34319   }
34320   case X86ISD::PEXTRB:
34321   case X86ISD::PEXTRW: {
34322     SDValue Src = Op.getOperand(0);
34323     EVT SrcVT = Src.getValueType();
34324     APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
34325                                             Op.getConstantOperandVal(1));
34326     Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
34327     Known = Known.anyextOrTrunc(BitWidth);
34328     Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
34329     break;
34330   }
34331   case X86ISD::VSRAI:
34332   case X86ISD::VSHLI:
34333   case X86ISD::VSRLI: {
34334     unsigned ShAmt = Op.getConstantOperandVal(1);
34335     if (ShAmt >= VT.getScalarSizeInBits()) {
34336       Known.setAllZero();
34337       break;
34338     }
34339 
34340     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34341     if (Opc == X86ISD::VSHLI) {
34342       Known.Zero <<= ShAmt;
34343       Known.One <<= ShAmt;
34344       // Low bits are known zero.
34345       Known.Zero.setLowBits(ShAmt);
34346     } else if (Opc == X86ISD::VSRLI) {
34347       Known.Zero.lshrInPlace(ShAmt);
34348       Known.One.lshrInPlace(ShAmt);
34349       // High bits are known zero.
34350       Known.Zero.setHighBits(ShAmt);
34351     } else {
34352       Known.Zero.ashrInPlace(ShAmt);
34353       Known.One.ashrInPlace(ShAmt);
34354     }
34355     break;
34356   }
34357   case X86ISD::PACKUS: {
34358     // PACKUS is just a truncation if the upper half is zero.
34359     APInt DemandedLHS, DemandedRHS;
34360     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
34361 
34362     Known.One = APInt::getAllOnesValue(BitWidth * 2);
34363     Known.Zero = APInt::getAllOnesValue(BitWidth * 2);
34364 
34365     KnownBits Known2;
34366     if (!!DemandedLHS) {
34367       Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
34368       Known = KnownBits::commonBits(Known, Known2);
34369     }
34370     if (!!DemandedRHS) {
34371       Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
34372       Known = KnownBits::commonBits(Known, Known2);
34373     }
34374 
34375     if (Known.countMinLeadingZeros() < BitWidth)
34376       Known.resetAll();
34377     Known = Known.trunc(BitWidth);
34378     break;
34379   }
34380   case X86ISD::ANDNP: {
34381     KnownBits Known2;
34382     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34383     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34384 
34385     // ANDNP = (~X & Y);
34386     Known.One &= Known2.Zero;
34387     Known.Zero |= Known2.One;
34388     break;
34389   }
34390   case X86ISD::FOR: {
34391     KnownBits Known2;
34392     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34393     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34394 
34395     Known |= Known2;
34396     break;
34397   }
34398   case X86ISD::PSADBW: {
34399     assert(VT.getScalarType() == MVT::i64 &&
34400            Op.getOperand(0).getValueType().getScalarType() == MVT::i8 &&
34401            "Unexpected PSADBW types");
34402 
34403     // PSADBW - fills low 16 bits and zeros upper 48 bits of each i64 result.
34404     Known.Zero.setBitsFrom(16);
34405     break;
34406   }
34407   case X86ISD::CMOV: {
34408     Known = DAG.computeKnownBits(Op.getOperand(1), Depth + 1);
34409     // If we don't know any bits, early out.
34410     if (Known.isUnknown())
34411       break;
34412     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
34413 
34414     // Only known if known in both the LHS and RHS.
34415     Known = KnownBits::commonBits(Known, Known2);
34416     break;
34417   }
34418   case X86ISD::BEXTR:
34419   case X86ISD::BEXTRI: {
34420     SDValue Op0 = Op.getOperand(0);
34421     SDValue Op1 = Op.getOperand(1);
34422 
34423     if (auto* Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
34424       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
34425       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
34426 
34427       // If the length is 0, the result is 0.
34428       if (Length == 0) {
34429         Known.setAllZero();
34430         break;
34431       }
34432 
34433       if ((Shift + Length) <= BitWidth) {
34434         Known = DAG.computeKnownBits(Op0, Depth + 1);
34435         Known = Known.extractBits(Length, Shift);
34436         Known = Known.zextOrTrunc(BitWidth);
34437       }
34438     }
34439     break;
34440   }
34441   case X86ISD::PDEP: {
34442     KnownBits Known2;
34443     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34444     Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
34445     // Zeros are retained from the mask operand. But not ones.
34446     Known.One.clearAllBits();
34447     // The result will have at least as many trailing zeros as the non-mask
34448     // operand since bits can only map to the same or higher bit position.
34449     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
34450     break;
34451   }
34452   case X86ISD::PEXT: {
34453     Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
34454     // The result has as many leading zeros as the number of zeroes in the mask.
34455     unsigned Count = Known.Zero.countPopulation();
34456     Known.Zero = APInt::getHighBitsSet(BitWidth, Count);
34457     Known.One.clearAllBits();
34458     break;
34459   }
34460   case X86ISD::VTRUNC:
34461   case X86ISD::VTRUNCS:
34462   case X86ISD::VTRUNCUS:
34463   case X86ISD::CVTSI2P:
34464   case X86ISD::CVTUI2P:
34465   case X86ISD::CVTP2SI:
34466   case X86ISD::CVTP2UI:
34467   case X86ISD::MCVTP2SI:
34468   case X86ISD::MCVTP2UI:
34469   case X86ISD::CVTTP2SI:
34470   case X86ISD::CVTTP2UI:
34471   case X86ISD::MCVTTP2SI:
34472   case X86ISD::MCVTTP2UI:
34473   case X86ISD::MCVTSI2P:
34474   case X86ISD::MCVTUI2P:
34475   case X86ISD::VFPROUND:
34476   case X86ISD::VMFPROUND:
34477   case X86ISD::CVTPS2PH:
34478   case X86ISD::MCVTPS2PH: {
34479     // Truncations/Conversions - upper elements are known zero.
34480     EVT SrcVT = Op.getOperand(0).getValueType();
34481     if (SrcVT.isVector()) {
34482       unsigned NumSrcElts = SrcVT.getVectorNumElements();
34483       if (NumElts > NumSrcElts &&
34484           DemandedElts.countTrailingZeros() >= NumSrcElts)
34485         Known.setAllZero();
34486     }
34487     break;
34488   }
34489   case X86ISD::STRICT_CVTTP2SI:
34490   case X86ISD::STRICT_CVTTP2UI:
34491   case X86ISD::STRICT_CVTSI2P:
34492   case X86ISD::STRICT_CVTUI2P:
34493   case X86ISD::STRICT_VFPROUND:
34494   case X86ISD::STRICT_CVTPS2PH: {
34495     // Strict Conversions - upper elements are known zero.
34496     EVT SrcVT = Op.getOperand(1).getValueType();
34497     if (SrcVT.isVector()) {
34498       unsigned NumSrcElts = SrcVT.getVectorNumElements();
34499       if (NumElts > NumSrcElts &&
34500           DemandedElts.countTrailingZeros() >= NumSrcElts)
34501         Known.setAllZero();
34502     }
34503     break;
34504   }
34505   case X86ISD::MOVQ2DQ: {
34506     // Move from MMX to XMM. Upper half of XMM should be 0.
34507     if (DemandedElts.countTrailingZeros() >= (NumElts / 2))
34508       Known.setAllZero();
34509     break;
34510   }
34511   }
34512 
34513   // Handle target shuffles.
34514   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
34515   if (isTargetShuffle(Opc)) {
34516     bool IsUnary;
34517     SmallVector<int, 64> Mask;
34518     SmallVector<SDValue, 2> Ops;
34519     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
34520                              IsUnary)) {
34521       unsigned NumOps = Ops.size();
34522       unsigned NumElts = VT.getVectorNumElements();
34523       if (Mask.size() == NumElts) {
34524         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
34525         Known.Zero.setAllBits(); Known.One.setAllBits();
34526         for (unsigned i = 0; i != NumElts; ++i) {
34527           if (!DemandedElts[i])
34528             continue;
34529           int M = Mask[i];
34530           if (M == SM_SentinelUndef) {
34531             // For UNDEF elements, we don't know anything about the common state
34532             // of the shuffle result.
34533             Known.resetAll();
34534             break;
34535           } else if (M == SM_SentinelZero) {
34536             Known.One.clearAllBits();
34537             continue;
34538           }
34539           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
34540                  "Shuffle index out of range");
34541 
34542           unsigned OpIdx = (unsigned)M / NumElts;
34543           unsigned EltIdx = (unsigned)M % NumElts;
34544           if (Ops[OpIdx].getValueType() != VT) {
34545             // TODO - handle target shuffle ops with different value types.
34546             Known.resetAll();
34547             break;
34548           }
34549           DemandedOps[OpIdx].setBit(EltIdx);
34550         }
34551         // Known bits are the values that are shared by every demanded element.
34552         for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
34553           if (!DemandedOps[i])
34554             continue;
34555           KnownBits Known2 =
34556               DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
34557           Known = KnownBits::commonBits(Known, Known2);
34558         }
34559       }
34560     }
34561   }
34562 }
34563 
34564 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
34565     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
34566     unsigned Depth) const {
34567   EVT VT = Op.getValueType();
34568   unsigned VTBits = VT.getScalarSizeInBits();
34569   unsigned Opcode = Op.getOpcode();
34570   switch (Opcode) {
34571   case X86ISD::SETCC_CARRY:
34572     // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
34573     return VTBits;
34574 
34575   case X86ISD::VTRUNC: {
34576     SDValue Src = Op.getOperand(0);
34577     MVT SrcVT = Src.getSimpleValueType();
34578     unsigned NumSrcBits = SrcVT.getScalarSizeInBits();
34579     assert(VTBits < NumSrcBits && "Illegal truncation input type");
34580     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
34581     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
34582     if (Tmp > (NumSrcBits - VTBits))
34583       return Tmp - (NumSrcBits - VTBits);
34584     return 1;
34585   }
34586 
34587   case X86ISD::PACKSS: {
34588     // PACKSS is just a truncation if the sign bits extend to the packed size.
34589     APInt DemandedLHS, DemandedRHS;
34590     getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
34591                         DemandedRHS);
34592 
34593     unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
34594     unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
34595     if (!!DemandedLHS)
34596       Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
34597     if (!!DemandedRHS)
34598       Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
34599     unsigned Tmp = std::min(Tmp0, Tmp1);
34600     if (Tmp > (SrcBits - VTBits))
34601       return Tmp - (SrcBits - VTBits);
34602     return 1;
34603   }
34604 
34605   case X86ISD::VSHLI: {
34606     SDValue Src = Op.getOperand(0);
34607     const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
34608     if (ShiftVal.uge(VTBits))
34609       return VTBits; // Shifted all bits out --> zero.
34610     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
34611     if (ShiftVal.uge(Tmp))
34612       return 1; // Shifted all sign bits out --> unknown.
34613     return Tmp - ShiftVal.getZExtValue();
34614   }
34615 
34616   case X86ISD::VSRAI: {
34617     SDValue Src = Op.getOperand(0);
34618     APInt ShiftVal = Op.getConstantOperandAPInt(1);
34619     if (ShiftVal.uge(VTBits - 1))
34620       return VTBits; // Sign splat.
34621     unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
34622     ShiftVal += Tmp;
34623     return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
34624   }
34625 
34626   case X86ISD::PCMPGT:
34627   case X86ISD::PCMPEQ:
34628   case X86ISD::CMPP:
34629   case X86ISD::VPCOM:
34630   case X86ISD::VPCOMU:
34631     // Vector compares return zero/all-bits result values.
34632     return VTBits;
34633 
34634   case X86ISD::ANDNP: {
34635     unsigned Tmp0 =
34636         DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
34637     if (Tmp0 == 1) return 1; // Early out.
34638     unsigned Tmp1 =
34639         DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
34640     return std::min(Tmp0, Tmp1);
34641   }
34642 
34643   case X86ISD::CMOV: {
34644     unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
34645     if (Tmp0 == 1) return 1;  // Early out.
34646     unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
34647     return std::min(Tmp0, Tmp1);
34648   }
34649   }
34650 
34651   // Handle target shuffles.
34652   // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
34653   if (isTargetShuffle(Opcode)) {
34654     bool IsUnary;
34655     SmallVector<int, 64> Mask;
34656     SmallVector<SDValue, 2> Ops;
34657     if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
34658                              IsUnary)) {
34659       unsigned NumOps = Ops.size();
34660       unsigned NumElts = VT.getVectorNumElements();
34661       if (Mask.size() == NumElts) {
34662         SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
34663         for (unsigned i = 0; i != NumElts; ++i) {
34664           if (!DemandedElts[i])
34665             continue;
34666           int M = Mask[i];
34667           if (M == SM_SentinelUndef) {
34668             // For UNDEF elements, we don't know anything about the common state
34669             // of the shuffle result.
34670             return 1;
34671           } else if (M == SM_SentinelZero) {
34672             // Zero = all sign bits.
34673             continue;
34674           }
34675           assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&
34676                  "Shuffle index out of range");
34677 
34678           unsigned OpIdx = (unsigned)M / NumElts;
34679           unsigned EltIdx = (unsigned)M % NumElts;
34680           if (Ops[OpIdx].getValueType() != VT) {
34681             // TODO - handle target shuffle ops with different value types.
34682             return 1;
34683           }
34684           DemandedOps[OpIdx].setBit(EltIdx);
34685         }
34686         unsigned Tmp0 = VTBits;
34687         for (unsigned i = 0; i != NumOps && Tmp0 > 1; ++i) {
34688           if (!DemandedOps[i])
34689             continue;
34690           unsigned Tmp1 =
34691               DAG.ComputeNumSignBits(Ops[i], DemandedOps[i], Depth + 1);
34692           Tmp0 = std::min(Tmp0, Tmp1);
34693         }
34694         return Tmp0;
34695       }
34696     }
34697   }
34698 
34699   // Fallback case.
34700   return 1;
34701 }
34702 
34703 SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
34704   if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
34705     return N->getOperand(0);
34706   return N;
34707 }
34708 
34709 // Helper to look for a normal load that can be narrowed into a vzload with the
34710 // specified VT and memory VT. Returns SDValue() on failure.
34711 static SDValue narrowLoadToVZLoad(LoadSDNode *LN, MVT MemVT, MVT VT,
34712                                   SelectionDAG &DAG) {
34713   // Can't if the load is volatile or atomic.
34714   if (!LN->isSimple())
34715     return SDValue();
34716 
34717   SDVTList Tys = DAG.getVTList(VT, MVT::Other);
34718   SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
34719   return DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, SDLoc(LN), Tys, Ops, MemVT,
34720                                  LN->getPointerInfo(), LN->getOriginalAlign(),
34721                                  LN->getMemOperand()->getFlags());
34722 }
34723 
34724 // Attempt to match a combined shuffle mask against supported unary shuffle
34725 // instructions.
34726 // TODO: Investigate sharing more of this with shuffle lowering.
34727 static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
34728                               bool AllowFloatDomain, bool AllowIntDomain,
34729                               SDValue &V1, const SDLoc &DL, SelectionDAG &DAG,
34730                               const X86Subtarget &Subtarget, unsigned &Shuffle,
34731                               MVT &SrcVT, MVT &DstVT) {
34732   unsigned NumMaskElts = Mask.size();
34733   unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
34734 
34735   // Match against a VZEXT_MOVL vXi32 zero-extending instruction.
34736   if (MaskEltSize == 32 && Mask[0] == 0) {
34737     if (isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) {
34738       Shuffle = X86ISD::VZEXT_MOVL;
34739       SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
34740       return true;
34741     }
34742     if (V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
34743         isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
34744       Shuffle = X86ISD::VZEXT_MOVL;
34745       SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
34746       return true;
34747     }
34748   }
34749 
34750   // Match against a ANY/ZERO_EXTEND_VECTOR_INREG instruction.
34751   // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
34752   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
34753                          (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
34754     unsigned MaxScale = 64 / MaskEltSize;
34755     for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
34756       bool MatchAny = true;
34757       bool MatchZero = true;
34758       unsigned NumDstElts = NumMaskElts / Scale;
34759       for (unsigned i = 0; i != NumDstElts && (MatchAny || MatchZero); ++i) {
34760         if (!isUndefOrEqual(Mask[i * Scale], (int)i)) {
34761           MatchAny = MatchZero = false;
34762           break;
34763         }
34764         MatchAny &= isUndefInRange(Mask, (i * Scale) + 1, Scale - 1);
34765         MatchZero &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
34766       }
34767       if (MatchAny || MatchZero) {
34768         assert(MatchZero && "Failed to match zext but matched aext?");
34769         unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
34770         MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
34771                                             MVT::getIntegerVT(MaskEltSize);
34772         SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
34773 
34774         if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
34775           V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
34776 
34777         Shuffle = unsigned(MatchAny ? ISD::ANY_EXTEND : ISD::ZERO_EXTEND);
34778         if (SrcVT.getVectorNumElements() != NumDstElts)
34779           Shuffle = getOpcode_EXTEND_VECTOR_INREG(Shuffle);
34780 
34781         DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
34782         DstVT = MVT::getVectorVT(DstVT, NumDstElts);
34783         return true;
34784       }
34785     }
34786   }
34787 
34788   // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
34789   if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2())) &&
34790       isUndefOrEqual(Mask[0], 0) &&
34791       isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
34792     Shuffle = X86ISD::VZEXT_MOVL;
34793     SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
34794     return true;
34795   }
34796 
34797   // Check if we have SSE3 which will let us use MOVDDUP etc. The
34798   // instructions are no slower than UNPCKLPD but has the option to
34799   // fold the input operand into even an unaligned memory load.
34800   if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
34801     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}, V1)) {
34802       Shuffle = X86ISD::MOVDDUP;
34803       SrcVT = DstVT = MVT::v2f64;
34804       return true;
34805     }
34806     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, V1)) {
34807       Shuffle = X86ISD::MOVSLDUP;
34808       SrcVT = DstVT = MVT::v4f32;
34809       return true;
34810     }
34811     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3}, V1)) {
34812       Shuffle = X86ISD::MOVSHDUP;
34813       SrcVT = DstVT = MVT::v4f32;
34814       return true;
34815     }
34816   }
34817 
34818   if (MaskVT.is256BitVector() && AllowFloatDomain) {
34819     assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles");
34820     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2}, V1)) {
34821       Shuffle = X86ISD::MOVDDUP;
34822       SrcVT = DstVT = MVT::v4f64;
34823       return true;
34824     }
34825     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1)) {
34826       Shuffle = X86ISD::MOVSLDUP;
34827       SrcVT = DstVT = MVT::v8f32;
34828       return true;
34829     }
34830     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1, 3, 3, 5, 5, 7, 7}, V1)) {
34831       Shuffle = X86ISD::MOVSHDUP;
34832       SrcVT = DstVT = MVT::v8f32;
34833       return true;
34834     }
34835   }
34836 
34837   if (MaskVT.is512BitVector() && AllowFloatDomain) {
34838     assert(Subtarget.hasAVX512() &&
34839            "AVX512 required for 512-bit vector shuffles");
34840     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0, 2, 2, 4, 4, 6, 6}, V1)) {
34841       Shuffle = X86ISD::MOVDDUP;
34842       SrcVT = DstVT = MVT::v8f64;
34843       return true;
34844     }
34845     if (isTargetShuffleEquivalent(
34846             MaskVT, Mask,
34847             {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14}, V1)) {
34848       Shuffle = X86ISD::MOVSLDUP;
34849       SrcVT = DstVT = MVT::v16f32;
34850       return true;
34851     }
34852     if (isTargetShuffleEquivalent(
34853             MaskVT, Mask,
34854             {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15}, V1)) {
34855       Shuffle = X86ISD::MOVSHDUP;
34856       SrcVT = DstVT = MVT::v16f32;
34857       return true;
34858     }
34859   }
34860 
34861   return false;
34862 }
34863 
34864 // Attempt to match a combined shuffle mask against supported unary immediate
34865 // permute instructions.
34866 // TODO: Investigate sharing more of this with shuffle lowering.
34867 static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
34868                                      const APInt &Zeroable,
34869                                      bool AllowFloatDomain, bool AllowIntDomain,
34870                                      const X86Subtarget &Subtarget,
34871                                      unsigned &Shuffle, MVT &ShuffleVT,
34872                                      unsigned &PermuteImm) {
34873   unsigned NumMaskElts = Mask.size();
34874   unsigned InputSizeInBits = MaskVT.getSizeInBits();
34875   unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
34876   MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
34877   bool ContainsZeros = isAnyZero(Mask);
34878 
34879   // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
34880   if (!ContainsZeros && MaskScalarSizeInBits == 64) {
34881     // Check for lane crossing permutes.
34882     if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
34883       // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
34884       if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
34885         Shuffle = X86ISD::VPERMI;
34886         ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
34887         PermuteImm = getV4X86ShuffleImm(Mask);
34888         return true;
34889       }
34890       if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
34891         SmallVector<int, 4> RepeatedMask;
34892         if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
34893           Shuffle = X86ISD::VPERMI;
34894           ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
34895           PermuteImm = getV4X86ShuffleImm(RepeatedMask);
34896           return true;
34897         }
34898       }
34899     } else if (AllowFloatDomain && Subtarget.hasAVX()) {
34900       // VPERMILPD can permute with a non-repeating shuffle.
34901       Shuffle = X86ISD::VPERMILPI;
34902       ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
34903       PermuteImm = 0;
34904       for (int i = 0, e = Mask.size(); i != e; ++i) {
34905         int M = Mask[i];
34906         if (M == SM_SentinelUndef)
34907           continue;
34908         assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index");
34909         PermuteImm |= (M & 1) << i;
34910       }
34911       return true;
34912     }
34913   }
34914 
34915   // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
34916   // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
34917   // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
34918   if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
34919       !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
34920     SmallVector<int, 4> RepeatedMask;
34921     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
34922       // Narrow the repeated mask to create 32-bit element permutes.
34923       SmallVector<int, 4> WordMask = RepeatedMask;
34924       if (MaskScalarSizeInBits == 64)
34925         narrowShuffleMaskElts(2, RepeatedMask, WordMask);
34926 
34927       Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
34928       ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
34929       ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
34930       PermuteImm = getV4X86ShuffleImm(WordMask);
34931       return true;
34932     }
34933   }
34934 
34935   // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
34936   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16 &&
34937       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
34938        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
34939        (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
34940     SmallVector<int, 4> RepeatedMask;
34941     if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
34942       ArrayRef<int> LoMask(RepeatedMask.data() + 0, 4);
34943       ArrayRef<int> HiMask(RepeatedMask.data() + 4, 4);
34944 
34945       // PSHUFLW: permute lower 4 elements only.
34946       if (isUndefOrInRange(LoMask, 0, 4) &&
34947           isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
34948         Shuffle = X86ISD::PSHUFLW;
34949         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
34950         PermuteImm = getV4X86ShuffleImm(LoMask);
34951         return true;
34952       }
34953 
34954       // PSHUFHW: permute upper 4 elements only.
34955       if (isUndefOrInRange(HiMask, 4, 8) &&
34956           isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
34957         // Offset the HiMask so that we can create the shuffle immediate.
34958         int OffsetHiMask[4];
34959         for (int i = 0; i != 4; ++i)
34960           OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
34961 
34962         Shuffle = X86ISD::PSHUFHW;
34963         ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
34964         PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
34965         return true;
34966       }
34967     }
34968   }
34969 
34970   // Attempt to match against byte/bit shifts.
34971   if (AllowIntDomain &&
34972       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
34973        (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
34974        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
34975     int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
34976                                        Mask, 0, Zeroable, Subtarget);
34977     if (0 < ShiftAmt && (!ShuffleVT.is512BitVector() || Subtarget.hasBWI() ||
34978                          32 <= ShuffleVT.getScalarSizeInBits())) {
34979       PermuteImm = (unsigned)ShiftAmt;
34980       return true;
34981     }
34982   }
34983 
34984   // Attempt to match against bit rotates.
34985   if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits < 64 &&
34986       ((MaskVT.is128BitVector() && Subtarget.hasXOP()) ||
34987        Subtarget.hasAVX512())) {
34988     int RotateAmt = matchShuffleAsBitRotate(ShuffleVT, MaskScalarSizeInBits,
34989                                             Subtarget, Mask);
34990     if (0 < RotateAmt) {
34991       Shuffle = X86ISD::VROTLI;
34992       PermuteImm = (unsigned)RotateAmt;
34993       return true;
34994     }
34995   }
34996 
34997   return false;
34998 }
34999 
35000 // Attempt to match a combined unary shuffle mask against supported binary
35001 // shuffle instructions.
35002 // TODO: Investigate sharing more of this with shuffle lowering.
35003 static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
35004                                bool AllowFloatDomain, bool AllowIntDomain,
35005                                SDValue &V1, SDValue &V2, const SDLoc &DL,
35006                                SelectionDAG &DAG, const X86Subtarget &Subtarget,
35007                                unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
35008                                bool IsUnary) {
35009   unsigned NumMaskElts = Mask.size();
35010   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
35011 
35012   if (MaskVT.is128BitVector()) {
35013     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 0}) && AllowFloatDomain) {
35014       V2 = V1;
35015       V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
35016       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
35017       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
35018       return true;
35019     }
35020     if (isTargetShuffleEquivalent(MaskVT, Mask, {1, 1}) && AllowFloatDomain) {
35021       V2 = V1;
35022       Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
35023       SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
35024       return true;
35025     }
35026     if (isTargetShuffleEquivalent(MaskVT, Mask, {0, 3}) &&
35027         Subtarget.hasSSE2() && (AllowFloatDomain || !Subtarget.hasSSE41())) {
35028       std::swap(V1, V2);
35029       Shuffle = X86ISD::MOVSD;
35030       SrcVT = DstVT = MVT::v2f64;
35031       return true;
35032     }
35033     if (isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3}) &&
35034         (AllowFloatDomain || !Subtarget.hasSSE41())) {
35035       Shuffle = X86ISD::MOVSS;
35036       SrcVT = DstVT = MVT::v4f32;
35037       return true;
35038     }
35039   }
35040 
35041   // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
35042   if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
35043       ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
35044       ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
35045     if (matchShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
35046                              Subtarget)) {
35047       DstVT = MaskVT;
35048       return true;
35049     }
35050   }
35051 
35052   // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
35053   if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
35054       (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
35055       (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
35056       (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
35057       (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
35058     if (matchShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL, DAG,
35059                               Subtarget)) {
35060       SrcVT = DstVT = MaskVT;
35061       if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
35062         SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
35063       return true;
35064     }
35065   }
35066 
35067   // Attempt to match against a OR if we're performing a blend shuffle and the
35068   // non-blended source element is zero in each case.
35069   if ((EltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
35070       (EltSizeInBits % V2.getScalarValueSizeInBits()) == 0) {
35071     bool IsBlend = true;
35072     unsigned NumV1Elts = V1.getValueType().getVectorNumElements();
35073     unsigned NumV2Elts = V2.getValueType().getVectorNumElements();
35074     unsigned Scale1 = NumV1Elts / NumMaskElts;
35075     unsigned Scale2 = NumV2Elts / NumMaskElts;
35076     APInt DemandedZeroV1 = APInt::getNullValue(NumV1Elts);
35077     APInt DemandedZeroV2 = APInt::getNullValue(NumV2Elts);
35078     for (unsigned i = 0; i != NumMaskElts; ++i) {
35079       int M = Mask[i];
35080       if (M == SM_SentinelUndef)
35081         continue;
35082       if (M == SM_SentinelZero) {
35083         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
35084         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
35085         continue;
35086       }
35087       if (M == (int)i) {
35088         DemandedZeroV2.setBits(i * Scale2, (i + 1) * Scale2);
35089         continue;
35090       }
35091       if (M == (int)(i + NumMaskElts)) {
35092         DemandedZeroV1.setBits(i * Scale1, (i + 1) * Scale1);
35093         continue;
35094       }
35095       IsBlend = false;
35096       break;
35097     }
35098     if (IsBlend &&
35099         DAG.computeKnownBits(V1, DemandedZeroV1).isZero() &&
35100         DAG.computeKnownBits(V2, DemandedZeroV2).isZero()) {
35101       Shuffle = ISD::OR;
35102       SrcVT = DstVT = MaskVT.changeTypeToInteger();
35103       return true;
35104     }
35105   }
35106 
35107   return false;
35108 }
35109 
35110 static bool matchBinaryPermuteShuffle(
35111     MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
35112     bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
35113     const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
35114     unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
35115   unsigned NumMaskElts = Mask.size();
35116   unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
35117 
35118   // Attempt to match against VALIGND/VALIGNQ rotate.
35119   if (AllowIntDomain && (EltSizeInBits == 64 || EltSizeInBits == 32) &&
35120       ((MaskVT.is128BitVector() && Subtarget.hasVLX()) ||
35121        (MaskVT.is256BitVector() && Subtarget.hasVLX()) ||
35122        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35123     if (!isAnyZero(Mask)) {
35124       int Rotation = matchShuffleAsElementRotate(V1, V2, Mask);
35125       if (0 < Rotation) {
35126         Shuffle = X86ISD::VALIGN;
35127         if (EltSizeInBits == 64)
35128           ShuffleVT = MVT::getVectorVT(MVT::i64, MaskVT.getSizeInBits() / 64);
35129         else
35130           ShuffleVT = MVT::getVectorVT(MVT::i32, MaskVT.getSizeInBits() / 32);
35131         PermuteImm = Rotation;
35132         return true;
35133       }
35134     }
35135   }
35136 
35137   // Attempt to match against PALIGNR byte rotate.
35138   if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
35139                          (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
35140                          (MaskVT.is512BitVector() && Subtarget.hasBWI()))) {
35141     int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
35142     if (0 < ByteRotation) {
35143       Shuffle = X86ISD::PALIGNR;
35144       ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
35145       PermuteImm = ByteRotation;
35146       return true;
35147     }
35148   }
35149 
35150   // Attempt to combine to X86ISD::BLENDI.
35151   if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
35152                             (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
35153       (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
35154     uint64_t BlendMask = 0;
35155     bool ForceV1Zero = false, ForceV2Zero = false;
35156     SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
35157     if (matchShuffleAsBlend(V1, V2, TargetMask, Zeroable, ForceV1Zero,
35158                             ForceV2Zero, BlendMask)) {
35159       if (MaskVT == MVT::v16i16) {
35160         // We can only use v16i16 PBLENDW if the lanes are repeated.
35161         SmallVector<int, 8> RepeatedMask;
35162         if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
35163                                         RepeatedMask)) {
35164           assert(RepeatedMask.size() == 8 &&
35165                  "Repeated mask size doesn't match!");
35166           PermuteImm = 0;
35167           for (int i = 0; i < 8; ++i)
35168             if (RepeatedMask[i] >= 8)
35169               PermuteImm |= 1 << i;
35170           V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
35171           V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
35172           Shuffle = X86ISD::BLENDI;
35173           ShuffleVT = MaskVT;
35174           return true;
35175         }
35176       } else {
35177         V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
35178         V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
35179         PermuteImm = (unsigned)BlendMask;
35180         Shuffle = X86ISD::BLENDI;
35181         ShuffleVT = MaskVT;
35182         return true;
35183       }
35184     }
35185   }
35186 
35187   // Attempt to combine to INSERTPS, but only if it has elements that need to
35188   // be set to zero.
35189   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
35190       MaskVT.is128BitVector() && isAnyZero(Mask) &&
35191       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
35192     Shuffle = X86ISD::INSERTPS;
35193     ShuffleVT = MVT::v4f32;
35194     return true;
35195   }
35196 
35197   // Attempt to combine to SHUFPD.
35198   if (AllowFloatDomain && EltSizeInBits == 64 &&
35199       ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
35200        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
35201        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35202     bool ForceV1Zero = false, ForceV2Zero = false;
35203     if (matchShuffleWithSHUFPD(MaskVT, V1, V2, ForceV1Zero, ForceV2Zero,
35204                                PermuteImm, Mask, Zeroable)) {
35205       V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
35206       V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
35207       Shuffle = X86ISD::SHUFP;
35208       ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
35209       return true;
35210     }
35211   }
35212 
35213   // Attempt to combine to SHUFPS.
35214   if (AllowFloatDomain && EltSizeInBits == 32 &&
35215       ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
35216        (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
35217        (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
35218     SmallVector<int, 4> RepeatedMask;
35219     if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
35220       // Match each half of the repeated mask, to determine if its just
35221       // referencing one of the vectors, is zeroable or entirely undef.
35222       auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
35223         int M0 = RepeatedMask[Offset];
35224         int M1 = RepeatedMask[Offset + 1];
35225 
35226         if (isUndefInRange(RepeatedMask, Offset, 2)) {
35227           return DAG.getUNDEF(MaskVT);
35228         } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
35229           S0 = (SM_SentinelUndef == M0 ? -1 : 0);
35230           S1 = (SM_SentinelUndef == M1 ? -1 : 1);
35231           return getZeroVector(MaskVT, Subtarget, DAG, DL);
35232         } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
35233           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
35234           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
35235           return V1;
35236         } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
35237           S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
35238           S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
35239           return V2;
35240         }
35241 
35242         return SDValue();
35243       };
35244 
35245       int ShufMask[4] = {-1, -1, -1, -1};
35246       SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
35247       SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
35248 
35249       if (Lo && Hi) {
35250         V1 = Lo;
35251         V2 = Hi;
35252         Shuffle = X86ISD::SHUFP;
35253         ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
35254         PermuteImm = getV4X86ShuffleImm(ShufMask);
35255         return true;
35256       }
35257     }
35258   }
35259 
35260   // Attempt to combine to INSERTPS more generally if X86ISD::SHUFP failed.
35261   if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
35262       MaskVT.is128BitVector() &&
35263       matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
35264     Shuffle = X86ISD::INSERTPS;
35265     ShuffleVT = MVT::v4f32;
35266     return true;
35267   }
35268 
35269   return false;
35270 }
35271 
35272 static SDValue combineX86ShuffleChainWithExtract(
35273     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
35274     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
35275     const X86Subtarget &Subtarget);
35276 
35277 /// Combine an arbitrary chain of shuffles into a single instruction if
35278 /// possible.
35279 ///
35280 /// This is the leaf of the recursive combine below. When we have found some
35281 /// chain of single-use x86 shuffle instructions and accumulated the combined
35282 /// shuffle mask represented by them, this will try to pattern match that mask
35283 /// into either a single instruction if there is a special purpose instruction
35284 /// for this operation, or into a PSHUFB instruction which is a fully general
35285 /// instruction but should only be used to replace chains over a certain depth.
35286 static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
35287                                       ArrayRef<int> BaseMask, int Depth,
35288                                       bool HasVariableMask,
35289                                       bool AllowVariableMask, SelectionDAG &DAG,
35290                                       const X86Subtarget &Subtarget) {
35291   assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!");
35292   assert((Inputs.size() == 1 || Inputs.size() == 2) &&
35293          "Unexpected number of shuffle inputs!");
35294 
35295   MVT RootVT = Root.getSimpleValueType();
35296   unsigned RootSizeInBits = RootVT.getSizeInBits();
35297   unsigned NumRootElts = RootVT.getVectorNumElements();
35298 
35299   // Canonicalize shuffle input op to the requested type.
35300   // TODO: Support cases where Op is smaller than VT.
35301   auto CanonicalizeShuffleInput = [&](MVT VT, SDValue Op) {
35302     return DAG.getBitcast(VT, Op);
35303   };
35304 
35305   // Find the inputs that enter the chain. Note that multiple uses are OK
35306   // here, we're not going to remove the operands we find.
35307   bool UnaryShuffle = (Inputs.size() == 1);
35308   SDValue V1 = peekThroughBitcasts(Inputs[0]);
35309   SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
35310                              : peekThroughBitcasts(Inputs[1]));
35311 
35312   MVT VT1 = V1.getSimpleValueType();
35313   MVT VT2 = V2.getSimpleValueType();
35314   assert(VT1.getSizeInBits() == RootSizeInBits &&
35315          VT2.getSizeInBits() == RootSizeInBits && "Vector size mismatch");
35316 
35317   SDLoc DL(Root);
35318   SDValue Res;
35319 
35320   unsigned NumBaseMaskElts = BaseMask.size();
35321   if (NumBaseMaskElts == 1) {
35322     assert(BaseMask[0] == 0 && "Invalid shuffle index found!");
35323     return CanonicalizeShuffleInput(RootVT, V1);
35324   }
35325 
35326   bool OptForSize = DAG.shouldOptForSize();
35327   unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
35328   bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
35329                      (RootVT.isFloatingPoint() && Depth >= 1) ||
35330                      (RootVT.is256BitVector() && !Subtarget.hasAVX2());
35331 
35332   // Don't combine if we are a AVX512/EVEX target and the mask element size
35333   // is different from the root element size - this would prevent writemasks
35334   // from being reused.
35335   bool IsMaskedShuffle = false;
35336   if (RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128)) {
35337     if (Root.hasOneUse() && Root->use_begin()->getOpcode() == ISD::VSELECT &&
35338         Root->use_begin()->getOperand(0).getScalarValueSizeInBits() == 1) {
35339       IsMaskedShuffle = true;
35340     }
35341   }
35342 
35343   // If we are shuffling a broadcast (and not introducing zeros) then
35344   // we can just use the broadcast directly. This works for smaller broadcast
35345   // elements as well as they already repeat across each mask element
35346   if (UnaryShuffle && isTargetShuffleSplat(V1) && !isAnyZero(BaseMask) &&
35347       (BaseMaskEltSizeInBits % V1.getScalarValueSizeInBits()) == 0 &&
35348       V1.getValueSizeInBits() >= RootSizeInBits) {
35349     return CanonicalizeShuffleInput(RootVT, V1);
35350   }
35351 
35352   // Handle 128/256-bit lane shuffles of 512-bit vectors.
35353   if (RootVT.is512BitVector() &&
35354       (NumBaseMaskElts == 2 || NumBaseMaskElts == 4)) {
35355     // If the upper subvectors are zeroable, then an extract+insert is more
35356     // optimal than using X86ISD::SHUF128. The insertion is free, even if it has
35357     // to zero the upper subvectors.
35358     if (isUndefOrZeroInRange(BaseMask, 1, NumBaseMaskElts - 1)) {
35359       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
35360         return SDValue(); // Nothing to do!
35361       assert(isInRange(BaseMask[0], 0, NumBaseMaskElts) &&
35362              "Unexpected lane shuffle");
35363       Res = CanonicalizeShuffleInput(RootVT, V1);
35364       unsigned SubIdx = BaseMask[0] * (NumRootElts / NumBaseMaskElts);
35365       bool UseZero = isAnyZero(BaseMask);
35366       Res = extractSubVector(Res, SubIdx, DAG, DL, BaseMaskEltSizeInBits);
35367       return widenSubVector(Res, UseZero, Subtarget, DAG, DL, RootSizeInBits);
35368     }
35369 
35370     // Narrow shuffle mask to v4x128.
35371     SmallVector<int, 4> Mask;
35372     assert((BaseMaskEltSizeInBits % 128) == 0 && "Illegal mask size");
35373     narrowShuffleMaskElts(BaseMaskEltSizeInBits / 128, BaseMask, Mask);
35374 
35375     // Try to lower to vshuf64x2/vshuf32x4.
35376     auto MatchSHUF128 = [&](MVT ShuffleVT, const SDLoc &DL, ArrayRef<int> Mask,
35377                             SDValue V1, SDValue V2, SelectionDAG &DAG) {
35378       unsigned PermMask = 0;
35379       // Insure elements came from the same Op.
35380       SDValue Ops[2] = {DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT)};
35381       for (int i = 0; i < 4; ++i) {
35382         assert(Mask[i] >= -1 && "Illegal shuffle sentinel value");
35383         if (Mask[i] < 0)
35384           continue;
35385 
35386         SDValue Op = Mask[i] >= 4 ? V2 : V1;
35387         unsigned OpIndex = i / 2;
35388         if (Ops[OpIndex].isUndef())
35389           Ops[OpIndex] = Op;
35390         else if (Ops[OpIndex] != Op)
35391           return SDValue();
35392 
35393         // Convert the 128-bit shuffle mask selection values into 128-bit
35394         // selection bits defined by a vshuf64x2 instruction's immediate control
35395         // byte.
35396         PermMask |= (Mask[i] % 4) << (i * 2);
35397       }
35398 
35399       return DAG.getNode(X86ISD::SHUF128, DL, ShuffleVT,
35400                          CanonicalizeShuffleInput(ShuffleVT, Ops[0]),
35401                          CanonicalizeShuffleInput(ShuffleVT, Ops[1]),
35402                          DAG.getTargetConstant(PermMask, DL, MVT::i8));
35403     };
35404 
35405     // FIXME: Is there a better way to do this? is256BitLaneRepeatedShuffleMask
35406     // doesn't work because our mask is for 128 bits and we don't have an MVT
35407     // to match that.
35408     bool PreferPERMQ =
35409         UnaryShuffle && isUndefOrInRange(Mask[0], 0, 2) &&
35410         isUndefOrInRange(Mask[1], 0, 2) && isUndefOrInRange(Mask[2], 2, 4) &&
35411         isUndefOrInRange(Mask[3], 2, 4) &&
35412         (Mask[0] < 0 || Mask[2] < 0 || Mask[0] == (Mask[2] % 2)) &&
35413         (Mask[1] < 0 || Mask[3] < 0 || Mask[1] == (Mask[3] % 2));
35414 
35415     if (!isAnyZero(Mask) && !PreferPERMQ) {
35416       if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
35417         return SDValue(); // Nothing to do!
35418       MVT ShuffleVT = (FloatDomain ? MVT::v8f64 : MVT::v8i64);
35419       if (SDValue V = MatchSHUF128(ShuffleVT, DL, Mask, V1, V2, DAG))
35420         return DAG.getBitcast(RootVT, V);
35421     }
35422   }
35423 
35424   // Handle 128-bit lane shuffles of 256-bit vectors.
35425   if (RootVT.is256BitVector() && NumBaseMaskElts == 2) {
35426     // If the upper half is zeroable, then an extract+insert is more optimal
35427     // than using X86ISD::VPERM2X128. The insertion is free, even if it has to
35428     // zero the upper half.
35429     if (isUndefOrZero(BaseMask[1])) {
35430       if (Depth == 0 && Root.getOpcode() == ISD::INSERT_SUBVECTOR)
35431         return SDValue(); // Nothing to do!
35432       assert(isInRange(BaseMask[0], 0, 2) && "Unexpected lane shuffle");
35433       Res = CanonicalizeShuffleInput(RootVT, V1);
35434       Res = extract128BitVector(Res, BaseMask[0] * (NumRootElts / 2), DAG, DL);
35435       return widenSubVector(Res, BaseMask[1] == SM_SentinelZero, Subtarget, DAG,
35436                             DL, 256);
35437     }
35438 
35439     if (Depth == 0 && Root.getOpcode() == X86ISD::VPERM2X128)
35440       return SDValue(); // Nothing to do!
35441 
35442     // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
35443     // we need to use the zeroing feature.
35444     // Prefer blends for sequential shuffles unless we are optimizing for size.
35445     if (UnaryShuffle &&
35446         !(Subtarget.hasAVX2() && isUndefOrInRange(BaseMask, 0, 2)) &&
35447         (OptForSize || !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0))) {
35448       unsigned PermMask = 0;
35449       PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
35450       PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
35451       return DAG.getNode(
35452           X86ISD::VPERM2X128, DL, RootVT, CanonicalizeShuffleInput(RootVT, V1),
35453           DAG.getUNDEF(RootVT), DAG.getTargetConstant(PermMask, DL, MVT::i8));
35454     }
35455 
35456     if (Depth == 0 && Root.getOpcode() == X86ISD::SHUF128)
35457       return SDValue(); // Nothing to do!
35458 
35459     // TODO - handle AVX512VL cases with X86ISD::SHUF128.
35460     if (!UnaryShuffle && !IsMaskedShuffle) {
35461       assert(llvm::all_of(BaseMask, [](int M) { return 0 <= M && M < 4; }) &&
35462              "Unexpected shuffle sentinel value");
35463       // Prefer blends to X86ISD::VPERM2X128.
35464       if (!((BaseMask[0] == 0 && BaseMask[1] == 3) ||
35465             (BaseMask[0] == 2 && BaseMask[1] == 1))) {
35466         unsigned PermMask = 0;
35467         PermMask |= ((BaseMask[0] & 3) << 0);
35468         PermMask |= ((BaseMask[1] & 3) << 4);
35469         SDValue LHS = isInRange(BaseMask[0], 0, 2) ? V1 : V2;
35470         SDValue RHS = isInRange(BaseMask[1], 0, 2) ? V1 : V2;
35471         return DAG.getNode(X86ISD::VPERM2X128, DL, RootVT,
35472                           CanonicalizeShuffleInput(RootVT, LHS),
35473                           CanonicalizeShuffleInput(RootVT, RHS),
35474                           DAG.getTargetConstant(PermMask, DL, MVT::i8));
35475       }
35476     }
35477   }
35478 
35479   // For masks that have been widened to 128-bit elements or more,
35480   // narrow back down to 64-bit elements.
35481   SmallVector<int, 64> Mask;
35482   if (BaseMaskEltSizeInBits > 64) {
35483     assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size");
35484     int MaskScale = BaseMaskEltSizeInBits / 64;
35485     narrowShuffleMaskElts(MaskScale, BaseMask, Mask);
35486   } else {
35487     Mask.assign(BaseMask.begin(), BaseMask.end());
35488   }
35489 
35490   // For masked shuffles, we're trying to match the root width for better
35491   // writemask folding, attempt to scale the mask.
35492   // TODO - variable shuffles might need this to be widened again.
35493   if (IsMaskedShuffle && NumRootElts > Mask.size()) {
35494     assert((NumRootElts % Mask.size()) == 0 && "Illegal mask size");
35495     int MaskScale = NumRootElts / Mask.size();
35496     SmallVector<int, 64> ScaledMask;
35497     narrowShuffleMaskElts(MaskScale, Mask, ScaledMask);
35498     Mask = std::move(ScaledMask);
35499   }
35500 
35501   unsigned NumMaskElts = Mask.size();
35502   unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
35503 
35504   // Determine the effective mask value type.
35505   FloatDomain &= (32 <= MaskEltSizeInBits);
35506   MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
35507                            : MVT::getIntegerVT(MaskEltSizeInBits);
35508   MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
35509 
35510   // Only allow legal mask types.
35511   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
35512     return SDValue();
35513 
35514   // Attempt to match the mask against known shuffle patterns.
35515   MVT ShuffleSrcVT, ShuffleVT;
35516   unsigned Shuffle, PermuteImm;
35517 
35518   // Which shuffle domains are permitted?
35519   // Permit domain crossing at higher combine depths.
35520   // TODO: Should we indicate which domain is preferred if both are allowed?
35521   bool AllowFloatDomain = FloatDomain || (Depth >= 3);
35522   bool AllowIntDomain = (!FloatDomain || (Depth >= 3)) && Subtarget.hasSSE2() &&
35523                         (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
35524 
35525   // Determine zeroable mask elements.
35526   APInt KnownUndef, KnownZero;
35527   resolveZeroablesFromTargetShuffle(Mask, KnownUndef, KnownZero);
35528   APInt Zeroable = KnownUndef | KnownZero;
35529 
35530   if (UnaryShuffle) {
35531     // Attempt to match against broadcast-from-vector.
35532     // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
35533     if ((Subtarget.hasAVX2() ||
35534          (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits)) &&
35535         (!IsMaskedShuffle || NumRootElts == NumMaskElts)) {
35536       if (isUndefOrEqual(Mask, 0)) {
35537         if (V1.getValueType() == MaskVT &&
35538             V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
35539             MayFoldLoad(V1.getOperand(0))) {
35540           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
35541             return SDValue(); // Nothing to do!
35542           Res = V1.getOperand(0);
35543           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
35544           return DAG.getBitcast(RootVT, Res);
35545         }
35546         if (Subtarget.hasAVX2()) {
35547           if (Depth == 0 && Root.getOpcode() == X86ISD::VBROADCAST)
35548             return SDValue(); // Nothing to do!
35549           Res = CanonicalizeShuffleInput(MaskVT, V1);
35550           Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
35551           return DAG.getBitcast(RootVT, Res);
35552         }
35553       }
35554     }
35555 
35556     SDValue NewV1 = V1; // Save operand in case early exit happens.
35557     if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
35558                           DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
35559                           ShuffleVT) &&
35560         (!IsMaskedShuffle ||
35561          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
35562       if (Depth == 0 && Root.getOpcode() == Shuffle)
35563         return SDValue(); // Nothing to do!
35564       Res = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
35565       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
35566       return DAG.getBitcast(RootVT, Res);
35567     }
35568 
35569     if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
35570                                  AllowIntDomain, Subtarget, Shuffle, ShuffleVT,
35571                                  PermuteImm) &&
35572         (!IsMaskedShuffle ||
35573          (NumRootElts == ShuffleVT.getVectorNumElements()))) {
35574       if (Depth == 0 && Root.getOpcode() == Shuffle)
35575         return SDValue(); // Nothing to do!
35576       Res = CanonicalizeShuffleInput(ShuffleVT, V1);
35577       Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
35578                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
35579       return DAG.getBitcast(RootVT, Res);
35580     }
35581   }
35582 
35583   // Attempt to combine to INSERTPS, but only if the inserted element has come
35584   // from a scalar.
35585   // TODO: Handle other insertions here as well?
35586   if (!UnaryShuffle && AllowFloatDomain && RootSizeInBits == 128 &&
35587       Subtarget.hasSSE41() &&
35588       !isTargetShuffleEquivalent(MaskVT, Mask, {4, 1, 2, 3})) {
35589     if (MaskEltSizeInBits == 32) {
35590       SDValue SrcV1 = V1, SrcV2 = V2;
35591       if (matchShuffleAsInsertPS(SrcV1, SrcV2, PermuteImm, Zeroable, Mask,
35592                                  DAG) &&
35593           SrcV2.getOpcode() == ISD::SCALAR_TO_VECTOR) {
35594         if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
35595           return SDValue(); // Nothing to do!
35596         Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
35597                           CanonicalizeShuffleInput(MVT::v4f32, SrcV1),
35598                           CanonicalizeShuffleInput(MVT::v4f32, SrcV2),
35599                           DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
35600         return DAG.getBitcast(RootVT, Res);
35601       }
35602     }
35603     if (MaskEltSizeInBits == 64 &&
35604         isTargetShuffleEquivalent(MaskVT, Mask, {0, 2}) &&
35605         V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
35606         V2.getScalarValueSizeInBits() <= 32) {
35607       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTPS)
35608         return SDValue(); // Nothing to do!
35609       PermuteImm = (/*DstIdx*/2 << 4) | (/*SrcIdx*/0 << 0);
35610       Res = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32,
35611                         CanonicalizeShuffleInput(MVT::v4f32, V1),
35612                         CanonicalizeShuffleInput(MVT::v4f32, V2),
35613                         DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
35614       return DAG.getBitcast(RootVT, Res);
35615     }
35616   }
35617 
35618   SDValue NewV1 = V1; // Save operands in case early exit happens.
35619   SDValue NewV2 = V2;
35620   if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
35621                          NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
35622                          ShuffleVT, UnaryShuffle) &&
35623       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
35624     if (Depth == 0 && Root.getOpcode() == Shuffle)
35625       return SDValue(); // Nothing to do!
35626     NewV1 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV1);
35627     NewV2 = CanonicalizeShuffleInput(ShuffleSrcVT, NewV2);
35628     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
35629     return DAG.getBitcast(RootVT, Res);
35630   }
35631 
35632   NewV1 = V1; // Save operands in case early exit happens.
35633   NewV2 = V2;
35634   if (matchBinaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
35635                                 AllowIntDomain, NewV1, NewV2, DL, DAG,
35636                                 Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
35637       (!IsMaskedShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
35638     if (Depth == 0 && Root.getOpcode() == Shuffle)
35639       return SDValue(); // Nothing to do!
35640     NewV1 = CanonicalizeShuffleInput(ShuffleVT, NewV1);
35641     NewV2 = CanonicalizeShuffleInput(ShuffleVT, NewV2);
35642     Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
35643                       DAG.getTargetConstant(PermuteImm, DL, MVT::i8));
35644     return DAG.getBitcast(RootVT, Res);
35645   }
35646 
35647   // Typically from here on, we need an integer version of MaskVT.
35648   MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
35649   IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
35650 
35651   // Annoyingly, SSE4A instructions don't map into the above match helpers.
35652   if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
35653     uint64_t BitLen, BitIdx;
35654     if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
35655                             Zeroable)) {
35656       if (Depth == 0 && Root.getOpcode() == X86ISD::EXTRQI)
35657         return SDValue(); // Nothing to do!
35658       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
35659       Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
35660                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
35661                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
35662       return DAG.getBitcast(RootVT, Res);
35663     }
35664 
35665     if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
35666       if (Depth == 0 && Root.getOpcode() == X86ISD::INSERTQI)
35667         return SDValue(); // Nothing to do!
35668       V1 = CanonicalizeShuffleInput(IntMaskVT, V1);
35669       V2 = CanonicalizeShuffleInput(IntMaskVT, V2);
35670       Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
35671                         DAG.getTargetConstant(BitLen, DL, MVT::i8),
35672                         DAG.getTargetConstant(BitIdx, DL, MVT::i8));
35673       return DAG.getBitcast(RootVT, Res);
35674     }
35675   }
35676 
35677   // Match shuffle against TRUNCATE patterns.
35678   if (AllowIntDomain && MaskEltSizeInBits < 64 && Subtarget.hasAVX512()) {
35679     // Match against a VTRUNC instruction, accounting for src/dst sizes.
35680     if (matchShuffleAsVTRUNC(ShuffleSrcVT, ShuffleVT, IntMaskVT, Mask, Zeroable,
35681                              Subtarget)) {
35682       bool IsTRUNCATE = ShuffleVT.getVectorNumElements() ==
35683                         ShuffleSrcVT.getVectorNumElements();
35684       unsigned Opc =
35685           IsTRUNCATE ? (unsigned)ISD::TRUNCATE : (unsigned)X86ISD::VTRUNC;
35686       if (Depth == 0 && Root.getOpcode() == Opc)
35687         return SDValue(); // Nothing to do!
35688       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
35689       Res = DAG.getNode(Opc, DL, ShuffleVT, V1);
35690       if (ShuffleVT.getSizeInBits() < RootSizeInBits)
35691         Res = widenSubVector(Res, true, Subtarget, DAG, DL, RootSizeInBits);
35692       return DAG.getBitcast(RootVT, Res);
35693     }
35694 
35695     // Do we need a more general binary truncation pattern?
35696     if (RootSizeInBits < 512 &&
35697         ((RootVT.is256BitVector() && Subtarget.useAVX512Regs()) ||
35698          (RootVT.is128BitVector() && Subtarget.hasVLX())) &&
35699         (MaskEltSizeInBits > 8 || Subtarget.hasBWI()) &&
35700         isSequentialOrUndefInRange(Mask, 0, NumMaskElts, 0, 2)) {
35701       if (Depth == 0 && Root.getOpcode() == ISD::TRUNCATE)
35702         return SDValue(); // Nothing to do!
35703       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
35704       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts / 2);
35705       V1 = CanonicalizeShuffleInput(ShuffleSrcVT, V1);
35706       V2 = CanonicalizeShuffleInput(ShuffleSrcVT, V2);
35707       ShuffleSrcVT = MVT::getIntegerVT(MaskEltSizeInBits * 2);
35708       ShuffleSrcVT = MVT::getVectorVT(ShuffleSrcVT, NumMaskElts);
35709       Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShuffleSrcVT, V1, V2);
35710       Res = DAG.getNode(ISD::TRUNCATE, DL, IntMaskVT, Res);
35711       return DAG.getBitcast(RootVT, Res);
35712     }
35713   }
35714 
35715   // Don't try to re-form single instruction chains under any circumstances now
35716   // that we've done encoding canonicalization for them.
35717   if (Depth < 1)
35718     return SDValue();
35719 
35720   // Depth threshold above which we can efficiently use variable mask shuffles.
35721   int VariableShuffleDepth = Subtarget.hasFastVariableShuffle() ? 1 : 2;
35722   AllowVariableMask &= (Depth >= VariableShuffleDepth) || HasVariableMask;
35723   // VPERMI2W/VPERMI2B are 3 uops on Skylake and Icelake so we require a
35724   // higher depth before combining them.
35725   bool AllowBWIVPERMV3 = (Depth >= 2 || HasVariableMask);
35726 
35727   bool MaskContainsZeros = isAnyZero(Mask);
35728 
35729   if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
35730     // If we have a single input lane-crossing shuffle then lower to VPERMV.
35731     if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros) {
35732       if (Subtarget.hasAVX2() &&
35733           (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) {
35734         SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
35735         Res = CanonicalizeShuffleInput(MaskVT, V1);
35736         Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
35737         return DAG.getBitcast(RootVT, Res);
35738       }
35739       // AVX512 variants (non-VLX will pad to 512-bit shuffles).
35740       if ((Subtarget.hasAVX512() &&
35741            (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
35742             MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
35743           (Subtarget.hasBWI() &&
35744            (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
35745           (Subtarget.hasVBMI() &&
35746            (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8))) {
35747         V1 = CanonicalizeShuffleInput(MaskVT, V1);
35748         V2 = DAG.getUNDEF(MaskVT);
35749         Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
35750         return DAG.getBitcast(RootVT, Res);
35751       }
35752     }
35753 
35754     // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
35755     // vector as the second source (non-VLX will pad to 512-bit shuffles).
35756     if (UnaryShuffle && AllowVariableMask &&
35757         ((Subtarget.hasAVX512() &&
35758           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
35759            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
35760            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32 ||
35761            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
35762          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
35763           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
35764          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
35765           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
35766       // Adjust shuffle mask - replace SM_SentinelZero with second source index.
35767       for (unsigned i = 0; i != NumMaskElts; ++i)
35768         if (Mask[i] == SM_SentinelZero)
35769           Mask[i] = NumMaskElts + i;
35770       V1 = CanonicalizeShuffleInput(MaskVT, V1);
35771       V2 = getZeroVector(MaskVT, Subtarget, DAG, DL);
35772       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
35773       return DAG.getBitcast(RootVT, Res);
35774     }
35775 
35776     // If that failed and either input is extracted then try to combine as a
35777     // shuffle with the larger type.
35778     if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
35779             Inputs, Root, BaseMask, Depth, HasVariableMask, AllowVariableMask,
35780             DAG, Subtarget))
35781       return WideShuffle;
35782 
35783     // If we have a dual input lane-crossing shuffle then lower to VPERMV3,
35784     // (non-VLX will pad to 512-bit shuffles).
35785     if (AllowVariableMask && !MaskContainsZeros &&
35786         ((Subtarget.hasAVX512() &&
35787           (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
35788            MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
35789            MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32 ||
35790            MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
35791          (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
35792           (MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
35793          (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
35794           (MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
35795       V1 = CanonicalizeShuffleInput(MaskVT, V1);
35796       V2 = CanonicalizeShuffleInput(MaskVT, V2);
35797       Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
35798       return DAG.getBitcast(RootVT, Res);
35799     }
35800     return SDValue();
35801   }
35802 
35803   // See if we can combine a single input shuffle with zeros to a bit-mask,
35804   // which is much simpler than any shuffle.
35805   if (UnaryShuffle && MaskContainsZeros && AllowVariableMask &&
35806       isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
35807       DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
35808     APInt Zero = APInt::getNullValue(MaskEltSizeInBits);
35809     APInt AllOnes = APInt::getAllOnesValue(MaskEltSizeInBits);
35810     APInt UndefElts(NumMaskElts, 0);
35811     SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
35812     for (unsigned i = 0; i != NumMaskElts; ++i) {
35813       int M = Mask[i];
35814       if (M == SM_SentinelUndef) {
35815         UndefElts.setBit(i);
35816         continue;
35817       }
35818       if (M == SM_SentinelZero)
35819         continue;
35820       EltBits[i] = AllOnes;
35821     }
35822     SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
35823     Res = CanonicalizeShuffleInput(MaskVT, V1);
35824     unsigned AndOpcode =
35825         MaskVT.isFloatingPoint() ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
35826     Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
35827     return DAG.getBitcast(RootVT, Res);
35828   }
35829 
35830   // If we have a single input shuffle with different shuffle patterns in the
35831   // the 128-bit lanes use the variable mask to VPERMILPS.
35832   // TODO Combine other mask types at higher depths.
35833   if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
35834       ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
35835        (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
35836     SmallVector<SDValue, 16> VPermIdx;
35837     for (int M : Mask) {
35838       SDValue Idx =
35839           M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
35840       VPermIdx.push_back(Idx);
35841     }
35842     SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
35843     Res = CanonicalizeShuffleInput(MaskVT, V1);
35844     Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
35845     return DAG.getBitcast(RootVT, Res);
35846   }
35847 
35848   // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
35849   // to VPERMIL2PD/VPERMIL2PS.
35850   if (AllowVariableMask && Subtarget.hasXOP() &&
35851       (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
35852        MaskVT == MVT::v8f32)) {
35853     // VPERMIL2 Operation.
35854     // Bits[3] - Match Bit.
35855     // Bits[2:1] - (Per Lane) PD Shuffle Mask.
35856     // Bits[2:0] - (Per Lane) PS Shuffle Mask.
35857     unsigned NumLanes = MaskVT.getSizeInBits() / 128;
35858     unsigned NumEltsPerLane = NumMaskElts / NumLanes;
35859     SmallVector<int, 8> VPerm2Idx;
35860     unsigned M2ZImm = 0;
35861     for (int M : Mask) {
35862       if (M == SM_SentinelUndef) {
35863         VPerm2Idx.push_back(-1);
35864         continue;
35865       }
35866       if (M == SM_SentinelZero) {
35867         M2ZImm = 2;
35868         VPerm2Idx.push_back(8);
35869         continue;
35870       }
35871       int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
35872       Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
35873       VPerm2Idx.push_back(Index);
35874     }
35875     V1 = CanonicalizeShuffleInput(MaskVT, V1);
35876     V2 = CanonicalizeShuffleInput(MaskVT, V2);
35877     SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
35878     Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
35879                       DAG.getTargetConstant(M2ZImm, DL, MVT::i8));
35880     return DAG.getBitcast(RootVT, Res);
35881   }
35882 
35883   // If we have 3 or more shuffle instructions or a chain involving a variable
35884   // mask, we can replace them with a single PSHUFB instruction profitably.
35885   // Intel's manuals suggest only using PSHUFB if doing so replacing 5
35886   // instructions, but in practice PSHUFB tends to be *very* fast so we're
35887   // more aggressive.
35888   if (UnaryShuffle && AllowVariableMask &&
35889       ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
35890        (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
35891        (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
35892     SmallVector<SDValue, 16> PSHUFBMask;
35893     int NumBytes = RootVT.getSizeInBits() / 8;
35894     int Ratio = NumBytes / NumMaskElts;
35895     for (int i = 0; i < NumBytes; ++i) {
35896       int M = Mask[i / Ratio];
35897       if (M == SM_SentinelUndef) {
35898         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
35899         continue;
35900       }
35901       if (M == SM_SentinelZero) {
35902         PSHUFBMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
35903         continue;
35904       }
35905       M = Ratio * M + i % Ratio;
35906       assert((M / 16) == (i / 16) && "Lane crossing detected");
35907       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
35908     }
35909     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
35910     Res = CanonicalizeShuffleInput(ByteVT, V1);
35911     SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
35912     Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
35913     return DAG.getBitcast(RootVT, Res);
35914   }
35915 
35916   // With XOP, if we have a 128-bit binary input shuffle we can always combine
35917   // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
35918   // slower than PSHUFB on targets that support both.
35919   if (AllowVariableMask && RootVT.is128BitVector() && Subtarget.hasXOP()) {
35920     // VPPERM Mask Operation
35921     // Bits[4:0] - Byte Index (0 - 31)
35922     // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
35923     SmallVector<SDValue, 16> VPPERMMask;
35924     int NumBytes = 16;
35925     int Ratio = NumBytes / NumMaskElts;
35926     for (int i = 0; i < NumBytes; ++i) {
35927       int M = Mask[i / Ratio];
35928       if (M == SM_SentinelUndef) {
35929         VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
35930         continue;
35931       }
35932       if (M == SM_SentinelZero) {
35933         VPPERMMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
35934         continue;
35935       }
35936       M = Ratio * M + i % Ratio;
35937       VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
35938     }
35939     MVT ByteVT = MVT::v16i8;
35940     V1 = CanonicalizeShuffleInput(ByteVT, V1);
35941     V2 = CanonicalizeShuffleInput(ByteVT, V2);
35942     SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
35943     Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
35944     return DAG.getBitcast(RootVT, Res);
35945   }
35946 
35947   // If that failed and either input is extracted then try to combine as a
35948   // shuffle with the larger type.
35949   if (SDValue WideShuffle = combineX86ShuffleChainWithExtract(
35950           Inputs, Root, BaseMask, Depth, HasVariableMask, AllowVariableMask,
35951           DAG, Subtarget))
35952     return WideShuffle;
35953 
35954   // If we have a dual input shuffle then lower to VPERMV3,
35955   // (non-VLX will pad to 512-bit shuffles)
35956   if (!UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
35957       ((Subtarget.hasAVX512() &&
35958         (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v8f64 ||
35959          MaskVT == MVT::v2i64 || MaskVT == MVT::v4i64 || MaskVT == MVT::v8i64 ||
35960          MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 || MaskVT == MVT::v8f32 ||
35961          MaskVT == MVT::v8i32 || MaskVT == MVT::v16f32 ||
35962          MaskVT == MVT::v16i32)) ||
35963        (Subtarget.hasBWI() && AllowBWIVPERMV3 &&
35964         (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16 || MaskVT == MVT::v32i16)) ||
35965        (Subtarget.hasVBMI() && AllowBWIVPERMV3 &&
35966         (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8 || MaskVT == MVT::v64i8)))) {
35967     V1 = CanonicalizeShuffleInput(MaskVT, V1);
35968     V2 = CanonicalizeShuffleInput(MaskVT, V2);
35969     Res = lowerShuffleWithPERMV(DL, MaskVT, Mask, V1, V2, Subtarget, DAG);
35970     return DAG.getBitcast(RootVT, Res);
35971   }
35972 
35973   // Failed to find any combines.
35974   return SDValue();
35975 }
35976 
35977 // Combine an arbitrary chain of shuffles + extract_subvectors into a single
35978 // instruction if possible.
35979 //
35980 // Wrapper for combineX86ShuffleChain that extends the shuffle mask to a larger
35981 // type size to attempt to combine:
35982 // shuffle(extract_subvector(x,c1),extract_subvector(y,c2),m1)
35983 // -->
35984 // extract_subvector(shuffle(x,y,m2),0)
35985 static SDValue combineX86ShuffleChainWithExtract(
35986     ArrayRef<SDValue> Inputs, SDValue Root, ArrayRef<int> BaseMask, int Depth,
35987     bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
35988     const X86Subtarget &Subtarget) {
35989   unsigned NumMaskElts = BaseMask.size();
35990   unsigned NumInputs = Inputs.size();
35991   if (NumInputs == 0)
35992     return SDValue();
35993 
35994   EVT RootVT = Root.getValueType();
35995   unsigned RootSizeInBits = RootVT.getSizeInBits();
35996   assert((RootSizeInBits % NumMaskElts) == 0 && "Unexpected root shuffle mask");
35997 
35998   SmallVector<SDValue, 4> WideInputs(Inputs.begin(), Inputs.end());
35999   SmallVector<unsigned, 4> Offsets(NumInputs, 0);
36000 
36001   // Peek through subvectors.
36002   // TODO: Support inter-mixed EXTRACT_SUBVECTORs + BITCASTs?
36003   unsigned WideSizeInBits = RootSizeInBits;
36004   for (unsigned i = 0; i != NumInputs; ++i) {
36005     SDValue &Src = WideInputs[i];
36006     unsigned &Offset = Offsets[i];
36007     Src = peekThroughBitcasts(Src);
36008     EVT BaseVT = Src.getValueType();
36009     while (Src.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
36010       Offset += Src.getConstantOperandVal(1);
36011       Src = Src.getOperand(0);
36012     }
36013     WideSizeInBits = std::max(WideSizeInBits,
36014                               (unsigned)Src.getValueSizeInBits());
36015     assert((Offset % BaseVT.getVectorNumElements()) == 0 &&
36016            "Unexpected subvector extraction");
36017     Offset /= BaseVT.getVectorNumElements();
36018     Offset *= NumMaskElts;
36019   }
36020 
36021   // Bail if we're always extracting from the lowest subvectors,
36022   // combineX86ShuffleChain should match this for the current width.
36023   if (llvm::all_of(Offsets, [](unsigned Offset) { return Offset == 0; }))
36024     return SDValue();
36025 
36026   unsigned Scale = WideSizeInBits / RootSizeInBits;
36027   assert((WideSizeInBits % RootSizeInBits) == 0 &&
36028          "Unexpected subvector extraction");
36029 
36030   // If the src vector types aren't the same, see if we can extend
36031   // them to match each other.
36032   // TODO: Support different scalar types?
36033   EVT WideSVT = WideInputs[0].getValueType().getScalarType();
36034   if (llvm::any_of(WideInputs, [&WideSVT, &DAG](SDValue Op) {
36035         return !DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()) ||
36036                Op.getValueType().getScalarType() != WideSVT;
36037       }))
36038     return SDValue();
36039 
36040   for (SDValue &NewInput : WideInputs) {
36041     assert((WideSizeInBits % NewInput.getValueSizeInBits()) == 0 &&
36042            "Shuffle vector size mismatch");
36043     if (WideSizeInBits > NewInput.getValueSizeInBits())
36044       NewInput = widenSubVector(NewInput, false, Subtarget, DAG,
36045                                 SDLoc(NewInput), WideSizeInBits);
36046     assert(WideSizeInBits == NewInput.getValueSizeInBits() &&
36047            "Unexpected subvector extraction");
36048   }
36049 
36050   // Create new mask for larger type.
36051   for (unsigned i = 1; i != NumInputs; ++i)
36052     Offsets[i] += i * Scale * NumMaskElts;
36053 
36054   SmallVector<int, 64> WideMask(BaseMask.begin(), BaseMask.end());
36055   for (int &M : WideMask) {
36056     if (M < 0)
36057       continue;
36058     M = (M % NumMaskElts) + Offsets[M / NumMaskElts];
36059   }
36060   WideMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
36061 
36062   // Remove unused/repeated shuffle source ops.
36063   resolveTargetShuffleInputsAndMask(WideInputs, WideMask);
36064   assert(!WideInputs.empty() && "Shuffle with no inputs detected");
36065 
36066   if (WideInputs.size() > 2)
36067     return SDValue();
36068 
36069   // Increase depth for every upper subvector we've peeked through.
36070   Depth += count_if(Offsets, [](unsigned Offset) { return Offset > 0; });
36071 
36072   // Attempt to combine wider chain.
36073   // TODO: Can we use a better Root?
36074   SDValue WideRoot = WideInputs[0];
36075   if (SDValue WideShuffle = combineX86ShuffleChain(
36076           WideInputs, WideRoot, WideMask, Depth, HasVariableMask,
36077           AllowVariableMask, DAG, Subtarget)) {
36078     WideShuffle =
36079         extractSubVector(WideShuffle, 0, DAG, SDLoc(Root), RootSizeInBits);
36080     return DAG.getBitcast(RootVT, WideShuffle);
36081   }
36082   return SDValue();
36083 }
36084 
36085 // Canonicalize the combined shuffle mask chain with horizontal ops.
36086 // NOTE: This may update the Ops and Mask.
36087 static SDValue canonicalizeShuffleMaskWithHorizOp(
36088     MutableArrayRef<SDValue> Ops, MutableArrayRef<int> Mask,
36089     unsigned RootSizeInBits, const SDLoc &DL, SelectionDAG &DAG,
36090     const X86Subtarget &Subtarget) {
36091   if (Mask.empty() || Ops.empty())
36092     return SDValue();
36093 
36094   SmallVector<SDValue> BC;
36095   for (SDValue Op : Ops)
36096     BC.push_back(peekThroughBitcasts(Op));
36097 
36098   // All ops must be the same horizop + type.
36099   SDValue BC0 = BC[0];
36100   EVT VT0 = BC0.getValueType();
36101   unsigned Opcode0 = BC0.getOpcode();
36102   if (VT0.getSizeInBits() != RootSizeInBits || llvm::any_of(BC, [&](SDValue V) {
36103         return V.getOpcode() != Opcode0 || V.getValueType() != VT0;
36104       }))
36105     return SDValue();
36106 
36107   bool isHoriz = (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
36108                   Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB);
36109   bool isPack = (Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS);
36110   if (!isHoriz && !isPack)
36111     return SDValue();
36112 
36113   int NumElts = VT0.getVectorNumElements();
36114   int NumLanes = VT0.getSizeInBits() / 128;
36115   int NumEltsPerLane = NumElts / NumLanes;
36116   int NumHalfEltsPerLane = NumEltsPerLane / 2;
36117 
36118   // See if we can remove the shuffle by resorting the HOP chain so that
36119   // the HOP args are pre-shuffled.
36120   // TODO: Generalize to any sized/depth chain.
36121   // TODO: Add support for PACKSS/PACKUS.
36122   if (isHoriz && NumEltsPerLane == 4 && VT0.is128BitVector() &&
36123       shouldUseHorizontalOp(Ops.size() == 1, DAG, Subtarget)) {
36124     SmallVector<int> ScaledMask;
36125     if (scaleShuffleElements(Mask, 4, ScaledMask)) {
36126       // Attempt to find a HOP(HOP(X,Y),HOP(Z,W)) source operand.
36127       auto GetHOpSrc = [&](int M) {
36128         if (M == SM_SentinelUndef)
36129           return DAG.getUNDEF(VT0);
36130         if (M == SM_SentinelZero)
36131           return getZeroVector(VT0.getSimpleVT(), Subtarget, DAG, DL);
36132         SDValue Src0 = BC[M / NumElts];
36133         SDValue Src1 = Src0.getOperand((M % 4) >= 2);
36134         if (Src1.getOpcode() == Opcode0 && Src0->isOnlyUserOf(Src1.getNode()))
36135           return Src1.getOperand(M % 2);
36136         return SDValue();
36137       };
36138       SDValue M0 = GetHOpSrc(ScaledMask[0]);
36139       SDValue M1 = GetHOpSrc(ScaledMask[1]);
36140       SDValue M2 = GetHOpSrc(ScaledMask[2]);
36141       SDValue M3 = GetHOpSrc(ScaledMask[3]);
36142       if (M0 && M1 && M2 && M3) {
36143         SDValue LHS = DAG.getNode(Opcode0, DL, VT0, M0, M1);
36144         SDValue RHS = DAG.getNode(Opcode0, DL, VT0, M2, M3);
36145         return DAG.getNode(Opcode0, DL, VT0, LHS, RHS);
36146       }
36147     }
36148   }
36149 
36150   if (2 < Ops.size())
36151     return SDValue();
36152 
36153   SDValue BC1 = BC[BC.size() - 1];
36154   if (Mask.size() == VT0.getVectorNumElements()) {
36155     // Canonicalize binary shuffles of horizontal ops that use the
36156     // same sources to an unary shuffle.
36157     // TODO: Try to perform this fold even if the shuffle remains.
36158     if (Ops.size() == 2) {
36159       auto ContainsOps = [](SDValue HOp, SDValue Op) {
36160         return Op == HOp.getOperand(0) || Op == HOp.getOperand(1);
36161       };
36162       // Commute if all BC0's ops are contained in BC1.
36163       if (ContainsOps(BC1, BC0.getOperand(0)) &&
36164           ContainsOps(BC1, BC0.getOperand(1))) {
36165         ShuffleVectorSDNode::commuteMask(Mask);
36166         std::swap(Ops[0], Ops[1]);
36167         std::swap(BC0, BC1);
36168       }
36169 
36170       // If BC1 can be represented by BC0, then convert to unary shuffle.
36171       if (ContainsOps(BC0, BC1.getOperand(0)) &&
36172           ContainsOps(BC0, BC1.getOperand(1))) {
36173         for (int &M : Mask) {
36174           if (M < NumElts) // BC0 element or UNDEF/Zero sentinel.
36175             continue;
36176           int SubLane = ((M % NumEltsPerLane) >= NumHalfEltsPerLane) ? 1 : 0;
36177           M -= NumElts + (SubLane * NumHalfEltsPerLane);
36178           if (BC1.getOperand(SubLane) != BC0.getOperand(0))
36179             M += NumHalfEltsPerLane;
36180         }
36181       }
36182     }
36183 
36184     // Canonicalize unary horizontal ops to only refer to lower halves.
36185     for (int i = 0; i != NumElts; ++i) {
36186       int &M = Mask[i];
36187       if (isUndefOrZero(M))
36188         continue;
36189       if (M < NumElts && BC0.getOperand(0) == BC0.getOperand(1) &&
36190           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
36191         M -= NumHalfEltsPerLane;
36192       if (NumElts <= M && BC1.getOperand(0) == BC1.getOperand(1) &&
36193           (M % NumEltsPerLane) >= NumHalfEltsPerLane)
36194         M -= NumHalfEltsPerLane;
36195     }
36196   }
36197 
36198   // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
36199   // single instruction. Attempt to match a v2X64 repeating shuffle pattern that
36200   // represents the LHS/RHS inputs for the lower/upper halves.
36201   unsigned EltSizeInBits = RootSizeInBits / Mask.size();
36202   SmallVector<int, 16> TargetMask128, WideMask128;
36203   if (isRepeatedTargetShuffleMask(128, EltSizeInBits, Mask, TargetMask128) &&
36204       scaleShuffleElements(TargetMask128, 2, WideMask128)) {
36205     assert(isUndefOrZeroOrInRange(WideMask128, 0, 4) && "Illegal shuffle");
36206     bool SingleOp = (Ops.size() == 1);
36207     if (!isHoriz || shouldUseHorizontalOp(SingleOp, DAG, Subtarget)) {
36208       SDValue Lo = isInRange(WideMask128[0], 0, 2) ? BC0 : BC1;
36209       SDValue Hi = isInRange(WideMask128[1], 0, 2) ? BC0 : BC1;
36210       Lo = Lo.getOperand(WideMask128[0] & 1);
36211       Hi = Hi.getOperand(WideMask128[1] & 1);
36212       if (SingleOp) {
36213         MVT SrcVT = BC0.getOperand(0).getSimpleValueType();
36214         SDValue Undef = DAG.getUNDEF(SrcVT);
36215         SDValue Zero = getZeroVector(SrcVT, Subtarget, DAG, DL);
36216         Lo = (WideMask128[0] == SM_SentinelZero ? Zero : Lo);
36217         Hi = (WideMask128[1] == SM_SentinelZero ? Zero : Hi);
36218         Lo = (WideMask128[0] == SM_SentinelUndef ? Undef : Lo);
36219         Hi = (WideMask128[1] == SM_SentinelUndef ? Undef : Hi);
36220       }
36221       return DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
36222     }
36223   }
36224 
36225   return SDValue();
36226 }
36227 
36228 // Attempt to constant fold all of the constant source ops.
36229 // Returns true if the entire shuffle is folded to a constant.
36230 // TODO: Extend this to merge multiple constant Ops and update the mask.
36231 static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
36232                                            ArrayRef<int> Mask, SDValue Root,
36233                                            bool HasVariableMask,
36234                                            SelectionDAG &DAG,
36235                                            const X86Subtarget &Subtarget) {
36236   MVT VT = Root.getSimpleValueType();
36237 
36238   unsigned SizeInBits = VT.getSizeInBits();
36239   unsigned NumMaskElts = Mask.size();
36240   unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
36241   unsigned NumOps = Ops.size();
36242 
36243   // Extract constant bits from each source op.
36244   bool OneUseConstantOp = false;
36245   SmallVector<APInt, 16> UndefEltsOps(NumOps);
36246   SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
36247   for (unsigned i = 0; i != NumOps; ++i) {
36248     SDValue SrcOp = Ops[i];
36249     OneUseConstantOp |= SrcOp.hasOneUse();
36250     if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
36251                                        RawBitsOps[i]))
36252       return SDValue();
36253   }
36254 
36255   // Only fold if at least one of the constants is only used once or
36256   // the combined shuffle has included a variable mask shuffle, this
36257   // is to avoid constant pool bloat.
36258   if (!OneUseConstantOp && !HasVariableMask)
36259     return SDValue();
36260 
36261   // Shuffle the constant bits according to the mask.
36262   SDLoc DL(Root);
36263   APInt UndefElts(NumMaskElts, 0);
36264   APInt ZeroElts(NumMaskElts, 0);
36265   APInt ConstantElts(NumMaskElts, 0);
36266   SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
36267                                         APInt::getNullValue(MaskSizeInBits));
36268   for (unsigned i = 0; i != NumMaskElts; ++i) {
36269     int M = Mask[i];
36270     if (M == SM_SentinelUndef) {
36271       UndefElts.setBit(i);
36272       continue;
36273     } else if (M == SM_SentinelZero) {
36274       ZeroElts.setBit(i);
36275       continue;
36276     }
36277     assert(0 <= M && M < (int)(NumMaskElts * NumOps));
36278 
36279     unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
36280     unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
36281 
36282     auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
36283     if (SrcUndefElts[SrcMaskIdx]) {
36284       UndefElts.setBit(i);
36285       continue;
36286     }
36287 
36288     auto &SrcEltBits = RawBitsOps[SrcOpIdx];
36289     APInt &Bits = SrcEltBits[SrcMaskIdx];
36290     if (!Bits) {
36291       ZeroElts.setBit(i);
36292       continue;
36293     }
36294 
36295     ConstantElts.setBit(i);
36296     ConstantBitData[i] = Bits;
36297   }
36298   assert((UndefElts | ZeroElts | ConstantElts).isAllOnesValue());
36299 
36300   // Attempt to create a zero vector.
36301   if ((UndefElts | ZeroElts).isAllOnesValue())
36302     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG, DL);
36303 
36304   // Create the constant data.
36305   MVT MaskSVT;
36306   if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
36307     MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
36308   else
36309     MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
36310 
36311   MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
36312   if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
36313     return SDValue();
36314 
36315   SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
36316   return DAG.getBitcast(VT, CstOp);
36317 }
36318 
36319 namespace llvm {
36320   namespace X86 {
36321     enum {
36322       MaxShuffleCombineDepth = 8
36323     };
36324   }
36325 } // namespace llvm
36326 
36327 /// Fully generic combining of x86 shuffle instructions.
36328 ///
36329 /// This should be the last combine run over the x86 shuffle instructions. Once
36330 /// they have been fully optimized, this will recursively consider all chains
36331 /// of single-use shuffle instructions, build a generic model of the cumulative
36332 /// shuffle operation, and check for simpler instructions which implement this
36333 /// operation. We use this primarily for two purposes:
36334 ///
36335 /// 1) Collapse generic shuffles to specialized single instructions when
36336 ///    equivalent. In most cases, this is just an encoding size win, but
36337 ///    sometimes we will collapse multiple generic shuffles into a single
36338 ///    special-purpose shuffle.
36339 /// 2) Look for sequences of shuffle instructions with 3 or more total
36340 ///    instructions, and replace them with the slightly more expensive SSSE3
36341 ///    PSHUFB instruction if available. We do this as the last combining step
36342 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
36343 ///    a suitable short sequence of other instructions. The PSHUFB will either
36344 ///    use a register or have to read from memory and so is slightly (but only
36345 ///    slightly) more expensive than the other shuffle instructions.
36346 ///
36347 /// Because this is inherently a quadratic operation (for each shuffle in
36348 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
36349 /// This should never be an issue in practice as the shuffle lowering doesn't
36350 /// produce sequences of more than 8 instructions.
36351 ///
36352 /// FIXME: We will currently miss some cases where the redundant shuffling
36353 /// would simplify under the threshold for PSHUFB formation because of
36354 /// combine-ordering. To fix this, we should do the redundant instruction
36355 /// combining in this recursive walk.
36356 static SDValue combineX86ShufflesRecursively(
36357     ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
36358     ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
36359     unsigned MaxDepth, bool HasVariableMask, bool AllowVariableMask,
36360     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
36361   assert(RootMask.size() > 0 &&
36362          (RootMask.size() > 1 || (RootMask[0] == 0 && SrcOpIndex == 0)) &&
36363          "Illegal shuffle root mask");
36364   assert(Root.getSimpleValueType().isVector() &&
36365          "Shuffles operate on vector types!");
36366   unsigned RootSizeInBits = Root.getSimpleValueType().getSizeInBits();
36367 
36368   // Bound the depth of our recursive combine because this is ultimately
36369   // quadratic in nature.
36370   if (Depth >= MaxDepth)
36371     return SDValue();
36372 
36373   // Directly rip through bitcasts to find the underlying operand.
36374   SDValue Op = SrcOps[SrcOpIndex];
36375   Op = peekThroughOneUseBitcasts(Op);
36376 
36377   EVT VT = Op.getValueType();
36378   if (!VT.isVector() || !VT.isSimple())
36379     return SDValue(); // Bail if we hit a non-simple non-vector.
36380 
36381   assert((RootSizeInBits % VT.getSizeInBits()) == 0 &&
36382          "Can only combine shuffles upto size of the root op.");
36383 
36384   // Extract target shuffle mask and resolve sentinels and inputs.
36385   // TODO - determine Op's demanded elts from RootMask.
36386   SmallVector<int, 64> OpMask;
36387   SmallVector<SDValue, 2> OpInputs;
36388   APInt OpUndef, OpZero;
36389   APInt OpDemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
36390   bool IsOpVariableMask = isTargetShuffleVariableMask(Op.getOpcode());
36391   if (!getTargetShuffleInputs(Op, OpDemandedElts, OpInputs, OpMask, OpUndef,
36392                               OpZero, DAG, Depth, false))
36393     return SDValue();
36394 
36395   // Shuffle inputs must not be larger than the shuffle result.
36396   // TODO: Relax this for single input faux shuffles (trunc/extract_subvector).
36397   if (llvm::any_of(OpInputs, [VT](SDValue OpInput) {
36398         return OpInput.getValueSizeInBits() > VT.getSizeInBits();
36399       }))
36400     return SDValue();
36401 
36402   // If the shuffle result was smaller than the root, we need to adjust the
36403   // mask indices and pad the mask with undefs.
36404   if (RootSizeInBits > VT.getSizeInBits()) {
36405     unsigned NumSubVecs = RootSizeInBits / VT.getSizeInBits();
36406     unsigned OpMaskSize = OpMask.size();
36407     if (OpInputs.size() > 1) {
36408       unsigned PaddedMaskSize = NumSubVecs * OpMaskSize;
36409       for (int &M : OpMask) {
36410         if (M < 0)
36411           continue;
36412         int EltIdx = M % OpMaskSize;
36413         int OpIdx = M / OpMaskSize;
36414         M = (PaddedMaskSize * OpIdx) + EltIdx;
36415       }
36416     }
36417     OpZero = OpZero.zext(NumSubVecs * OpMaskSize);
36418     OpUndef = OpUndef.zext(NumSubVecs * OpMaskSize);
36419     OpMask.append((NumSubVecs - 1) * OpMaskSize, SM_SentinelUndef);
36420   }
36421 
36422   SmallVector<int, 64> Mask;
36423   SmallVector<SDValue, 16> Ops;
36424 
36425   // We don't need to merge masks if the root is empty.
36426   bool EmptyRoot = (Depth == 0) && (RootMask.size() == 1);
36427   if (EmptyRoot) {
36428     // Only resolve zeros if it will remove an input, otherwise we might end
36429     // up in an infinite loop.
36430     bool ResolveKnownZeros = true;
36431     if (!OpZero.isNullValue()) {
36432       APInt UsedInputs = APInt::getNullValue(OpInputs.size());
36433       for (int i = 0, e = OpMask.size(); i != e; ++i) {
36434         int M = OpMask[i];
36435         if (OpUndef[i] || OpZero[i] || isUndefOrZero(M))
36436           continue;
36437         UsedInputs.setBit(M / OpMask.size());
36438         if (UsedInputs.isAllOnesValue()) {
36439           ResolveKnownZeros = false;
36440           break;
36441         }
36442       }
36443     }
36444     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero,
36445                                       ResolveKnownZeros);
36446 
36447     Mask = OpMask;
36448     Ops.append(OpInputs.begin(), OpInputs.end());
36449   } else {
36450     resolveTargetShuffleFromZeroables(OpMask, OpUndef, OpZero);
36451 
36452     // Add the inputs to the Ops list, avoiding duplicates.
36453     Ops.append(SrcOps.begin(), SrcOps.end());
36454 
36455     auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
36456       // Attempt to find an existing match.
36457       SDValue InputBC = peekThroughBitcasts(Input);
36458       for (int i = 0, e = Ops.size(); i < e; ++i)
36459         if (InputBC == peekThroughBitcasts(Ops[i]))
36460           return i;
36461       // Match failed - should we replace an existing Op?
36462       if (InsertionPoint >= 0) {
36463         Ops[InsertionPoint] = Input;
36464         return InsertionPoint;
36465       }
36466       // Add to the end of the Ops list.
36467       Ops.push_back(Input);
36468       return Ops.size() - 1;
36469     };
36470 
36471     SmallVector<int, 2> OpInputIdx;
36472     for (SDValue OpInput : OpInputs)
36473       OpInputIdx.push_back(
36474           AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
36475 
36476     assert(((RootMask.size() > OpMask.size() &&
36477              RootMask.size() % OpMask.size() == 0) ||
36478             (OpMask.size() > RootMask.size() &&
36479              OpMask.size() % RootMask.size() == 0) ||
36480             OpMask.size() == RootMask.size()) &&
36481            "The smaller number of elements must divide the larger.");
36482 
36483     // This function can be performance-critical, so we rely on the power-of-2
36484     // knowledge that we have about the mask sizes to replace div/rem ops with
36485     // bit-masks and shifts.
36486     assert(isPowerOf2_32(RootMask.size()) &&
36487            "Non-power-of-2 shuffle mask sizes");
36488     assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes");
36489     unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
36490     unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
36491 
36492     unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
36493     unsigned RootRatio =
36494         std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
36495     unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
36496     assert((RootRatio == 1 || OpRatio == 1) &&
36497            "Must not have a ratio for both incoming and op masks!");
36498 
36499     assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes");
36500     assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes");
36501     assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes");
36502     unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
36503     unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
36504 
36505     Mask.resize(MaskWidth, SM_SentinelUndef);
36506 
36507     // Merge this shuffle operation's mask into our accumulated mask. Note that
36508     // this shuffle's mask will be the first applied to the input, followed by
36509     // the root mask to get us all the way to the root value arrangement. The
36510     // reason for this order is that we are recursing up the operation chain.
36511     for (unsigned i = 0; i < MaskWidth; ++i) {
36512       unsigned RootIdx = i >> RootRatioLog2;
36513       if (RootMask[RootIdx] < 0) {
36514         // This is a zero or undef lane, we're done.
36515         Mask[i] = RootMask[RootIdx];
36516         continue;
36517       }
36518 
36519       unsigned RootMaskedIdx =
36520           RootRatio == 1
36521               ? RootMask[RootIdx]
36522               : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
36523 
36524       // Just insert the scaled root mask value if it references an input other
36525       // than the SrcOp we're currently inserting.
36526       if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
36527           (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
36528         Mask[i] = RootMaskedIdx;
36529         continue;
36530       }
36531 
36532       RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
36533       unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
36534       if (OpMask[OpIdx] < 0) {
36535         // The incoming lanes are zero or undef, it doesn't matter which ones we
36536         // are using.
36537         Mask[i] = OpMask[OpIdx];
36538         continue;
36539       }
36540 
36541       // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
36542       unsigned OpMaskedIdx = OpRatio == 1 ? OpMask[OpIdx]
36543                                           : (OpMask[OpIdx] << OpRatioLog2) +
36544                                                 (RootMaskedIdx & (OpRatio - 1));
36545 
36546       OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
36547       int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
36548       assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input");
36549       OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
36550 
36551       Mask[i] = OpMaskedIdx;
36552     }
36553   }
36554 
36555   // Remove unused/repeated shuffle source ops.
36556   resolveTargetShuffleInputsAndMask(Ops, Mask);
36557 
36558   // Handle the all undef/zero cases early.
36559   if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
36560     return DAG.getUNDEF(Root.getValueType());
36561   if (all_of(Mask, [](int Idx) { return Idx < 0; }))
36562     return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
36563                          SDLoc(Root));
36564 
36565   assert(!Ops.empty() && "Shuffle with no inputs detected");
36566   HasVariableMask |= IsOpVariableMask;
36567 
36568   // Update the list of shuffle nodes that have been combined so far.
36569   SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
36570                                                 SrcNodes.end());
36571   CombinedNodes.push_back(Op.getNode());
36572 
36573   // See if we can recurse into each shuffle source op (if it's a target
36574   // shuffle). The source op should only be generally combined if it either has
36575   // a single use (i.e. current Op) or all its users have already been combined,
36576   // if not then we can still combine but should prevent generation of variable
36577   // shuffles to avoid constant pool bloat.
36578   // Don't recurse if we already have more source ops than we can combine in
36579   // the remaining recursion depth.
36580   if (Ops.size() < (MaxDepth - Depth)) {
36581     for (int i = 0, e = Ops.size(); i < e; ++i) {
36582       // For empty roots, we need to resolve zeroable elements before combining
36583       // them with other shuffles.
36584       SmallVector<int, 64> ResolvedMask = Mask;
36585       if (EmptyRoot)
36586         resolveTargetShuffleFromZeroables(ResolvedMask, OpUndef, OpZero);
36587       bool AllowVar = false;
36588       if (Ops[i].getNode()->hasOneUse() ||
36589           SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode()))
36590         AllowVar = AllowVariableMask;
36591       if (SDValue Res = combineX86ShufflesRecursively(
36592               Ops, i, Root, ResolvedMask, CombinedNodes, Depth + 1, MaxDepth,
36593               HasVariableMask, AllowVar, DAG, Subtarget))
36594         return Res;
36595     }
36596   }
36597 
36598   // Attempt to constant fold all of the constant source ops.
36599   if (SDValue Cst = combineX86ShufflesConstants(
36600           Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
36601     return Cst;
36602 
36603   // Canonicalize the combined shuffle mask chain with horizontal ops.
36604   // NOTE: This will update the Ops and Mask.
36605   if (SDValue HOp = canonicalizeShuffleMaskWithHorizOp(
36606           Ops, Mask, RootSizeInBits, SDLoc(Root), DAG, Subtarget))
36607     return DAG.getBitcast(Root.getValueType(), HOp);
36608 
36609   // Widen any subvector shuffle inputs we've collected.
36610   if (any_of(Ops, [RootSizeInBits](SDValue Op) {
36611         return Op.getValueSizeInBits() < RootSizeInBits;
36612       })) {
36613     for (SDValue &Op : Ops)
36614       if (Op.getValueSizeInBits() < RootSizeInBits)
36615         Op = widenSubVector(Op, false, Subtarget, DAG, SDLoc(Op),
36616                             RootSizeInBits);
36617     // Reresolve - we might have repeated subvector sources.
36618     resolveTargetShuffleInputsAndMask(Ops, Mask);
36619   }
36620 
36621   // We can only combine unary and binary shuffle mask cases.
36622   if (Ops.size() <= 2) {
36623     // Minor canonicalization of the accumulated shuffle mask to make it easier
36624     // to match below. All this does is detect masks with sequential pairs of
36625     // elements, and shrink them to the half-width mask. It does this in a loop
36626     // so it will reduce the size of the mask to the minimal width mask which
36627     // performs an equivalent shuffle.
36628     while (Mask.size() > 1) {
36629       SmallVector<int, 64> WidenedMask;
36630       if (!canWidenShuffleElements(Mask, WidenedMask))
36631         break;
36632       Mask = std::move(WidenedMask);
36633     }
36634 
36635     // Canonicalization of binary shuffle masks to improve pattern matching by
36636     // commuting the inputs.
36637     if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
36638       ShuffleVectorSDNode::commuteMask(Mask);
36639       std::swap(Ops[0], Ops[1]);
36640     }
36641 
36642     // Finally, try to combine into a single shuffle instruction.
36643     return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
36644                                   AllowVariableMask, DAG, Subtarget);
36645   }
36646 
36647   // If that failed and any input is extracted then try to combine as a
36648   // shuffle with the larger type.
36649   return combineX86ShuffleChainWithExtract(Ops, Root, Mask, Depth,
36650                                            HasVariableMask, AllowVariableMask,
36651                                            DAG, Subtarget);
36652 }
36653 
36654 /// Helper entry wrapper to combineX86ShufflesRecursively.
36655 static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
36656                                              const X86Subtarget &Subtarget) {
36657   return combineX86ShufflesRecursively({Op}, 0, Op, {0}, {}, /*Depth*/ 0,
36658                                        X86::MaxShuffleCombineDepth,
36659                                        /*HasVarMask*/ false,
36660                                        /*AllowVarMask*/ true, DAG, Subtarget);
36661 }
36662 
36663 /// Get the PSHUF-style mask from PSHUF node.
36664 ///
36665 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
36666 /// PSHUF-style masks that can be reused with such instructions.
36667 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
36668   MVT VT = N.getSimpleValueType();
36669   SmallVector<int, 4> Mask;
36670   SmallVector<SDValue, 2> Ops;
36671   bool IsUnary;
36672   bool HaveMask =
36673       getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask, IsUnary);
36674   (void)HaveMask;
36675   assert(HaveMask);
36676 
36677   // If we have more than 128-bits, only the low 128-bits of shuffle mask
36678   // matter. Check that the upper masks are repeats and remove them.
36679   if (VT.getSizeInBits() > 128) {
36680     int LaneElts = 128 / VT.getScalarSizeInBits();
36681 #ifndef NDEBUG
36682     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
36683       for (int j = 0; j < LaneElts; ++j)
36684         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
36685                "Mask doesn't repeat in high 128-bit lanes!");
36686 #endif
36687     Mask.resize(LaneElts);
36688   }
36689 
36690   switch (N.getOpcode()) {
36691   case X86ISD::PSHUFD:
36692     return Mask;
36693   case X86ISD::PSHUFLW:
36694     Mask.resize(4);
36695     return Mask;
36696   case X86ISD::PSHUFHW:
36697     Mask.erase(Mask.begin(), Mask.begin() + 4);
36698     for (int &M : Mask)
36699       M -= 4;
36700     return Mask;
36701   default:
36702     llvm_unreachable("No valid shuffle instruction found!");
36703   }
36704 }
36705 
36706 /// Search for a combinable shuffle across a chain ending in pshufd.
36707 ///
36708 /// We walk up the chain and look for a combinable shuffle, skipping over
36709 /// shuffles that we could hoist this shuffle's transformation past without
36710 /// altering anything.
36711 static SDValue
36712 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
36713                              SelectionDAG &DAG) {
36714   assert(N.getOpcode() == X86ISD::PSHUFD &&
36715          "Called with something other than an x86 128-bit half shuffle!");
36716   SDLoc DL(N);
36717 
36718   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
36719   // of the shuffles in the chain so that we can form a fresh chain to replace
36720   // this one.
36721   SmallVector<SDValue, 8> Chain;
36722   SDValue V = N.getOperand(0);
36723   for (; V.hasOneUse(); V = V.getOperand(0)) {
36724     switch (V.getOpcode()) {
36725     default:
36726       return SDValue(); // Nothing combined!
36727 
36728     case ISD::BITCAST:
36729       // Skip bitcasts as we always know the type for the target specific
36730       // instructions.
36731       continue;
36732 
36733     case X86ISD::PSHUFD:
36734       // Found another dword shuffle.
36735       break;
36736 
36737     case X86ISD::PSHUFLW:
36738       // Check that the low words (being shuffled) are the identity in the
36739       // dword shuffle, and the high words are self-contained.
36740       if (Mask[0] != 0 || Mask[1] != 1 ||
36741           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
36742         return SDValue();
36743 
36744       Chain.push_back(V);
36745       continue;
36746 
36747     case X86ISD::PSHUFHW:
36748       // Check that the high words (being shuffled) are the identity in the
36749       // dword shuffle, and the low words are self-contained.
36750       if (Mask[2] != 2 || Mask[3] != 3 ||
36751           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
36752         return SDValue();
36753 
36754       Chain.push_back(V);
36755       continue;
36756 
36757     case X86ISD::UNPCKL:
36758     case X86ISD::UNPCKH:
36759       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
36760       // shuffle into a preceding word shuffle.
36761       if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
36762           V.getSimpleValueType().getVectorElementType() != MVT::i16)
36763         return SDValue();
36764 
36765       // Search for a half-shuffle which we can combine with.
36766       unsigned CombineOp =
36767           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
36768       if (V.getOperand(0) != V.getOperand(1) ||
36769           !V->isOnlyUserOf(V.getOperand(0).getNode()))
36770         return SDValue();
36771       Chain.push_back(V);
36772       V = V.getOperand(0);
36773       do {
36774         switch (V.getOpcode()) {
36775         default:
36776           return SDValue(); // Nothing to combine.
36777 
36778         case X86ISD::PSHUFLW:
36779         case X86ISD::PSHUFHW:
36780           if (V.getOpcode() == CombineOp)
36781             break;
36782 
36783           Chain.push_back(V);
36784 
36785           LLVM_FALLTHROUGH;
36786         case ISD::BITCAST:
36787           V = V.getOperand(0);
36788           continue;
36789         }
36790         break;
36791       } while (V.hasOneUse());
36792       break;
36793     }
36794     // Break out of the loop if we break out of the switch.
36795     break;
36796   }
36797 
36798   if (!V.hasOneUse())
36799     // We fell out of the loop without finding a viable combining instruction.
36800     return SDValue();
36801 
36802   // Merge this node's mask and our incoming mask.
36803   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
36804   for (int &M : Mask)
36805     M = VMask[M];
36806   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
36807                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
36808 
36809   // Rebuild the chain around this new shuffle.
36810   while (!Chain.empty()) {
36811     SDValue W = Chain.pop_back_val();
36812 
36813     if (V.getValueType() != W.getOperand(0).getValueType())
36814       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
36815 
36816     switch (W.getOpcode()) {
36817     default:
36818       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
36819 
36820     case X86ISD::UNPCKL:
36821     case X86ISD::UNPCKH:
36822       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
36823       break;
36824 
36825     case X86ISD::PSHUFD:
36826     case X86ISD::PSHUFLW:
36827     case X86ISD::PSHUFHW:
36828       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
36829       break;
36830     }
36831   }
36832   if (V.getValueType() != N.getValueType())
36833     V = DAG.getBitcast(N.getValueType(), V);
36834 
36835   // Return the new chain to replace N.
36836   return V;
36837 }
36838 
36839 // Attempt to commute shufps LHS loads:
36840 // permilps(shufps(load(),x)) --> permilps(shufps(x,load()))
36841 static SDValue combineCommutableSHUFP(SDValue N, MVT VT, const SDLoc &DL,
36842                                       SelectionDAG &DAG) {
36843   // TODO: Add vXf64 support.
36844   if (VT != MVT::v4f32 && VT != MVT::v8f32 && VT != MVT::v16f32)
36845     return SDValue();
36846 
36847   // SHUFP(LHS, RHS) -> SHUFP(RHS, LHS) iff LHS is foldable + RHS is not.
36848   auto commuteSHUFP = [&VT, &DL, &DAG](SDValue Parent, SDValue V) {
36849     if (V.getOpcode() != X86ISD::SHUFP || !Parent->isOnlyUserOf(V.getNode()))
36850       return SDValue();
36851     SDValue N0 = V.getOperand(0);
36852     SDValue N1 = V.getOperand(1);
36853     unsigned Imm = V.getConstantOperandVal(2);
36854     if (!MayFoldLoad(peekThroughOneUseBitcasts(N0)) ||
36855         MayFoldLoad(peekThroughOneUseBitcasts(N1)))
36856       return SDValue();
36857     Imm = ((Imm & 0x0F) << 4) | ((Imm & 0xF0) >> 4);
36858     return DAG.getNode(X86ISD::SHUFP, DL, VT, N1, N0,
36859                        DAG.getTargetConstant(Imm, DL, MVT::i8));
36860   };
36861 
36862   switch (N.getOpcode()) {
36863   case X86ISD::VPERMILPI:
36864     if (SDValue NewSHUFP = commuteSHUFP(N, N.getOperand(0))) {
36865       unsigned Imm = N.getConstantOperandVal(1);
36866       return DAG.getNode(X86ISD::VPERMILPI, DL, VT, NewSHUFP,
36867                          DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
36868     }
36869     break;
36870   case X86ISD::SHUFP: {
36871     SDValue N0 = N.getOperand(0);
36872     SDValue N1 = N.getOperand(1);
36873     unsigned Imm = N.getConstantOperandVal(2);
36874     if (N0 == N1) {
36875       if (SDValue NewSHUFP = commuteSHUFP(N, N0))
36876         return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, NewSHUFP,
36877                            DAG.getTargetConstant(Imm ^ 0xAA, DL, MVT::i8));
36878     } else if (SDValue NewSHUFP = commuteSHUFP(N, N0)) {
36879       return DAG.getNode(X86ISD::SHUFP, DL, VT, NewSHUFP, N1,
36880                          DAG.getTargetConstant(Imm ^ 0x0A, DL, MVT::i8));
36881     } else if (SDValue NewSHUFP = commuteSHUFP(N, N1)) {
36882       return DAG.getNode(X86ISD::SHUFP, DL, VT, N0, NewSHUFP,
36883                          DAG.getTargetConstant(Imm ^ 0xA0, DL, MVT::i8));
36884     }
36885     break;
36886   }
36887   }
36888 
36889   return SDValue();
36890 }
36891 
36892 /// Attempt to fold vpermf128(op(),op()) -> op(vpermf128(),vpermf128()).
36893 static SDValue canonicalizeLaneShuffleWithRepeatedOps(SDValue V,
36894                                                       SelectionDAG &DAG,
36895                                                       const SDLoc &DL) {
36896   assert(V.getOpcode() == X86ISD::VPERM2X128 && "Unknown lane shuffle");
36897 
36898   MVT VT = V.getSimpleValueType();
36899   SDValue Src0 = peekThroughBitcasts(V.getOperand(0));
36900   SDValue Src1 = peekThroughBitcasts(V.getOperand(1));
36901   unsigned SrcOpc0 = Src0.getOpcode();
36902   unsigned SrcOpc1 = Src1.getOpcode();
36903   EVT SrcVT0 = Src0.getValueType();
36904   EVT SrcVT1 = Src1.getValueType();
36905 
36906   if (!Src1.isUndef() && (SrcVT0 != SrcVT1 || SrcOpc0 != SrcOpc1))
36907     return SDValue();
36908 
36909   switch (SrcOpc0) {
36910   case X86ISD::MOVDDUP: {
36911     SDValue LHS = DAG.getBitcast(VT, Src0.getOperand(0));
36912     SDValue RHS =
36913         DAG.getBitcast(VT, Src1.isUndef() ? Src1 : Src1.getOperand(0));
36914     SDValue Res =
36915         DAG.getNode(X86ISD::VPERM2X128, DL, VT, LHS, RHS, V.getOperand(2));
36916     Res = DAG.getNode(SrcOpc0, DL, SrcVT0, DAG.getBitcast(SrcVT0, Res));
36917     return DAG.getBitcast(VT, Res);
36918   }
36919   case X86ISD::VPERMILPI:
36920     // TODO: Handle v4f64 permutes with different low/high lane masks.
36921     if (SrcVT0 == MVT::v4f64) {
36922       uint64_t Mask = Src0.getConstantOperandVal(1);
36923       if ((Mask & 0x3) != ((Mask >> 2) & 0x3))
36924         break;
36925     }
36926     LLVM_FALLTHROUGH;
36927   case X86ISD::VSHLI:
36928   case X86ISD::VSRLI:
36929   case X86ISD::VSRAI:
36930   case X86ISD::PSHUFD:
36931     if (Src1.isUndef() || Src0.getOperand(1) == Src1.getOperand(1)) {
36932       SDValue LHS = DAG.getBitcast(VT, Src0.getOperand(0));
36933       SDValue RHS =
36934           DAG.getBitcast(VT, Src1.isUndef() ? Src1 : Src1.getOperand(0));
36935       SDValue Res =
36936           DAG.getNode(X86ISD::VPERM2X128, DL, VT, LHS, RHS, V.getOperand(2));
36937       Res = DAG.getNode(SrcOpc0, DL, SrcVT0, DAG.getBitcast(SrcVT0, Res),
36938                         Src0.getOperand(1));
36939       return DAG.getBitcast(VT, Res);
36940     }
36941     break;
36942   }
36943 
36944   return SDValue();
36945 }
36946 
36947 /// Try to combine x86 target specific shuffles.
36948 static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
36949                                     TargetLowering::DAGCombinerInfo &DCI,
36950                                     const X86Subtarget &Subtarget) {
36951   SDLoc DL(N);
36952   MVT VT = N.getSimpleValueType();
36953   SmallVector<int, 4> Mask;
36954   unsigned Opcode = N.getOpcode();
36955 
36956   if (SDValue R = combineCommutableSHUFP(N, VT, DL, DAG))
36957     return R;
36958 
36959   // Canonicalize UNARYSHUFFLE(XOR(X,-1) -> XOR(UNARYSHUFFLE(X),-1) to
36960   // help expose the 'NOT' pattern further up the DAG.
36961   // TODO: This might be beneficial for any binop with a 'splattable' operand.
36962   switch (Opcode) {
36963   case X86ISD::MOVDDUP:
36964   case X86ISD::PSHUFD: {
36965     SDValue Src = N.getOperand(0);
36966     if (Src.hasOneUse() && Src.getValueType() == VT) {
36967       if (SDValue Not = IsNOT(Src, DAG, /*OneUse*/ true)) {
36968         Not = DAG.getBitcast(VT, Not);
36969         Not = Opcode == X86ISD::MOVDDUP
36970                   ? DAG.getNode(Opcode, DL, VT, Not)
36971                   : DAG.getNode(Opcode, DL, VT, Not, N.getOperand(1));
36972         EVT IntVT = Not.getValueType().changeTypeToInteger();
36973         SDValue AllOnes = DAG.getConstant(-1, DL, IntVT);
36974         Not = DAG.getBitcast(IntVT, Not);
36975         Not = DAG.getNode(ISD::XOR, DL, IntVT, Not, AllOnes);
36976         return DAG.getBitcast(VT, Not);
36977       }
36978     }
36979     break;
36980   }
36981   }
36982 
36983   // Handle specific target shuffles.
36984   switch (Opcode) {
36985   case X86ISD::MOVDDUP: {
36986     SDValue Src = N.getOperand(0);
36987     // Turn a 128-bit MOVDDUP of a full vector load into movddup+vzload.
36988     if (VT == MVT::v2f64 && Src.hasOneUse() &&
36989         ISD::isNormalLoad(Src.getNode())) {
36990       LoadSDNode *LN = cast<LoadSDNode>(Src);
36991       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::f64, MVT::v2f64, DAG)) {
36992         SDValue Movddup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, VZLoad);
36993         DCI.CombineTo(N.getNode(), Movddup);
36994         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
36995         DCI.recursivelyDeleteUnusedNodes(LN);
36996         return N; // Return N so it doesn't get rechecked!
36997       }
36998     }
36999 
37000     return SDValue();
37001   }
37002   case X86ISD::VBROADCAST: {
37003     SDValue Src = N.getOperand(0);
37004     SDValue BC = peekThroughBitcasts(Src);
37005     EVT SrcVT = Src.getValueType();
37006     EVT BCVT = BC.getValueType();
37007 
37008     // If broadcasting from another shuffle, attempt to simplify it.
37009     // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
37010     if (isTargetShuffle(BC.getOpcode()) &&
37011         VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
37012       unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
37013       SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
37014                                         SM_SentinelUndef);
37015       for (unsigned i = 0; i != Scale; ++i)
37016         DemandedMask[i] = i;
37017       if (SDValue Res = combineX86ShufflesRecursively(
37018               {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 0,
37019               X86::MaxShuffleCombineDepth,
37020               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
37021         return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
37022                            DAG.getBitcast(SrcVT, Res));
37023     }
37024 
37025     // broadcast(bitcast(src)) -> bitcast(broadcast(src))
37026     // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
37027     if (Src.getOpcode() == ISD::BITCAST &&
37028         SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits() &&
37029         DAG.getTargetLoweringInfo().isTypeLegal(BCVT)) {
37030       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
37031                                    VT.getVectorNumElements());
37032       return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
37033     }
37034 
37035     // Reduce broadcast source vector to lowest 128-bits.
37036     if (SrcVT.getSizeInBits() > 128)
37037       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
37038                          extract128BitVector(Src, 0, DAG, DL));
37039 
37040     // broadcast(scalar_to_vector(x)) -> broadcast(x).
37041     if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
37042       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
37043 
37044     // Share broadcast with the longest vector and extract low subvector (free).
37045     // Ensure the same SDValue from the SDNode use is being used.
37046     for (SDNode *User : Src->uses())
37047       if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
37048           Src == User->getOperand(0) &&
37049           User->getValueSizeInBits(0).getFixedSize() >
37050               VT.getFixedSizeInBits()) {
37051         return extractSubVector(SDValue(User, 0), 0, DAG, DL,
37052                                 VT.getSizeInBits());
37053       }
37054 
37055     // vbroadcast(scalarload X) -> vbroadcast_load X
37056     // For float loads, extract other uses of the scalar from the broadcast.
37057     if (!SrcVT.isVector() && (Src.hasOneUse() || VT.isFloatingPoint()) &&
37058         ISD::isNormalLoad(Src.getNode())) {
37059       LoadSDNode *LN = cast<LoadSDNode>(Src);
37060       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37061       SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37062       SDValue BcastLd =
37063           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
37064                                   LN->getMemoryVT(), LN->getMemOperand());
37065       // If the load value is used only by N, replace it via CombineTo N.
37066       bool NoReplaceExtract = Src.hasOneUse();
37067       DCI.CombineTo(N.getNode(), BcastLd);
37068       if (NoReplaceExtract) {
37069         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37070         DCI.recursivelyDeleteUnusedNodes(LN);
37071       } else {
37072         SDValue Scl = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT, BcastLd,
37073                                   DAG.getIntPtrConstant(0, DL));
37074         DCI.CombineTo(LN, Scl, BcastLd.getValue(1));
37075       }
37076       return N; // Return N so it doesn't get rechecked!
37077     }
37078 
37079     // Due to isTypeDesirableForOp, we won't always shrink a load truncated to
37080     // i16. So shrink it ourselves if we can make a broadcast_load.
37081     if (SrcVT == MVT::i16 && Src.getOpcode() == ISD::TRUNCATE &&
37082         Src.hasOneUse() && Src.getOperand(0).hasOneUse()) {
37083       assert(Subtarget.hasAVX2() && "Expected AVX2");
37084       SDValue TruncIn = Src.getOperand(0);
37085 
37086       // If this is a truncate of a non extending load we can just narrow it to
37087       // use a broadcast_load.
37088       if (ISD::isNormalLoad(TruncIn.getNode())) {
37089         LoadSDNode *LN = cast<LoadSDNode>(TruncIn);
37090         // Unless its volatile or atomic.
37091         if (LN->isSimple()) {
37092           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37093           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37094           SDValue BcastLd = DAG.getMemIntrinsicNode(
37095               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
37096               LN->getPointerInfo(), LN->getOriginalAlign(),
37097               LN->getMemOperand()->getFlags());
37098           DCI.CombineTo(N.getNode(), BcastLd);
37099           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37100           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
37101           return N; // Return N so it doesn't get rechecked!
37102         }
37103       }
37104 
37105       // If this is a truncate of an i16 extload, we can directly replace it.
37106       if (ISD::isUNINDEXEDLoad(Src.getOperand(0).getNode()) &&
37107           ISD::isEXTLoad(Src.getOperand(0).getNode())) {
37108         LoadSDNode *LN = cast<LoadSDNode>(Src.getOperand(0));
37109         if (LN->getMemoryVT().getSizeInBits() == 16) {
37110           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37111           SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37112           SDValue BcastLd =
37113               DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
37114                                       LN->getMemoryVT(), LN->getMemOperand());
37115           DCI.CombineTo(N.getNode(), BcastLd);
37116           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37117           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
37118           return N; // Return N so it doesn't get rechecked!
37119         }
37120       }
37121 
37122       // If this is a truncate of load that has been shifted right, we can
37123       // offset the pointer and use a narrower load.
37124       if (TruncIn.getOpcode() == ISD::SRL &&
37125           TruncIn.getOperand(0).hasOneUse() &&
37126           isa<ConstantSDNode>(TruncIn.getOperand(1)) &&
37127           ISD::isNormalLoad(TruncIn.getOperand(0).getNode())) {
37128         LoadSDNode *LN = cast<LoadSDNode>(TruncIn.getOperand(0));
37129         unsigned ShiftAmt = TruncIn.getConstantOperandVal(1);
37130         // Make sure the shift amount and the load size are divisible by 16.
37131         // Don't do this if the load is volatile or atomic.
37132         if (ShiftAmt % 16 == 0 && TruncIn.getValueSizeInBits() % 16 == 0 &&
37133             LN->isSimple()) {
37134           unsigned Offset = ShiftAmt / 8;
37135           SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37136           SDValue Ptr = DAG.getMemBasePlusOffset(LN->getBasePtr(),
37137                                                  TypeSize::Fixed(Offset), DL);
37138           SDValue Ops[] = { LN->getChain(), Ptr };
37139           SDValue BcastLd = DAG.getMemIntrinsicNode(
37140               X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MVT::i16,
37141               LN->getPointerInfo().getWithOffset(Offset),
37142               LN->getOriginalAlign(),
37143               LN->getMemOperand()->getFlags());
37144           DCI.CombineTo(N.getNode(), BcastLd);
37145           DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37146           DCI.recursivelyDeleteUnusedNodes(Src.getNode());
37147           return N; // Return N so it doesn't get rechecked!
37148         }
37149       }
37150     }
37151 
37152     // vbroadcast(vzload X) -> vbroadcast_load X
37153     if (Src.getOpcode() == X86ISD::VZEXT_LOAD && Src.hasOneUse()) {
37154       MemSDNode *LN = cast<MemIntrinsicSDNode>(Src);
37155       if (LN->getMemoryVT().getSizeInBits() == VT.getScalarSizeInBits()) {
37156         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37157         SDValue Ops[] = { LN->getChain(), LN->getBasePtr() };
37158         SDValue BcastLd =
37159             DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, DL, Tys, Ops,
37160                                     LN->getMemoryVT(), LN->getMemOperand());
37161         DCI.CombineTo(N.getNode(), BcastLd);
37162         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37163         DCI.recursivelyDeleteUnusedNodes(LN);
37164         return N; // Return N so it doesn't get rechecked!
37165       }
37166     }
37167 
37168     // vbroadcast(vector load X) -> vbroadcast_load
37169     if ((SrcVT == MVT::v2f64 || SrcVT == MVT::v4f32 || SrcVT == MVT::v2i64 ||
37170          SrcVT == MVT::v4i32) &&
37171         Src.hasOneUse() && ISD::isNormalLoad(Src.getNode())) {
37172       LoadSDNode *LN = cast<LoadSDNode>(Src);
37173       // Unless the load is volatile or atomic.
37174       if (LN->isSimple()) {
37175         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37176         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
37177         SDValue BcastLd = DAG.getMemIntrinsicNode(
37178             X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, SrcVT.getScalarType(),
37179             LN->getPointerInfo(), LN->getOriginalAlign(),
37180             LN->getMemOperand()->getFlags());
37181         DCI.CombineTo(N.getNode(), BcastLd);
37182         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), BcastLd.getValue(1));
37183         DCI.recursivelyDeleteUnusedNodes(LN);
37184         return N; // Return N so it doesn't get rechecked!
37185       }
37186     }
37187 
37188     return SDValue();
37189   }
37190   case X86ISD::VZEXT_MOVL: {
37191     SDValue N0 = N.getOperand(0);
37192 
37193     // If this a vzmovl of a full vector load, replace it with a vzload, unless
37194     // the load is volatile.
37195     if (N0.hasOneUse() && ISD::isNormalLoad(N0.getNode())) {
37196       auto *LN = cast<LoadSDNode>(N0);
37197       if (SDValue VZLoad =
37198               narrowLoadToVZLoad(LN, VT.getVectorElementType(), VT, DAG)) {
37199         DCI.CombineTo(N.getNode(), VZLoad);
37200         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
37201         DCI.recursivelyDeleteUnusedNodes(LN);
37202         return N;
37203       }
37204     }
37205 
37206     // If this a VZEXT_MOVL of a VBROADCAST_LOAD, we don't need the broadcast
37207     // and can just use a VZEXT_LOAD.
37208     // FIXME: Is there some way to do this with SimplifyDemandedVectorElts?
37209     if (N0.hasOneUse() && N0.getOpcode() == X86ISD::VBROADCAST_LOAD) {
37210       auto *LN = cast<MemSDNode>(N0);
37211       if (VT.getScalarSizeInBits() == LN->getMemoryVT().getSizeInBits()) {
37212         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
37213         SDValue Ops[] = {LN->getChain(), LN->getBasePtr()};
37214         SDValue VZLoad =
37215             DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
37216                                     LN->getMemoryVT(), LN->getMemOperand());
37217         DCI.CombineTo(N.getNode(), VZLoad);
37218         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
37219         DCI.recursivelyDeleteUnusedNodes(LN);
37220         return N;
37221       }
37222     }
37223 
37224     // Turn (v2i64 (vzext_movl (scalar_to_vector (i64 X)))) into
37225     // (v2i64 (bitcast (v4i32 (vzext_movl (scalar_to_vector (i32 (trunc X)))))))
37226     // if the upper bits of the i64 are zero.
37227     if (N0.hasOneUse() && N0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
37228         N0.getOperand(0).hasOneUse() &&
37229         N0.getOperand(0).getValueType() == MVT::i64) {
37230       SDValue In = N0.getOperand(0);
37231       APInt Mask = APInt::getHighBitsSet(64, 32);
37232       if (DAG.MaskedValueIsZero(In, Mask)) {
37233         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, In);
37234         MVT VecVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
37235         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Trunc);
37236         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, VecVT, SclVec);
37237         return DAG.getBitcast(VT, Movl);
37238       }
37239     }
37240 
37241     // Load a scalar integer constant directly to XMM instead of transferring an
37242     // immediate value from GPR.
37243     // vzext_movl (scalar_to_vector C) --> load [C,0...]
37244     if (N0.getOpcode() == ISD::SCALAR_TO_VECTOR) {
37245       if (auto *C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
37246         // Create a vector constant - scalar constant followed by zeros.
37247         EVT ScalarVT = N0.getOperand(0).getValueType();
37248         Type *ScalarTy = ScalarVT.getTypeForEVT(*DAG.getContext());
37249         unsigned NumElts = VT.getVectorNumElements();
37250         Constant *Zero = ConstantInt::getNullValue(ScalarTy);
37251         SmallVector<Constant *, 32> ConstantVec(NumElts, Zero);
37252         ConstantVec[0] = const_cast<ConstantInt *>(C->getConstantIntValue());
37253 
37254         // Load the vector constant from constant pool.
37255         MVT PVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
37256         SDValue CP = DAG.getConstantPool(ConstantVector::get(ConstantVec), PVT);
37257         MachinePointerInfo MPI =
37258             MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
37259         Align Alignment = cast<ConstantPoolSDNode>(CP)->getAlign();
37260         return DAG.getLoad(VT, DL, DAG.getEntryNode(), CP, MPI, Alignment,
37261                            MachineMemOperand::MOLoad);
37262       }
37263     }
37264 
37265     // Pull subvector inserts into undef through VZEXT_MOVL by making it an
37266     // insert into a zero vector. This helps get VZEXT_MOVL closer to
37267     // scalar_to_vectors where 256/512 are canonicalized to an insert and a
37268     // 128-bit scalar_to_vector. This reduces the number of isel patterns.
37269     if (!DCI.isBeforeLegalizeOps() && N0.hasOneUse()) {
37270       SDValue V = peekThroughOneUseBitcasts(N0);
37271 
37272       if (V.getOpcode() == ISD::INSERT_SUBVECTOR && V.getOperand(0).isUndef() &&
37273           isNullConstant(V.getOperand(2))) {
37274         SDValue In = V.getOperand(1);
37275         MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
37276                                      In.getValueSizeInBits() /
37277                                          VT.getScalarSizeInBits());
37278         In = DAG.getBitcast(SubVT, In);
37279         SDValue Movl = DAG.getNode(X86ISD::VZEXT_MOVL, DL, SubVT, In);
37280         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
37281                            getZeroVector(VT, Subtarget, DAG, DL), Movl,
37282                            V.getOperand(2));
37283       }
37284     }
37285 
37286     return SDValue();
37287   }
37288   case X86ISD::BLENDI: {
37289     SDValue N0 = N.getOperand(0);
37290     SDValue N1 = N.getOperand(1);
37291 
37292     // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
37293     // TODO: Handle MVT::v16i16 repeated blend mask.
37294     if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
37295         N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
37296       MVT SrcVT = N0.getOperand(0).getSimpleValueType();
37297       if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
37298           SrcVT.getScalarSizeInBits() >= 32) {
37299         unsigned BlendMask = N.getConstantOperandVal(2);
37300         unsigned Size = VT.getVectorNumElements();
37301         unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
37302         BlendMask = scaleVectorShuffleBlendMask(BlendMask, Size, Scale);
37303         return DAG.getBitcast(
37304             VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
37305                             N1.getOperand(0),
37306                             DAG.getTargetConstant(BlendMask, DL, MVT::i8)));
37307       }
37308     }
37309     return SDValue();
37310   }
37311   case X86ISD::VPERMI: {
37312     // vpermi(bitcast(x)) -> bitcast(vpermi(x)) for same number of elements.
37313     // TODO: Remove when we have preferred domains in combineX86ShuffleChain.
37314     SDValue N0 = N.getOperand(0);
37315     SDValue N1 = N.getOperand(1);
37316     unsigned EltSizeInBits = VT.getScalarSizeInBits();
37317     if (N0.getOpcode() == ISD::BITCAST &&
37318         N0.getOperand(0).getScalarValueSizeInBits() == EltSizeInBits) {
37319       SDValue Src = N0.getOperand(0);
37320       EVT SrcVT = Src.getValueType();
37321       SDValue Res = DAG.getNode(X86ISD::VPERMI, DL, SrcVT, Src, N1);
37322       return DAG.getBitcast(VT, Res);
37323     }
37324     return SDValue();
37325   }
37326   case X86ISD::VPERM2X128: {
37327     // Fold vperm2x128(bitcast(x),bitcast(y),c) -> bitcast(vperm2x128(x,y,c)).
37328     SDValue LHS = N->getOperand(0);
37329     SDValue RHS = N->getOperand(1);
37330     if (LHS.getOpcode() == ISD::BITCAST &&
37331         (RHS.getOpcode() == ISD::BITCAST || RHS.isUndef())) {
37332       EVT SrcVT = LHS.getOperand(0).getValueType();
37333       if (RHS.isUndef() || SrcVT == RHS.getOperand(0).getValueType()) {
37334         return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERM2X128, DL, SrcVT,
37335                                               DAG.getBitcast(SrcVT, LHS),
37336                                               DAG.getBitcast(SrcVT, RHS),
37337                                               N->getOperand(2)));
37338       }
37339     }
37340 
37341     // Fold vperm2x128(op(),op()) -> op(vperm2x128(),vperm2x128()).
37342     if (SDValue Res = canonicalizeLaneShuffleWithRepeatedOps(N, DAG, DL))
37343       return Res;
37344 
37345     // Fold vperm2x128 subvector shuffle with an inner concat pattern.
37346     // vperm2x128(concat(X,Y),concat(Z,W)) --> concat X,Y etc.
37347     auto FindSubVector128 = [&](unsigned Idx) {
37348       if (Idx > 3)
37349         return SDValue();
37350       SDValue Src = peekThroughBitcasts(N.getOperand(Idx < 2 ? 0 : 1));
37351       SmallVector<SDValue> SubOps;
37352       if (collectConcatOps(Src.getNode(), SubOps) && SubOps.size() == 2)
37353         return SubOps[Idx & 1];
37354       unsigned NumElts = Src.getValueType().getVectorNumElements();
37355       if ((Idx & 1) == 1 && Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
37356           Src.getOperand(1).getValueSizeInBits() == 128 &&
37357           Src.getConstantOperandAPInt(2) == (NumElts / 2)) {
37358         return Src.getOperand(1);
37359       }
37360       return SDValue();
37361     };
37362     unsigned Imm = N.getConstantOperandVal(2);
37363     if (SDValue SubLo = FindSubVector128(Imm & 0x0F)) {
37364       if (SDValue SubHi = FindSubVector128((Imm & 0xF0) >> 4)) {
37365         MVT SubVT = VT.getHalfNumVectorElementsVT();
37366         SubLo = DAG.getBitcast(SubVT, SubLo);
37367         SubHi = DAG.getBitcast(SubVT, SubHi);
37368         return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, SubLo, SubHi);
37369       }
37370     }
37371     return SDValue();
37372   }
37373   case X86ISD::PSHUFD:
37374   case X86ISD::PSHUFLW:
37375   case X86ISD::PSHUFHW:
37376     Mask = getPSHUFShuffleMask(N);
37377     assert(Mask.size() == 4);
37378     break;
37379   case X86ISD::MOVSD:
37380   case X86ISD::MOVSS: {
37381     SDValue N0 = N.getOperand(0);
37382     SDValue N1 = N.getOperand(1);
37383 
37384     // Canonicalize scalar FPOps:
37385     // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
37386     // If commutable, allow OP(N1[0], N0[0]).
37387     unsigned Opcode1 = N1.getOpcode();
37388     if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
37389         Opcode1 == ISD::FDIV) {
37390       SDValue N10 = N1.getOperand(0);
37391       SDValue N11 = N1.getOperand(1);
37392       if (N10 == N0 ||
37393           (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
37394         if (N10 != N0)
37395           std::swap(N10, N11);
37396         MVT SVT = VT.getVectorElementType();
37397         SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
37398         N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
37399         N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
37400         SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
37401         SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
37402         return DAG.getNode(Opcode, DL, VT, N0, SclVec);
37403       }
37404     }
37405 
37406     return SDValue();
37407   }
37408   case X86ISD::INSERTPS: {
37409     assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32");
37410     SDValue Op0 = N.getOperand(0);
37411     SDValue Op1 = N.getOperand(1);
37412     unsigned InsertPSMask = N.getConstantOperandVal(2);
37413     unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
37414     unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
37415     unsigned ZeroMask = InsertPSMask & 0xF;
37416 
37417     // If we zero out all elements from Op0 then we don't need to reference it.
37418     if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
37419       return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
37420                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
37421 
37422     // If we zero out the element from Op1 then we don't need to reference it.
37423     if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
37424       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
37425                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
37426 
37427     // Attempt to merge insertps Op1 with an inner target shuffle node.
37428     SmallVector<int, 8> TargetMask1;
37429     SmallVector<SDValue, 2> Ops1;
37430     APInt KnownUndef1, KnownZero1;
37431     if (getTargetShuffleAndZeroables(Op1, TargetMask1, Ops1, KnownUndef1,
37432                                      KnownZero1)) {
37433       if (KnownUndef1[SrcIdx] || KnownZero1[SrcIdx]) {
37434         // Zero/UNDEF insertion - zero out element and remove dependency.
37435         InsertPSMask |= (1u << DstIdx);
37436         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
37437                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
37438       }
37439       // Update insertps mask srcidx and reference the source input directly.
37440       int M = TargetMask1[SrcIdx];
37441       assert(0 <= M && M < 8 && "Shuffle index out of range");
37442       InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
37443       Op1 = Ops1[M < 4 ? 0 : 1];
37444       return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
37445                          DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
37446     }
37447 
37448     // Attempt to merge insertps Op0 with an inner target shuffle node.
37449     SmallVector<int, 8> TargetMask0;
37450     SmallVector<SDValue, 2> Ops0;
37451     APInt KnownUndef0, KnownZero0;
37452     if (getTargetShuffleAndZeroables(Op0, TargetMask0, Ops0, KnownUndef0,
37453                                      KnownZero0)) {
37454       bool Updated = false;
37455       bool UseInput00 = false;
37456       bool UseInput01 = false;
37457       for (int i = 0; i != 4; ++i) {
37458         if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
37459           // No change if element is already zero or the inserted element.
37460           continue;
37461         } else if (KnownUndef0[i] || KnownZero0[i]) {
37462           // If the target mask is undef/zero then we must zero the element.
37463           InsertPSMask |= (1u << i);
37464           Updated = true;
37465           continue;
37466         }
37467 
37468         // The input vector element must be inline.
37469         int M = TargetMask0[i];
37470         if (M != i && M != (i + 4))
37471           return SDValue();
37472 
37473         // Determine which inputs of the target shuffle we're using.
37474         UseInput00 |= (0 <= M && M < 4);
37475         UseInput01 |= (4 <= M);
37476       }
37477 
37478       // If we're not using both inputs of the target shuffle then use the
37479       // referenced input directly.
37480       if (UseInput00 && !UseInput01) {
37481         Updated = true;
37482         Op0 = Ops0[0];
37483       } else if (!UseInput00 && UseInput01) {
37484         Updated = true;
37485         Op0 = Ops0[1];
37486       }
37487 
37488       if (Updated)
37489         return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
37490                            DAG.getTargetConstant(InsertPSMask, DL, MVT::i8));
37491     }
37492 
37493     // If we're inserting an element from a vbroadcast load, fold the
37494     // load into the X86insertps instruction. We need to convert the scalar
37495     // load to a vector and clear the source lane of the INSERTPS control.
37496     if (Op1.getOpcode() == X86ISD::VBROADCAST_LOAD && Op1.hasOneUse()) {
37497       auto *MemIntr = cast<MemIntrinsicSDNode>(Op1);
37498       if (MemIntr->getMemoryVT().getScalarSizeInBits() == 32) {
37499         SDValue Load = DAG.getLoad(MVT::f32, DL, MemIntr->getChain(),
37500                                    MemIntr->getBasePtr(),
37501                                    MemIntr->getMemOperand());
37502         SDValue Insert = DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0,
37503                            DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT,
37504                                        Load),
37505                            DAG.getTargetConstant(InsertPSMask & 0x3f, DL, MVT::i8));
37506         DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
37507         return Insert;
37508       }
37509     }
37510 
37511     return SDValue();
37512   }
37513   default:
37514     return SDValue();
37515   }
37516 
37517   // Nuke no-op shuffles that show up after combining.
37518   if (isNoopShuffleMask(Mask))
37519     return N.getOperand(0);
37520 
37521   // Look for simplifications involving one or two shuffle instructions.
37522   SDValue V = N.getOperand(0);
37523   switch (N.getOpcode()) {
37524   default:
37525     break;
37526   case X86ISD::PSHUFLW:
37527   case X86ISD::PSHUFHW:
37528     assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
37529 
37530     // See if this reduces to a PSHUFD which is no more expensive and can
37531     // combine with more operations. Note that it has to at least flip the
37532     // dwords as otherwise it would have been removed as a no-op.
37533     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
37534       int DMask[] = {0, 1, 2, 3};
37535       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
37536       DMask[DOffset + 0] = DOffset + 1;
37537       DMask[DOffset + 1] = DOffset + 0;
37538       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
37539       V = DAG.getBitcast(DVT, V);
37540       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
37541                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
37542       return DAG.getBitcast(VT, V);
37543     }
37544 
37545     // Look for shuffle patterns which can be implemented as a single unpack.
37546     // FIXME: This doesn't handle the location of the PSHUFD generically, and
37547     // only works when we have a PSHUFD followed by two half-shuffles.
37548     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
37549         (V.getOpcode() == X86ISD::PSHUFLW ||
37550          V.getOpcode() == X86ISD::PSHUFHW) &&
37551         V.getOpcode() != N.getOpcode() &&
37552         V.hasOneUse() && V.getOperand(0).hasOneUse()) {
37553       SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
37554       if (D.getOpcode() == X86ISD::PSHUFD) {
37555         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
37556         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
37557         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
37558         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
37559         int WordMask[8];
37560         for (int i = 0; i < 4; ++i) {
37561           WordMask[i + NOffset] = Mask[i] + NOffset;
37562           WordMask[i + VOffset] = VMask[i] + VOffset;
37563         }
37564         // Map the word mask through the DWord mask.
37565         int MappedMask[8];
37566         for (int i = 0; i < 8; ++i)
37567           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
37568         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
37569             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
37570           // We can replace all three shuffles with an unpack.
37571           V = DAG.getBitcast(VT, D.getOperand(0));
37572           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
37573                                                 : X86ISD::UNPCKH,
37574                              DL, VT, V, V);
37575         }
37576       }
37577     }
37578 
37579     break;
37580 
37581   case X86ISD::PSHUFD:
37582     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
37583       return NewN;
37584 
37585     break;
37586   }
37587 
37588   return SDValue();
37589 }
37590 
37591 /// Checks if the shuffle mask takes subsequent elements
37592 /// alternately from two vectors.
37593 /// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
37594 static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
37595 
37596   int ParitySrc[2] = {-1, -1};
37597   unsigned Size = Mask.size();
37598   for (unsigned i = 0; i != Size; ++i) {
37599     int M = Mask[i];
37600     if (M < 0)
37601       continue;
37602 
37603     // Make sure we are using the matching element from the input.
37604     if ((M % Size) != i)
37605       return false;
37606 
37607     // Make sure we use the same input for all elements of the same parity.
37608     int Src = M / Size;
37609     if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
37610       return false;
37611     ParitySrc[i % 2] = Src;
37612   }
37613 
37614   // Make sure each input is used.
37615   if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
37616     return false;
37617 
37618   Op0Even = ParitySrc[0] == 0;
37619   return true;
37620 }
37621 
37622 /// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
37623 /// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
37624 /// are written to the parameters \p Opnd0 and \p Opnd1.
37625 ///
37626 /// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
37627 /// so it is easier to generically match. We also insert dummy vector shuffle
37628 /// nodes for the operands which explicitly discard the lanes which are unused
37629 /// by this operation to try to flow through the rest of the combiner
37630 /// the fact that they're unused.
37631 static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
37632                              SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
37633                              bool &IsSubAdd) {
37634 
37635   EVT VT = N->getValueType(0);
37636   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37637   if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
37638       !VT.getSimpleVT().isFloatingPoint())
37639     return false;
37640 
37641   // We only handle target-independent shuffles.
37642   // FIXME: It would be easy and harmless to use the target shuffle mask
37643   // extraction tool to support more.
37644   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
37645     return false;
37646 
37647   SDValue V1 = N->getOperand(0);
37648   SDValue V2 = N->getOperand(1);
37649 
37650   // Make sure we have an FADD and an FSUB.
37651   if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
37652       (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
37653       V1.getOpcode() == V2.getOpcode())
37654     return false;
37655 
37656   // If there are other uses of these operations we can't fold them.
37657   if (!V1->hasOneUse() || !V2->hasOneUse())
37658     return false;
37659 
37660   // Ensure that both operations have the same operands. Note that we can
37661   // commute the FADD operands.
37662   SDValue LHS, RHS;
37663   if (V1.getOpcode() == ISD::FSUB) {
37664     LHS = V1->getOperand(0); RHS = V1->getOperand(1);
37665     if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
37666         (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
37667       return false;
37668   } else {
37669     assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode");
37670     LHS = V2->getOperand(0); RHS = V2->getOperand(1);
37671     if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
37672         (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
37673       return false;
37674   }
37675 
37676   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
37677   bool Op0Even;
37678   if (!isAddSubOrSubAddMask(Mask, Op0Even))
37679     return false;
37680 
37681   // It's a subadd if the vector in the even parity is an FADD.
37682   IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
37683                      : V2->getOpcode() == ISD::FADD;
37684 
37685   Opnd0 = LHS;
37686   Opnd1 = RHS;
37687   return true;
37688 }
37689 
37690 /// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
37691 static SDValue combineShuffleToFMAddSub(SDNode *N,
37692                                         const X86Subtarget &Subtarget,
37693                                         SelectionDAG &DAG) {
37694   // We only handle target-independent shuffles.
37695   // FIXME: It would be easy and harmless to use the target shuffle mask
37696   // extraction tool to support more.
37697   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
37698     return SDValue();
37699 
37700   MVT VT = N->getSimpleValueType(0);
37701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37702   if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
37703     return SDValue();
37704 
37705   // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
37706   SDValue Op0 = N->getOperand(0);
37707   SDValue Op1 = N->getOperand(1);
37708   SDValue FMAdd = Op0, FMSub = Op1;
37709   if (FMSub.getOpcode() != X86ISD::FMSUB)
37710     std::swap(FMAdd, FMSub);
37711 
37712   if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
37713       FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
37714       FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
37715       FMAdd.getOperand(2) != FMSub.getOperand(2))
37716     return SDValue();
37717 
37718   // Check for correct shuffle mask.
37719   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
37720   bool Op0Even;
37721   if (!isAddSubOrSubAddMask(Mask, Op0Even))
37722     return SDValue();
37723 
37724   // FMAddSub takes zeroth operand from FMSub node.
37725   SDLoc DL(N);
37726   bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
37727   unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
37728   return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
37729                      FMAdd.getOperand(2));
37730 }
37731 
37732 /// Try to combine a shuffle into a target-specific add-sub or
37733 /// mul-add-sub node.
37734 static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
37735                                                 const X86Subtarget &Subtarget,
37736                                                 SelectionDAG &DAG) {
37737   if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
37738     return V;
37739 
37740   SDValue Opnd0, Opnd1;
37741   bool IsSubAdd;
37742   if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
37743     return SDValue();
37744 
37745   MVT VT = N->getSimpleValueType(0);
37746   SDLoc DL(N);
37747 
37748   // Try to generate X86ISD::FMADDSUB node here.
37749   SDValue Opnd2;
37750   if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
37751     unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
37752     return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
37753   }
37754 
37755   if (IsSubAdd)
37756     return SDValue();
37757 
37758   // Do not generate X86ISD::ADDSUB node for 512-bit types even though
37759   // the ADDSUB idiom has been successfully recognized. There are no known
37760   // X86 targets with 512-bit ADDSUB instructions!
37761   if (VT.is512BitVector())
37762     return SDValue();
37763 
37764   return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
37765 }
37766 
37767 // We are looking for a shuffle where both sources are concatenated with undef
37768 // and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
37769 // if we can express this as a single-source shuffle, that's preferable.
37770 static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
37771                                            const X86Subtarget &Subtarget) {
37772   if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
37773     return SDValue();
37774 
37775   EVT VT = N->getValueType(0);
37776 
37777   // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
37778   if (!VT.is128BitVector() && !VT.is256BitVector())
37779     return SDValue();
37780 
37781   if (VT.getVectorElementType() != MVT::i32 &&
37782       VT.getVectorElementType() != MVT::i64 &&
37783       VT.getVectorElementType() != MVT::f32 &&
37784       VT.getVectorElementType() != MVT::f64)
37785     return SDValue();
37786 
37787   SDValue N0 = N->getOperand(0);
37788   SDValue N1 = N->getOperand(1);
37789 
37790   // Check that both sources are concats with undef.
37791   if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
37792       N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
37793       N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
37794       !N1.getOperand(1).isUndef())
37795     return SDValue();
37796 
37797   // Construct the new shuffle mask. Elements from the first source retain their
37798   // index, but elements from the second source no longer need to skip an undef.
37799   SmallVector<int, 8> Mask;
37800   int NumElts = VT.getVectorNumElements();
37801 
37802   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
37803   for (int Elt : SVOp->getMask())
37804     Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
37805 
37806   SDLoc DL(N);
37807   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
37808                                N1.getOperand(0));
37809   return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
37810 }
37811 
37812 /// Eliminate a redundant shuffle of a horizontal math op.
37813 static SDValue foldShuffleOfHorizOp(SDNode *N, SelectionDAG &DAG) {
37814   // TODO: Can we use getTargetShuffleInputs instead?
37815   unsigned Opcode = N->getOpcode();
37816   if (Opcode != X86ISD::MOVDDUP && Opcode != X86ISD::VBROADCAST)
37817     if (Opcode != X86ISD::UNPCKL && Opcode != X86ISD::UNPCKH)
37818       if (Opcode != ISD::VECTOR_SHUFFLE || !N->getOperand(1).isUndef())
37819         return SDValue();
37820 
37821   // For a broadcast, peek through an extract element of index 0 to find the
37822   // horizontal op: broadcast (ext_vec_elt HOp, 0)
37823   EVT VT = N->getValueType(0);
37824   if (Opcode == X86ISD::VBROADCAST) {
37825     SDValue SrcOp = N->getOperand(0);
37826     if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
37827         SrcOp.getValueType() == MVT::f64 &&
37828         SrcOp.getOperand(0).getValueType() == VT &&
37829         isNullConstant(SrcOp.getOperand(1)))
37830       N = SrcOp.getNode();
37831   }
37832 
37833   SDValue HOp = N->getOperand(0);
37834   if (HOp.getOpcode() != X86ISD::HADD && HOp.getOpcode() != X86ISD::FHADD &&
37835       HOp.getOpcode() != X86ISD::HSUB && HOp.getOpcode() != X86ISD::FHSUB)
37836     return SDValue();
37837 
37838   // unpcklo(hop(x,y),hop(z,w)) -> permute(hop(x,z)).
37839   // unpckhi(hop(x,y),hop(z,w)) -> permute(hop(y,w)).
37840   // Don't fold if hop(x,y) == hop(z,w).
37841   if (Opcode == X86ISD::UNPCKL || Opcode == X86ISD::UNPCKH) {
37842     SDValue HOp2 = N->getOperand(1);
37843     if (HOp.getOpcode() != HOp2.getOpcode() || VT.getScalarSizeInBits() != 32)
37844       return SDValue();
37845     if (HOp == HOp2)
37846       return SDValue();
37847     SDLoc DL(HOp);
37848     unsigned LoHi = Opcode == X86ISD::UNPCKL ? 0 : 1;
37849     SDValue Res = DAG.getNode(HOp.getOpcode(), DL, VT, HOp.getOperand(LoHi),
37850                               HOp2.getOperand(LoHi));
37851     // Use SHUFPS for the permute so this will work on SSE3 targets, shuffle
37852     // combining and domain handling will simplify this later on.
37853     EVT ShuffleVT = VT.changeVectorElementType(MVT::f32);
37854     Res = DAG.getBitcast(ShuffleVT, Res);
37855     Res = DAG.getNode(X86ISD::SHUFP, DL, ShuffleVT, Res, Res,
37856                       getV4X86ShuffleImm8ForMask({0, 2, 1, 3}, DL, DAG));
37857     return DAG.getBitcast(VT, Res);
37858   }
37859 
37860   // 128-bit horizontal math instructions are defined to operate on adjacent
37861   // lanes of each operand as:
37862   // v4X32: A[0] + A[1] , A[2] + A[3] , B[0] + B[1] , B[2] + B[3]
37863   // ...similarly for v2f64 and v8i16.
37864   if (!HOp.getOperand(0).isUndef() && !HOp.getOperand(1).isUndef() &&
37865       HOp.getOperand(0) != HOp.getOperand(1))
37866     return SDValue();
37867 
37868   // The shuffle that we are eliminating may have allowed the horizontal op to
37869   // have an undemanded (undefined) operand. Duplicate the other (defined)
37870   // operand to ensure that the results are defined across all lanes without the
37871   // shuffle.
37872   auto updateHOp = [](SDValue HorizOp, SelectionDAG &DAG) {
37873     SDValue X;
37874     if (HorizOp.getOperand(0).isUndef()) {
37875       assert(!HorizOp.getOperand(1).isUndef() && "Not expecting foldable h-op");
37876       X = HorizOp.getOperand(1);
37877     } else if (HorizOp.getOperand(1).isUndef()) {
37878       assert(!HorizOp.getOperand(0).isUndef() && "Not expecting foldable h-op");
37879       X = HorizOp.getOperand(0);
37880     } else {
37881       return HorizOp;
37882     }
37883     return DAG.getNode(HorizOp.getOpcode(), SDLoc(HorizOp),
37884                        HorizOp.getValueType(), X, X);
37885   };
37886 
37887   // When the operands of a horizontal math op are identical, the low half of
37888   // the result is the same as the high half. If a target shuffle is also
37889   // replicating low and high halves (and without changing the type/length of
37890   // the vector), we don't need the shuffle.
37891   if (Opcode == X86ISD::MOVDDUP || Opcode == X86ISD::VBROADCAST) {
37892     if (Opcode == X86ISD::VBROADCAST && !VT.is128BitVector())
37893       return SDValue();
37894     if (HOp.getScalarValueSizeInBits() == 64 && HOp.getValueType() == VT) {
37895       // movddup (hadd X, X) --> hadd X, X
37896       // broadcast (extract_vec_elt (hadd X, X), 0) --> hadd X, X
37897       assert((HOp.getValueType() == MVT::v2f64 ||
37898               HOp.getValueType() == MVT::v4f64) && "Unexpected type for h-op");
37899       return updateHOp(HOp, DAG);
37900     }
37901     return SDValue();
37902   }
37903 
37904   // shuffle (hadd X, X), undef, [low half...high half] --> hadd X, X
37905   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
37906 
37907   // TODO: Other mask possibilities like {1,1} and {1,0} could be added here,
37908   // but this should be tied to whatever horizontal op matching and shuffle
37909   // canonicalization are producing.
37910   if (HOp.getValueSizeInBits() == 128 &&
37911       (isShuffleEquivalent(Mask, {0, 0}) ||
37912        isShuffleEquivalent(Mask, {0, 1, 0, 1}) ||
37913        isShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3})))
37914     return updateHOp(HOp, DAG);
37915 
37916   if (HOp.getValueSizeInBits() == 256 &&
37917       (isShuffleEquivalent(Mask, {0, 0, 2, 2}) ||
37918        isShuffleEquivalent(Mask, {0, 1, 0, 1, 4, 5, 4, 5}) ||
37919        isShuffleEquivalent(
37920            Mask, {0, 1, 2, 3, 0, 1, 2, 3, 8, 9, 10, 11, 8, 9, 10, 11})))
37921     return updateHOp(HOp, DAG);
37922 
37923   return SDValue();
37924 }
37925 
37926 /// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
37927 /// low half of each source vector and does not set any high half elements in
37928 /// the destination vector, narrow the shuffle to half its original size.
37929 static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
37930   if (!Shuf->getValueType(0).isSimple())
37931     return SDValue();
37932   MVT VT = Shuf->getSimpleValueType(0);
37933   if (!VT.is256BitVector() && !VT.is512BitVector())
37934     return SDValue();
37935 
37936   // See if we can ignore all of the high elements of the shuffle.
37937   ArrayRef<int> Mask = Shuf->getMask();
37938   if (!isUndefUpperHalf(Mask))
37939     return SDValue();
37940 
37941   // Check if the shuffle mask accesses only the low half of each input vector
37942   // (half-index output is 0 or 2).
37943   int HalfIdx1, HalfIdx2;
37944   SmallVector<int, 8> HalfMask(Mask.size() / 2);
37945   if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
37946       (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
37947     return SDValue();
37948 
37949   // Create a half-width shuffle to replace the unnecessarily wide shuffle.
37950   // The trick is knowing that all of the insert/extract are actually free
37951   // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
37952   // of narrow inputs into a narrow output, and that is always cheaper than
37953   // the wide shuffle that we started with.
37954   return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
37955                                Shuf->getOperand(1), HalfMask, HalfIdx1,
37956                                HalfIdx2, false, DAG, /*UseConcat*/true);
37957 }
37958 
37959 static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
37960                               TargetLowering::DAGCombinerInfo &DCI,
37961                               const X86Subtarget &Subtarget) {
37962   if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
37963     if (SDValue V = narrowShuffle(Shuf, DAG))
37964       return V;
37965 
37966   // If we have legalized the vector types, look for blends of FADD and FSUB
37967   // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
37968   SDLoc dl(N);
37969   EVT VT = N->getValueType(0);
37970   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37971   if (TLI.isTypeLegal(VT)) {
37972     if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
37973       return AddSub;
37974 
37975     if (SDValue HAddSub = foldShuffleOfHorizOp(N, DAG))
37976       return HAddSub;
37977 
37978     // Merge shuffles through binops if its likely we'll be able to merge it
37979     // with other shuffles (as long as they aren't splats).
37980     // shuffle(bop(shuffle(x,y),shuffle(z,w)),bop(shuffle(a,b),shuffle(c,d)))
37981     // TODO: We might be able to move this to DAGCombiner::visitVECTOR_SHUFFLE.
37982     if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(N)) {
37983       unsigned SrcOpcode = N->getOperand(0).getOpcode();
37984       if (SrcOpcode == N->getOperand(1).getOpcode() && TLI.isBinOp(SrcOpcode) &&
37985           N->isOnlyUserOf(N->getOperand(0).getNode()) &&
37986           N->isOnlyUserOf(N->getOperand(1).getNode())) {
37987         SDValue Op00 = N->getOperand(0).getOperand(0);
37988         SDValue Op10 = N->getOperand(1).getOperand(0);
37989         SDValue Op01 = N->getOperand(0).getOperand(1);
37990         SDValue Op11 = N->getOperand(1).getOperand(1);
37991         auto *SVN00 = dyn_cast<ShuffleVectorSDNode>(Op00);
37992         auto *SVN10 = dyn_cast<ShuffleVectorSDNode>(Op10);
37993         auto *SVN01 = dyn_cast<ShuffleVectorSDNode>(Op01);
37994         auto *SVN11 = dyn_cast<ShuffleVectorSDNode>(Op11);
37995         if (((SVN00 && !SVN00->isSplat()) || (SVN10 && !SVN10->isSplat())) &&
37996             ((SVN01 && !SVN01->isSplat()) || (SVN11 && !SVN11->isSplat()))) {
37997           SDLoc DL(N);
37998           ArrayRef<int> Mask = SVN->getMask();
37999           SDValue LHS = DAG.getVectorShuffle(VT, DL, Op00, Op10, Mask);
38000           SDValue RHS = DAG.getVectorShuffle(VT, DL, Op01, Op11, Mask);
38001           return DAG.getNode(SrcOpcode, DL, VT, LHS, RHS);
38002         }
38003       }
38004     }
38005   }
38006 
38007   // Attempt to combine into a vector load/broadcast.
38008   if (SDValue LD = combineToConsecutiveLoads(VT, SDValue(N, 0), dl, DAG,
38009                                              Subtarget, true))
38010     return LD;
38011 
38012   // For AVX2, we sometimes want to combine
38013   // (vector_shuffle <mask> (concat_vectors t1, undef)
38014   //                        (concat_vectors t2, undef))
38015   // Into:
38016   // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
38017   // Since the latter can be efficiently lowered with VPERMD/VPERMQ
38018   if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
38019     return ShufConcat;
38020 
38021   if (isTargetShuffle(N->getOpcode())) {
38022     SDValue Op(N, 0);
38023     if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
38024       return Shuffle;
38025 
38026     // Try recursively combining arbitrary sequences of x86 shuffle
38027     // instructions into higher-order shuffles. We do this after combining
38028     // specific PSHUF instruction sequences into their minimal form so that we
38029     // can evaluate how many specialized shuffle instructions are involved in
38030     // a particular chain.
38031     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
38032       return Res;
38033 
38034     // Simplify source operands based on shuffle mask.
38035     // TODO - merge this into combineX86ShufflesRecursively.
38036     APInt KnownUndef, KnownZero;
38037     APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
38038     if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
38039                                        DCI))
38040       return SDValue(N, 0);
38041   }
38042 
38043   return SDValue();
38044 }
38045 
38046 // Simplify variable target shuffle masks based on the demanded elements.
38047 // TODO: Handle DemandedBits in mask indices as well?
38048 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetShuffle(
38049     SDValue Op, const APInt &DemandedElts, unsigned MaskIndex,
38050     TargetLowering::TargetLoweringOpt &TLO, unsigned Depth) const {
38051   // If we're demanding all elements don't bother trying to simplify the mask.
38052   unsigned NumElts = DemandedElts.getBitWidth();
38053   if (DemandedElts.isAllOnesValue())
38054     return false;
38055 
38056   SDValue Mask = Op.getOperand(MaskIndex);
38057   if (!Mask.hasOneUse())
38058     return false;
38059 
38060   // Attempt to generically simplify the variable shuffle mask.
38061   APInt MaskUndef, MaskZero;
38062   if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
38063                                  Depth + 1))
38064     return true;
38065 
38066   // Attempt to extract+simplify a (constant pool load) shuffle mask.
38067   // TODO: Support other types from getTargetShuffleMaskIndices?
38068   SDValue BC = peekThroughOneUseBitcasts(Mask);
38069   EVT BCVT = BC.getValueType();
38070   auto *Load = dyn_cast<LoadSDNode>(BC);
38071   if (!Load)
38072     return false;
38073 
38074   const Constant *C = getTargetConstantFromNode(Load);
38075   if (!C)
38076     return false;
38077 
38078   Type *CTy = C->getType();
38079   if (!CTy->isVectorTy() ||
38080       CTy->getPrimitiveSizeInBits() != Mask.getValueSizeInBits())
38081     return false;
38082 
38083   // Handle scaling for i64 elements on 32-bit targets.
38084   unsigned NumCstElts = cast<FixedVectorType>(CTy)->getNumElements();
38085   if (NumCstElts != NumElts && NumCstElts != (NumElts * 2))
38086     return false;
38087   unsigned Scale = NumCstElts / NumElts;
38088 
38089   // Simplify mask if we have an undemanded element that is not undef.
38090   bool Simplified = false;
38091   SmallVector<Constant *, 32> ConstVecOps;
38092   for (unsigned i = 0; i != NumCstElts; ++i) {
38093     Constant *Elt = C->getAggregateElement(i);
38094     if (!DemandedElts[i / Scale] && !isa<UndefValue>(Elt)) {
38095       ConstVecOps.push_back(UndefValue::get(Elt->getType()));
38096       Simplified = true;
38097       continue;
38098     }
38099     ConstVecOps.push_back(Elt);
38100   }
38101   if (!Simplified)
38102     return false;
38103 
38104   // Generate new constant pool entry + legalize immediately for the load.
38105   SDLoc DL(Op);
38106   SDValue CV = TLO.DAG.getConstantPool(ConstantVector::get(ConstVecOps), BCVT);
38107   SDValue LegalCV = LowerConstantPool(CV, TLO.DAG);
38108   SDValue NewMask = TLO.DAG.getLoad(
38109       BCVT, DL, TLO.DAG.getEntryNode(), LegalCV,
38110       MachinePointerInfo::getConstantPool(TLO.DAG.getMachineFunction()),
38111       Load->getAlign());
38112   return TLO.CombineTo(Mask, TLO.DAG.getBitcast(Mask.getValueType(), NewMask));
38113 }
38114 
38115 bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
38116     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
38117     TargetLoweringOpt &TLO, unsigned Depth) const {
38118   int NumElts = DemandedElts.getBitWidth();
38119   unsigned Opc = Op.getOpcode();
38120   EVT VT = Op.getValueType();
38121 
38122   // Handle special case opcodes.
38123   switch (Opc) {
38124   case X86ISD::PMULDQ:
38125   case X86ISD::PMULUDQ: {
38126     APInt LHSUndef, LHSZero;
38127     APInt RHSUndef, RHSZero;
38128     SDValue LHS = Op.getOperand(0);
38129     SDValue RHS = Op.getOperand(1);
38130     if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
38131                                    Depth + 1))
38132       return true;
38133     if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
38134                                    Depth + 1))
38135       return true;
38136     // Multiply by zero.
38137     KnownZero = LHSZero | RHSZero;
38138     break;
38139   }
38140   case X86ISD::VSHL:
38141   case X86ISD::VSRL:
38142   case X86ISD::VSRA: {
38143     // We only need the bottom 64-bits of the (128-bit) shift amount.
38144     SDValue Amt = Op.getOperand(1);
38145     MVT AmtVT = Amt.getSimpleValueType();
38146     assert(AmtVT.is128BitVector() && "Unexpected value type");
38147 
38148     // If we reuse the shift amount just for sse shift amounts then we know that
38149     // only the bottom 64-bits are only ever used.
38150     bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
38151       unsigned UseOpc = Use->getOpcode();
38152       return (UseOpc == X86ISD::VSHL || UseOpc == X86ISD::VSRL ||
38153               UseOpc == X86ISD::VSRA) &&
38154              Use->getOperand(0) != Amt;
38155     });
38156 
38157     APInt AmtUndef, AmtZero;
38158     unsigned NumAmtElts = AmtVT.getVectorNumElements();
38159     APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
38160     if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
38161                                    Depth + 1, AssumeSingleUse))
38162       return true;
38163     LLVM_FALLTHROUGH;
38164   }
38165   case X86ISD::VSHLI:
38166   case X86ISD::VSRLI:
38167   case X86ISD::VSRAI: {
38168     SDValue Src = Op.getOperand(0);
38169     APInt SrcUndef;
38170     if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
38171                                    Depth + 1))
38172       return true;
38173 
38174     // Aggressively peek through ops to get at the demanded elts.
38175     if (!DemandedElts.isAllOnesValue())
38176       if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
38177               Src, DemandedElts, TLO.DAG, Depth + 1))
38178         return TLO.CombineTo(
38179             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc, Op.getOperand(1)));
38180     break;
38181   }
38182   case X86ISD::KSHIFTL: {
38183     SDValue Src = Op.getOperand(0);
38184     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
38185     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
38186     unsigned ShiftAmt = Amt->getZExtValue();
38187 
38188     if (ShiftAmt == 0)
38189       return TLO.CombineTo(Op, Src);
38190 
38191     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
38192     // single shift.  We can do this if the bottom bits (which are shifted
38193     // out) are never demanded.
38194     if (Src.getOpcode() == X86ISD::KSHIFTR) {
38195       if (!DemandedElts.intersects(APInt::getLowBitsSet(NumElts, ShiftAmt))) {
38196         unsigned C1 = Src.getConstantOperandVal(1);
38197         unsigned NewOpc = X86ISD::KSHIFTL;
38198         int Diff = ShiftAmt - C1;
38199         if (Diff < 0) {
38200           Diff = -Diff;
38201           NewOpc = X86ISD::KSHIFTR;
38202         }
38203 
38204         SDLoc dl(Op);
38205         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
38206         return TLO.CombineTo(
38207             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
38208       }
38209     }
38210 
38211     APInt DemandedSrc = DemandedElts.lshr(ShiftAmt);
38212     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
38213                                    Depth + 1))
38214       return true;
38215 
38216     KnownUndef <<= ShiftAmt;
38217     KnownZero <<= ShiftAmt;
38218     KnownZero.setLowBits(ShiftAmt);
38219     break;
38220   }
38221   case X86ISD::KSHIFTR: {
38222     SDValue Src = Op.getOperand(0);
38223     auto *Amt = cast<ConstantSDNode>(Op.getOperand(1));
38224     assert(Amt->getAPIntValue().ult(NumElts) && "Out of range shift amount");
38225     unsigned ShiftAmt = Amt->getZExtValue();
38226 
38227     if (ShiftAmt == 0)
38228       return TLO.CombineTo(Op, Src);
38229 
38230     // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
38231     // single shift.  We can do this if the top bits (which are shifted
38232     // out) are never demanded.
38233     if (Src.getOpcode() == X86ISD::KSHIFTL) {
38234       if (!DemandedElts.intersects(APInt::getHighBitsSet(NumElts, ShiftAmt))) {
38235         unsigned C1 = Src.getConstantOperandVal(1);
38236         unsigned NewOpc = X86ISD::KSHIFTR;
38237         int Diff = ShiftAmt - C1;
38238         if (Diff < 0) {
38239           Diff = -Diff;
38240           NewOpc = X86ISD::KSHIFTL;
38241         }
38242 
38243         SDLoc dl(Op);
38244         SDValue NewSA = TLO.DAG.getTargetConstant(Diff, dl, MVT::i8);
38245         return TLO.CombineTo(
38246             Op, TLO.DAG.getNode(NewOpc, dl, VT, Src.getOperand(0), NewSA));
38247       }
38248     }
38249 
38250     APInt DemandedSrc = DemandedElts.shl(ShiftAmt);
38251     if (SimplifyDemandedVectorElts(Src, DemandedSrc, KnownUndef, KnownZero, TLO,
38252                                    Depth + 1))
38253       return true;
38254 
38255     KnownUndef.lshrInPlace(ShiftAmt);
38256     KnownZero.lshrInPlace(ShiftAmt);
38257     KnownZero.setHighBits(ShiftAmt);
38258     break;
38259   }
38260   case X86ISD::CVTSI2P:
38261   case X86ISD::CVTUI2P: {
38262     SDValue Src = Op.getOperand(0);
38263     MVT SrcVT = Src.getSimpleValueType();
38264     APInt SrcUndef, SrcZero;
38265     APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
38266     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
38267                                    Depth + 1))
38268       return true;
38269     break;
38270   }
38271   case X86ISD::PACKSS:
38272   case X86ISD::PACKUS: {
38273     SDValue N0 = Op.getOperand(0);
38274     SDValue N1 = Op.getOperand(1);
38275 
38276     APInt DemandedLHS, DemandedRHS;
38277     getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
38278 
38279     APInt SrcUndef, SrcZero;
38280     if (SimplifyDemandedVectorElts(N0, DemandedLHS, SrcUndef, SrcZero, TLO,
38281                                    Depth + 1))
38282       return true;
38283     if (SimplifyDemandedVectorElts(N1, DemandedRHS, SrcUndef, SrcZero, TLO,
38284                                    Depth + 1))
38285       return true;
38286 
38287     // Aggressively peek through ops to get at the demanded elts.
38288     // TODO - we should do this for all target/faux shuffles ops.
38289     if (!DemandedElts.isAllOnesValue()) {
38290       SDValue NewN0 = SimplifyMultipleUseDemandedVectorElts(N0, DemandedLHS,
38291                                                             TLO.DAG, Depth + 1);
38292       SDValue NewN1 = SimplifyMultipleUseDemandedVectorElts(N1, DemandedRHS,
38293                                                             TLO.DAG, Depth + 1);
38294       if (NewN0 || NewN1) {
38295         NewN0 = NewN0 ? NewN0 : N0;
38296         NewN1 = NewN1 ? NewN1 : N1;
38297         return TLO.CombineTo(Op,
38298                              TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewN0, NewN1));
38299       }
38300     }
38301     break;
38302   }
38303   case X86ISD::HADD:
38304   case X86ISD::HSUB:
38305   case X86ISD::FHADD:
38306   case X86ISD::FHSUB: {
38307     APInt DemandedLHS, DemandedRHS;
38308     getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
38309 
38310     APInt LHSUndef, LHSZero;
38311     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, LHSUndef,
38312                                    LHSZero, TLO, Depth + 1))
38313       return true;
38314     APInt RHSUndef, RHSZero;
38315     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, RHSUndef,
38316                                    RHSZero, TLO, Depth + 1))
38317       return true;
38318     break;
38319   }
38320   case X86ISD::VTRUNC:
38321   case X86ISD::VTRUNCS:
38322   case X86ISD::VTRUNCUS: {
38323     SDValue Src = Op.getOperand(0);
38324     MVT SrcVT = Src.getSimpleValueType();
38325     APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
38326     APInt SrcUndef, SrcZero;
38327     if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
38328                                    Depth + 1))
38329       return true;
38330     KnownZero = SrcZero.zextOrTrunc(NumElts);
38331     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
38332     break;
38333   }
38334   case X86ISD::BLENDV: {
38335     APInt SelUndef, SelZero;
38336     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
38337                                    SelZero, TLO, Depth + 1))
38338       return true;
38339 
38340     // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
38341     APInt LHSUndef, LHSZero;
38342     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
38343                                    LHSZero, TLO, Depth + 1))
38344       return true;
38345 
38346     APInt RHSUndef, RHSZero;
38347     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
38348                                    RHSZero, TLO, Depth + 1))
38349       return true;
38350 
38351     KnownZero = LHSZero & RHSZero;
38352     KnownUndef = LHSUndef & RHSUndef;
38353     break;
38354   }
38355   case X86ISD::VZEXT_MOVL: {
38356     // If upper demanded elements are already zero then we have nothing to do.
38357     SDValue Src = Op.getOperand(0);
38358     APInt DemandedUpperElts = DemandedElts;
38359     DemandedUpperElts.clearLowBits(1);
38360     if (TLO.DAG.computeKnownBits(Src, DemandedUpperElts, Depth + 1).isZero())
38361       return TLO.CombineTo(Op, Src);
38362     break;
38363   }
38364   case X86ISD::VBROADCAST: {
38365     SDValue Src = Op.getOperand(0);
38366     MVT SrcVT = Src.getSimpleValueType();
38367     if (!SrcVT.isVector())
38368       break;
38369     // Don't bother broadcasting if we just need the 0'th element.
38370     if (DemandedElts == 1) {
38371       if (Src.getValueType() != VT)
38372         Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
38373                              SDLoc(Op));
38374       return TLO.CombineTo(Op, Src);
38375     }
38376     APInt SrcUndef, SrcZero;
38377     APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
38378     if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
38379                                    Depth + 1))
38380       return true;
38381     // Aggressively peek through src to get at the demanded elt.
38382     // TODO - we should do this for all target/faux shuffles ops.
38383     if (SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
38384             Src, SrcElts, TLO.DAG, Depth + 1))
38385       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
38386     break;
38387   }
38388   case X86ISD::VPERMV:
38389     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 0, TLO,
38390                                                    Depth))
38391       return true;
38392     break;
38393   case X86ISD::PSHUFB:
38394   case X86ISD::VPERMV3:
38395   case X86ISD::VPERMILPV:
38396     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 1, TLO,
38397                                                    Depth))
38398       return true;
38399     break;
38400   case X86ISD::VPPERM:
38401   case X86ISD::VPERMIL2:
38402     if (SimplifyDemandedVectorEltsForTargetShuffle(Op, DemandedElts, 2, TLO,
38403                                                    Depth))
38404       return true;
38405     break;
38406   }
38407 
38408   // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
38409   // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
38410   // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
38411   if ((VT.is256BitVector() || VT.is512BitVector()) &&
38412       DemandedElts.lshr(NumElts / 2) == 0) {
38413     unsigned SizeInBits = VT.getSizeInBits();
38414     unsigned ExtSizeInBits = SizeInBits / 2;
38415 
38416     // See if 512-bit ops only use the bottom 128-bits.
38417     if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
38418       ExtSizeInBits = SizeInBits / 4;
38419 
38420     switch (Opc) {
38421       // Scalar broadcast.
38422     case X86ISD::VBROADCAST: {
38423       SDLoc DL(Op);
38424       SDValue Src = Op.getOperand(0);
38425       if (Src.getValueSizeInBits() > ExtSizeInBits)
38426         Src = extractSubVector(Src, 0, TLO.DAG, DL, ExtSizeInBits);
38427       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
38428                                     ExtSizeInBits / VT.getScalarSizeInBits());
38429       SDValue Bcst = TLO.DAG.getNode(X86ISD::VBROADCAST, DL, BcstVT, Src);
38430       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
38431                                                TLO.DAG, DL, ExtSizeInBits));
38432     }
38433     case X86ISD::VBROADCAST_LOAD: {
38434       SDLoc DL(Op);
38435       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
38436       EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
38437                                     ExtSizeInBits / VT.getScalarSizeInBits());
38438       SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
38439       SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
38440       SDValue Bcst = TLO.DAG.getMemIntrinsicNode(
38441           X86ISD::VBROADCAST_LOAD, DL, Tys, Ops, MemIntr->getMemoryVT(),
38442           MemIntr->getMemOperand());
38443       TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
38444                                            Bcst.getValue(1));
38445       return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
38446                                                TLO.DAG, DL, ExtSizeInBits));
38447     }
38448       // Subvector broadcast.
38449     case X86ISD::SUBV_BROADCAST_LOAD: {
38450       auto *MemIntr = cast<MemIntrinsicSDNode>(Op);
38451       EVT MemVT = MemIntr->getMemoryVT();
38452       if (ExtSizeInBits == MemVT.getStoreSizeInBits()) {
38453         SDLoc DL(Op);
38454         SDValue Ld =
38455             TLO.DAG.getLoad(MemVT, DL, MemIntr->getChain(),
38456                             MemIntr->getBasePtr(), MemIntr->getMemOperand());
38457         TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
38458                                              Ld.getValue(1));
38459         return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Ld, 0,
38460                                                  TLO.DAG, DL, ExtSizeInBits));
38461       } else if ((ExtSizeInBits % MemVT.getStoreSizeInBits()) == 0) {
38462         SDLoc DL(Op);
38463         EVT BcstVT = EVT::getVectorVT(*TLO.DAG.getContext(), VT.getScalarType(),
38464                                       ExtSizeInBits / VT.getScalarSizeInBits());
38465         SDVTList Tys = TLO.DAG.getVTList(BcstVT, MVT::Other);
38466         SDValue Ops[] = {MemIntr->getOperand(0), MemIntr->getOperand(1)};
38467         SDValue Bcst =
38468             TLO.DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, DL, Tys,
38469                                         Ops, MemVT, MemIntr->getMemOperand());
38470         TLO.DAG.makeEquivalentMemoryOrdering(SDValue(MemIntr, 1),
38471                                              Bcst.getValue(1));
38472         return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Bcst, 0,
38473                                                  TLO.DAG, DL, ExtSizeInBits));
38474       }
38475       break;
38476     }
38477       // Byte shifts by immediate.
38478     case X86ISD::VSHLDQ:
38479     case X86ISD::VSRLDQ:
38480       // Shift by uniform.
38481     case X86ISD::VSHL:
38482     case X86ISD::VSRL:
38483     case X86ISD::VSRA:
38484       // Shift by immediate.
38485     case X86ISD::VSHLI:
38486     case X86ISD::VSRLI:
38487     case X86ISD::VSRAI: {
38488       SDLoc DL(Op);
38489       SDValue Ext0 =
38490           extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
38491       SDValue ExtOp =
38492           TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
38493       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
38494       SDValue Insert =
38495           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
38496       return TLO.CombineTo(Op, Insert);
38497     }
38498     case X86ISD::VPERMI: {
38499       // Simplify PERMPD/PERMQ to extract_subvector.
38500       // TODO: This should be done in shuffle combining.
38501       if (VT == MVT::v4f64 || VT == MVT::v4i64) {
38502         SmallVector<int, 4> Mask;
38503         DecodeVPERMMask(NumElts, Op.getConstantOperandVal(1), Mask);
38504         if (isUndefOrEqual(Mask[0], 2) && isUndefOrEqual(Mask[1], 3)) {
38505           SDLoc DL(Op);
38506           SDValue Ext = extractSubVector(Op.getOperand(0), 2, TLO.DAG, DL, 128);
38507           SDValue UndefVec = TLO.DAG.getUNDEF(VT);
38508           SDValue Insert = insertSubVector(UndefVec, Ext, 0, TLO.DAG, DL, 128);
38509           return TLO.CombineTo(Op, Insert);
38510         }
38511       }
38512       break;
38513     }
38514       // Zero upper elements.
38515     case X86ISD::VZEXT_MOVL:
38516       // Target unary shuffles by immediate:
38517     case X86ISD::PSHUFD:
38518     case X86ISD::PSHUFLW:
38519     case X86ISD::PSHUFHW:
38520     case X86ISD::VPERMILPI:
38521       // (Non-Lane Crossing) Target Shuffles.
38522     case X86ISD::VPERMILPV:
38523     case X86ISD::VPERMIL2:
38524     case X86ISD::PSHUFB:
38525     case X86ISD::UNPCKL:
38526     case X86ISD::UNPCKH:
38527     case X86ISD::BLENDI:
38528       // Integer ops.
38529     case X86ISD::AVG:
38530     case X86ISD::PACKSS:
38531     case X86ISD::PACKUS:
38532       // Horizontal Ops.
38533     case X86ISD::HADD:
38534     case X86ISD::HSUB:
38535     case X86ISD::FHADD:
38536     case X86ISD::FHSUB: {
38537       SDLoc DL(Op);
38538       SmallVector<SDValue, 4> Ops;
38539       for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
38540         SDValue SrcOp = Op.getOperand(i);
38541         EVT SrcVT = SrcOp.getValueType();
38542         assert((!SrcVT.isVector() || SrcVT.getSizeInBits() == SizeInBits) &&
38543                "Unsupported vector size");
38544         Ops.push_back(SrcVT.isVector() ? extractSubVector(SrcOp, 0, TLO.DAG, DL,
38545                                                           ExtSizeInBits)
38546                                        : SrcOp);
38547       }
38548       MVT ExtVT = VT.getSimpleVT();
38549       ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
38550                                ExtSizeInBits / ExtVT.getScalarSizeInBits());
38551       SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ops);
38552       SDValue UndefVec = TLO.DAG.getUNDEF(VT);
38553       SDValue Insert =
38554           insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
38555       return TLO.CombineTo(Op, Insert);
38556     }
38557     }
38558   }
38559 
38560   // Get target/faux shuffle mask.
38561   APInt OpUndef, OpZero;
38562   SmallVector<int, 64> OpMask;
38563   SmallVector<SDValue, 2> OpInputs;
38564   if (!getTargetShuffleInputs(Op, DemandedElts, OpInputs, OpMask, OpUndef,
38565                               OpZero, TLO.DAG, Depth, false))
38566     return false;
38567 
38568   // Shuffle inputs must be the same size as the result.
38569   if (OpMask.size() != (unsigned)NumElts ||
38570       llvm::any_of(OpInputs, [VT](SDValue V) {
38571         return VT.getSizeInBits() != V.getValueSizeInBits() ||
38572                !V.getValueType().isVector();
38573       }))
38574     return false;
38575 
38576   KnownZero = OpZero;
38577   KnownUndef = OpUndef;
38578 
38579   // Check if shuffle mask can be simplified to undef/zero/identity.
38580   int NumSrcs = OpInputs.size();
38581   for (int i = 0; i != NumElts; ++i)
38582     if (!DemandedElts[i])
38583       OpMask[i] = SM_SentinelUndef;
38584 
38585   if (isUndefInRange(OpMask, 0, NumElts)) {
38586     KnownUndef.setAllBits();
38587     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
38588   }
38589   if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
38590     KnownZero.setAllBits();
38591     return TLO.CombineTo(
38592         Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
38593   }
38594   for (int Src = 0; Src != NumSrcs; ++Src)
38595     if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
38596       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, OpInputs[Src]));
38597 
38598   // Attempt to simplify inputs.
38599   for (int Src = 0; Src != NumSrcs; ++Src) {
38600     // TODO: Support inputs of different types.
38601     if (OpInputs[Src].getValueType() != VT)
38602       continue;
38603 
38604     int Lo = Src * NumElts;
38605     APInt SrcElts = APInt::getNullValue(NumElts);
38606     for (int i = 0; i != NumElts; ++i)
38607       if (DemandedElts[i]) {
38608         int M = OpMask[i] - Lo;
38609         if (0 <= M && M < NumElts)
38610           SrcElts.setBit(M);
38611       }
38612 
38613     // TODO - Propagate input undef/zero elts.
38614     APInt SrcUndef, SrcZero;
38615     if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
38616                                    TLO, Depth + 1))
38617       return true;
38618   }
38619 
38620   // If we don't demand all elements, then attempt to combine to a simpler
38621   // shuffle.
38622   // We need to convert the depth to something combineX86ShufflesRecursively
38623   // can handle - so pretend its Depth == 0 again, and reduce the max depth
38624   // to match. This prevents combineX86ShuffleChain from returning a
38625   // combined shuffle that's the same as the original root, causing an
38626   // infinite loop.
38627   if (!DemandedElts.isAllOnesValue()) {
38628     assert(Depth < X86::MaxShuffleCombineDepth && "Depth out of range");
38629 
38630     SmallVector<int, 64> DemandedMask(NumElts, SM_SentinelUndef);
38631     for (int i = 0; i != NumElts; ++i)
38632       if (DemandedElts[i])
38633         DemandedMask[i] = i;
38634 
38635     SDValue NewShuffle = combineX86ShufflesRecursively(
38636         {Op}, 0, Op, DemandedMask, {}, 0, X86::MaxShuffleCombineDepth - Depth,
38637         /*HasVarMask*/ false,
38638         /*AllowVarMask*/ true, TLO.DAG, Subtarget);
38639     if (NewShuffle)
38640       return TLO.CombineTo(Op, NewShuffle);
38641   }
38642 
38643   return false;
38644 }
38645 
38646 bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
38647     SDValue Op, const APInt &OriginalDemandedBits,
38648     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
38649     unsigned Depth) const {
38650   EVT VT = Op.getValueType();
38651   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
38652   unsigned Opc = Op.getOpcode();
38653   switch(Opc) {
38654   case X86ISD::VTRUNC: {
38655     KnownBits KnownOp;
38656     SDValue Src = Op.getOperand(0);
38657     MVT SrcVT = Src.getSimpleValueType();
38658 
38659     // Simplify the input, using demanded bit information.
38660     APInt TruncMask = OriginalDemandedBits.zext(SrcVT.getScalarSizeInBits());
38661     APInt DemandedElts = OriginalDemandedElts.trunc(SrcVT.getVectorNumElements());
38662     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, KnownOp, TLO, Depth + 1))
38663       return true;
38664     break;
38665   }
38666   case X86ISD::PMULDQ:
38667   case X86ISD::PMULUDQ: {
38668     // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
38669     KnownBits KnownOp;
38670     SDValue LHS = Op.getOperand(0);
38671     SDValue RHS = Op.getOperand(1);
38672     // FIXME: Can we bound this better?
38673     APInt DemandedMask = APInt::getLowBitsSet(64, 32);
38674     if (SimplifyDemandedBits(LHS, DemandedMask, OriginalDemandedElts, KnownOp,
38675                              TLO, Depth + 1))
38676       return true;
38677     if (SimplifyDemandedBits(RHS, DemandedMask, OriginalDemandedElts, KnownOp,
38678                              TLO, Depth + 1))
38679       return true;
38680 
38681     // Aggressively peek through ops to get at the demanded low bits.
38682     SDValue DemandedLHS = SimplifyMultipleUseDemandedBits(
38683         LHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
38684     SDValue DemandedRHS = SimplifyMultipleUseDemandedBits(
38685         RHS, DemandedMask, OriginalDemandedElts, TLO.DAG, Depth + 1);
38686     if (DemandedLHS || DemandedRHS) {
38687       DemandedLHS = DemandedLHS ? DemandedLHS : LHS;
38688       DemandedRHS = DemandedRHS ? DemandedRHS : RHS;
38689       return TLO.CombineTo(
38690           Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, DemandedLHS, DemandedRHS));
38691     }
38692     break;
38693   }
38694   case X86ISD::VSHLI: {
38695     SDValue Op0 = Op.getOperand(0);
38696 
38697     unsigned ShAmt = Op.getConstantOperandVal(1);
38698     if (ShAmt >= BitWidth)
38699       break;
38700 
38701     APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
38702 
38703     // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
38704     // single shift.  We can do this if the bottom bits (which are shifted
38705     // out) are never demanded.
38706     if (Op0.getOpcode() == X86ISD::VSRLI &&
38707         OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
38708       unsigned Shift2Amt = Op0.getConstantOperandVal(1);
38709       if (Shift2Amt < BitWidth) {
38710         int Diff = ShAmt - Shift2Amt;
38711         if (Diff == 0)
38712           return TLO.CombineTo(Op, Op0.getOperand(0));
38713 
38714         unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
38715         SDValue NewShift = TLO.DAG.getNode(
38716             NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
38717             TLO.DAG.getTargetConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
38718         return TLO.CombineTo(Op, NewShift);
38719       }
38720     }
38721 
38722     // If we are only demanding sign bits then we can use the shift source directly.
38723     unsigned NumSignBits =
38724         TLO.DAG.ComputeNumSignBits(Op0, OriginalDemandedElts, Depth + 1);
38725     unsigned UpperDemandedBits =
38726         BitWidth - OriginalDemandedBits.countTrailingZeros();
38727     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
38728       return TLO.CombineTo(Op, Op0);
38729 
38730     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
38731                              TLO, Depth + 1))
38732       return true;
38733 
38734     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
38735     Known.Zero <<= ShAmt;
38736     Known.One <<= ShAmt;
38737 
38738     // Low bits known zero.
38739     Known.Zero.setLowBits(ShAmt);
38740     return false;
38741   }
38742   case X86ISD::VSRLI: {
38743     unsigned ShAmt = Op.getConstantOperandVal(1);
38744     if (ShAmt >= BitWidth)
38745       break;
38746 
38747     APInt DemandedMask = OriginalDemandedBits << ShAmt;
38748 
38749     if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
38750                              OriginalDemandedElts, Known, TLO, Depth + 1))
38751       return true;
38752 
38753     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
38754     Known.Zero.lshrInPlace(ShAmt);
38755     Known.One.lshrInPlace(ShAmt);
38756 
38757     // High bits known zero.
38758     Known.Zero.setHighBits(ShAmt);
38759     return false;
38760   }
38761   case X86ISD::VSRAI: {
38762     SDValue Op0 = Op.getOperand(0);
38763     SDValue Op1 = Op.getOperand(1);
38764 
38765     unsigned ShAmt = cast<ConstantSDNode>(Op1)->getZExtValue();
38766     if (ShAmt >= BitWidth)
38767       break;
38768 
38769     APInt DemandedMask = OriginalDemandedBits << ShAmt;
38770 
38771     // If we just want the sign bit then we don't need to shift it.
38772     if (OriginalDemandedBits.isSignMask())
38773       return TLO.CombineTo(Op, Op0);
38774 
38775     // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
38776     if (Op0.getOpcode() == X86ISD::VSHLI &&
38777         Op.getOperand(1) == Op0.getOperand(1)) {
38778       SDValue Op00 = Op0.getOperand(0);
38779       unsigned NumSignBits =
38780           TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
38781       if (ShAmt < NumSignBits)
38782         return TLO.CombineTo(Op, Op00);
38783     }
38784 
38785     // If any of the demanded bits are produced by the sign extension, we also
38786     // demand the input sign bit.
38787     if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
38788       DemandedMask.setSignBit();
38789 
38790     if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
38791                              TLO, Depth + 1))
38792       return true;
38793 
38794     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
38795     Known.Zero.lshrInPlace(ShAmt);
38796     Known.One.lshrInPlace(ShAmt);
38797 
38798     // If the input sign bit is known to be zero, or if none of the top bits
38799     // are demanded, turn this into an unsigned shift right.
38800     if (Known.Zero[BitWidth - ShAmt - 1] ||
38801         OriginalDemandedBits.countLeadingZeros() >= ShAmt)
38802       return TLO.CombineTo(
38803           Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
38804 
38805     // High bits are known one.
38806     if (Known.One[BitWidth - ShAmt - 1])
38807       Known.One.setHighBits(ShAmt);
38808     return false;
38809   }
38810   case X86ISD::PEXTRB:
38811   case X86ISD::PEXTRW: {
38812     SDValue Vec = Op.getOperand(0);
38813     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
38814     MVT VecVT = Vec.getSimpleValueType();
38815     unsigned NumVecElts = VecVT.getVectorNumElements();
38816 
38817     if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
38818       unsigned Idx = CIdx->getZExtValue();
38819       unsigned VecBitWidth = VecVT.getScalarSizeInBits();
38820 
38821       // If we demand no bits from the vector then we must have demanded
38822       // bits from the implict zext - simplify to zero.
38823       APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
38824       if (DemandedVecBits == 0)
38825         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
38826 
38827       APInt KnownUndef, KnownZero;
38828       APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
38829       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
38830                                      KnownZero, TLO, Depth + 1))
38831         return true;
38832 
38833       KnownBits KnownVec;
38834       if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
38835                                KnownVec, TLO, Depth + 1))
38836         return true;
38837 
38838       if (SDValue V = SimplifyMultipleUseDemandedBits(
38839               Vec, DemandedVecBits, DemandedVecElts, TLO.DAG, Depth + 1))
38840         return TLO.CombineTo(
38841             Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, V, Op.getOperand(1)));
38842 
38843       Known = KnownVec.zext(BitWidth);
38844       return false;
38845     }
38846     break;
38847   }
38848   case X86ISD::PINSRB:
38849   case X86ISD::PINSRW: {
38850     SDValue Vec = Op.getOperand(0);
38851     SDValue Scl = Op.getOperand(1);
38852     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
38853     MVT VecVT = Vec.getSimpleValueType();
38854 
38855     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
38856       unsigned Idx = CIdx->getZExtValue();
38857       if (!OriginalDemandedElts[Idx])
38858         return TLO.CombineTo(Op, Vec);
38859 
38860       KnownBits KnownVec;
38861       APInt DemandedVecElts(OriginalDemandedElts);
38862       DemandedVecElts.clearBit(Idx);
38863       if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
38864                                KnownVec, TLO, Depth + 1))
38865         return true;
38866 
38867       KnownBits KnownScl;
38868       unsigned NumSclBits = Scl.getScalarValueSizeInBits();
38869       APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
38870       if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
38871         return true;
38872 
38873       KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
38874       Known = KnownBits::commonBits(KnownVec, KnownScl);
38875       return false;
38876     }
38877     break;
38878   }
38879   case X86ISD::PACKSS:
38880     // PACKSS saturates to MIN/MAX integer values. So if we just want the
38881     // sign bit then we can just ask for the source operands sign bit.
38882     // TODO - add known bits handling.
38883     if (OriginalDemandedBits.isSignMask()) {
38884       APInt DemandedLHS, DemandedRHS;
38885       getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
38886 
38887       KnownBits KnownLHS, KnownRHS;
38888       APInt SignMask = APInt::getSignMask(BitWidth * 2);
38889       if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
38890                                KnownLHS, TLO, Depth + 1))
38891         return true;
38892       if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
38893                                KnownRHS, TLO, Depth + 1))
38894         return true;
38895 
38896       // Attempt to avoid multi-use ops if we don't need anything from them.
38897       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
38898           Op.getOperand(0), SignMask, DemandedLHS, TLO.DAG, Depth + 1);
38899       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
38900           Op.getOperand(1), SignMask, DemandedRHS, TLO.DAG, Depth + 1);
38901       if (DemandedOp0 || DemandedOp1) {
38902         SDValue Op0 = DemandedOp0 ? DemandedOp0 : Op.getOperand(0);
38903         SDValue Op1 = DemandedOp1 ? DemandedOp1 : Op.getOperand(1);
38904         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, Op0, Op1));
38905       }
38906     }
38907     // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
38908     break;
38909   case X86ISD::PCMPGT:
38910     // icmp sgt(0, R) == ashr(R, BitWidth-1).
38911     // iff we only need the sign bit then we can use R directly.
38912     if (OriginalDemandedBits.isSignMask() &&
38913         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
38914       return TLO.CombineTo(Op, Op.getOperand(1));
38915     break;
38916   case X86ISD::MOVMSK: {
38917     SDValue Src = Op.getOperand(0);
38918     MVT SrcVT = Src.getSimpleValueType();
38919     unsigned SrcBits = SrcVT.getScalarSizeInBits();
38920     unsigned NumElts = SrcVT.getVectorNumElements();
38921 
38922     // If we don't need the sign bits at all just return zero.
38923     if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
38924       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
38925 
38926     // Only demand the vector elements of the sign bits we need.
38927     APInt KnownUndef, KnownZero;
38928     APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
38929     if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
38930                                    TLO, Depth + 1))
38931       return true;
38932 
38933     Known.Zero = KnownZero.zextOrSelf(BitWidth);
38934     Known.Zero.setHighBits(BitWidth - NumElts);
38935 
38936     // MOVMSK only uses the MSB from each vector element.
38937     KnownBits KnownSrc;
38938     APInt DemandedSrcBits = APInt::getSignMask(SrcBits);
38939     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, KnownSrc, TLO,
38940                              Depth + 1))
38941       return true;
38942 
38943     if (KnownSrc.One[SrcBits - 1])
38944       Known.One.setLowBits(NumElts);
38945     else if (KnownSrc.Zero[SrcBits - 1])
38946       Known.Zero.setLowBits(NumElts);
38947 
38948     // Attempt to avoid multi-use os if we don't need anything from it.
38949     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
38950             Src, DemandedSrcBits, DemandedElts, TLO.DAG, Depth + 1))
38951       return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, SDLoc(Op), VT, NewSrc));
38952     return false;
38953   }
38954   case X86ISD::BEXTR:
38955   case X86ISD::BEXTRI: {
38956     SDValue Op0 = Op.getOperand(0);
38957     SDValue Op1 = Op.getOperand(1);
38958 
38959     // Only bottom 16-bits of the control bits are required.
38960     if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
38961       // NOTE: SimplifyDemandedBits won't do this for constants.
38962       uint64_t Val1 = Cst1->getZExtValue();
38963       uint64_t MaskedVal1 = Val1 & 0xFFFF;
38964       if (Opc == X86ISD::BEXTR && MaskedVal1 != Val1) {
38965         SDLoc DL(Op);
38966         return TLO.CombineTo(
38967             Op, TLO.DAG.getNode(X86ISD::BEXTR, DL, VT, Op0,
38968                                 TLO.DAG.getConstant(MaskedVal1, DL, VT)));
38969       }
38970 
38971       unsigned Shift = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 0);
38972       unsigned Length = Cst1->getAPIntValue().extractBitsAsZExtValue(8, 8);
38973 
38974       // If the length is 0, the result is 0.
38975       if (Length == 0) {
38976         Known.setAllZero();
38977         return false;
38978       }
38979 
38980       if ((Shift + Length) <= BitWidth) {
38981         APInt DemandedMask = APInt::getBitsSet(BitWidth, Shift, Shift + Length);
38982         if (SimplifyDemandedBits(Op0, DemandedMask, Known, TLO, Depth + 1))
38983           return true;
38984 
38985         Known = Known.extractBits(Length, Shift);
38986         Known = Known.zextOrTrunc(BitWidth);
38987         return false;
38988       }
38989     } else {
38990       assert(Opc == X86ISD::BEXTR && "Unexpected opcode!");
38991       KnownBits Known1;
38992       APInt DemandedMask(APInt::getLowBitsSet(BitWidth, 16));
38993       if (SimplifyDemandedBits(Op1, DemandedMask, Known1, TLO, Depth + 1))
38994         return true;
38995 
38996       // If the length is 0, replace with 0.
38997       KnownBits LengthBits = Known1.extractBits(8, 8);
38998       if (LengthBits.isZero())
38999         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
39000     }
39001 
39002     break;
39003   }
39004   case X86ISD::PDEP: {
39005     SDValue Op0 = Op.getOperand(0);
39006     SDValue Op1 = Op.getOperand(1);
39007 
39008     unsigned DemandedBitsLZ = OriginalDemandedBits.countLeadingZeros();
39009     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
39010 
39011     // If the demanded bits has leading zeroes, we don't demand those from the
39012     // mask.
39013     if (SimplifyDemandedBits(Op1, LoMask, Known, TLO, Depth + 1))
39014       return true;
39015 
39016     // The number of possible 1s in the mask determines the number of LSBs of
39017     // operand 0 used. Undemanded bits from the mask don't matter so filter
39018     // them before counting.
39019     KnownBits Known2;
39020     uint64_t Count = (~Known.Zero & LoMask).countPopulation();
39021     APInt DemandedMask(APInt::getLowBitsSet(BitWidth, Count));
39022     if (SimplifyDemandedBits(Op0, DemandedMask, Known2, TLO, Depth + 1))
39023       return true;
39024 
39025     // Zeroes are retained from the mask, but not ones.
39026     Known.One.clearAllBits();
39027     // The result will have at least as many trailing zeros as the non-mask
39028     // operand since bits can only map to the same or higher bit position.
39029     Known.Zero.setLowBits(Known2.countMinTrailingZeros());
39030     return false;
39031   }
39032   }
39033 
39034   return TargetLowering::SimplifyDemandedBitsForTargetNode(
39035       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
39036 }
39037 
39038 SDValue X86TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
39039     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
39040     SelectionDAG &DAG, unsigned Depth) const {
39041   int NumElts = DemandedElts.getBitWidth();
39042   unsigned Opc = Op.getOpcode();
39043   EVT VT = Op.getValueType();
39044 
39045   switch (Opc) {
39046   case X86ISD::PINSRB:
39047   case X86ISD::PINSRW: {
39048     // If we don't demand the inserted element, return the base vector.
39049     SDValue Vec = Op.getOperand(0);
39050     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
39051     MVT VecVT = Vec.getSimpleValueType();
39052     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
39053         !DemandedElts[CIdx->getZExtValue()])
39054       return Vec;
39055     break;
39056   }
39057   case X86ISD::VSHLI: {
39058     // If we are only demanding sign bits then we can use the shift source
39059     // directly.
39060     SDValue Op0 = Op.getOperand(0);
39061     unsigned ShAmt = Op.getConstantOperandVal(1);
39062     unsigned BitWidth = DemandedBits.getBitWidth();
39063     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
39064     unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
39065     if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= UpperDemandedBits)
39066       return Op0;
39067     break;
39068   }
39069   case X86ISD::VSRAI:
39070     // iff we only need the sign bit then we can use the source directly.
39071     // TODO: generalize where we only demand extended signbits.
39072     if (DemandedBits.isSignMask())
39073       return Op.getOperand(0);
39074     break;
39075   case X86ISD::PCMPGT:
39076     // icmp sgt(0, R) == ashr(R, BitWidth-1).
39077     // iff we only need the sign bit then we can use R directly.
39078     if (DemandedBits.isSignMask() &&
39079         ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
39080       return Op.getOperand(1);
39081     break;
39082   }
39083 
39084   APInt ShuffleUndef, ShuffleZero;
39085   SmallVector<int, 16> ShuffleMask;
39086   SmallVector<SDValue, 2> ShuffleOps;
39087   if (getTargetShuffleInputs(Op, DemandedElts, ShuffleOps, ShuffleMask,
39088                              ShuffleUndef, ShuffleZero, DAG, Depth, false)) {
39089     // If all the demanded elts are from one operand and are inline,
39090     // then we can use the operand directly.
39091     int NumOps = ShuffleOps.size();
39092     if (ShuffleMask.size() == (unsigned)NumElts &&
39093         llvm::all_of(ShuffleOps, [VT](SDValue V) {
39094           return VT.getSizeInBits() == V.getValueSizeInBits();
39095         })) {
39096 
39097       if (DemandedElts.isSubsetOf(ShuffleUndef))
39098         return DAG.getUNDEF(VT);
39099       if (DemandedElts.isSubsetOf(ShuffleUndef | ShuffleZero))
39100         return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, SDLoc(Op));
39101 
39102       // Bitmask that indicates which ops have only been accessed 'inline'.
39103       APInt IdentityOp = APInt::getAllOnesValue(NumOps);
39104       for (int i = 0; i != NumElts; ++i) {
39105         int M = ShuffleMask[i];
39106         if (!DemandedElts[i] || ShuffleUndef[i])
39107           continue;
39108         int OpIdx = M / NumElts;
39109         int EltIdx = M % NumElts;
39110         if (M < 0 || EltIdx != i) {
39111           IdentityOp.clearAllBits();
39112           break;
39113         }
39114         IdentityOp &= APInt::getOneBitSet(NumOps, OpIdx);
39115         if (IdentityOp == 0)
39116           break;
39117       }
39118       assert((IdentityOp == 0 || IdentityOp.countPopulation() == 1) &&
39119              "Multiple identity shuffles detected");
39120 
39121       if (IdentityOp != 0)
39122         return DAG.getBitcast(VT, ShuffleOps[IdentityOp.countTrailingZeros()]);
39123     }
39124   }
39125 
39126   return TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
39127       Op, DemandedBits, DemandedElts, DAG, Depth);
39128 }
39129 
39130 // Helper to peek through bitops/setcc to determine size of source vector.
39131 // Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
39132 static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size) {
39133   switch (Src.getOpcode()) {
39134   case ISD::SETCC:
39135     return Src.getOperand(0).getValueSizeInBits() == Size;
39136   case ISD::AND:
39137   case ISD::XOR:
39138   case ISD::OR:
39139     return checkBitcastSrcVectorSize(Src.getOperand(0), Size) &&
39140            checkBitcastSrcVectorSize(Src.getOperand(1), Size);
39141   }
39142   return false;
39143 }
39144 
39145 // Helper to flip between AND/OR/XOR opcodes and their X86ISD FP equivalents.
39146 static unsigned getAltBitOpcode(unsigned Opcode) {
39147   switch(Opcode) {
39148   case ISD::AND: return X86ISD::FAND;
39149   case ISD::OR: return X86ISD::FOR;
39150   case ISD::XOR: return X86ISD::FXOR;
39151   case X86ISD::ANDNP: return X86ISD::FANDN;
39152   }
39153   llvm_unreachable("Unknown bitwise opcode");
39154 }
39155 
39156 // Helper to adjust v4i32 MOVMSK expansion to work with SSE1-only targets.
39157 static SDValue adjustBitcastSrcVectorSSE1(SelectionDAG &DAG, SDValue Src,
39158                                           const SDLoc &DL) {
39159   EVT SrcVT = Src.getValueType();
39160   if (SrcVT != MVT::v4i1)
39161     return SDValue();
39162 
39163   switch (Src.getOpcode()) {
39164   case ISD::SETCC:
39165     if (Src.getOperand(0).getValueType() == MVT::v4i32 &&
39166         ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode()) &&
39167         cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT) {
39168       SDValue Op0 = Src.getOperand(0);
39169       if (ISD::isNormalLoad(Op0.getNode()))
39170         return DAG.getBitcast(MVT::v4f32, Op0);
39171       if (Op0.getOpcode() == ISD::BITCAST &&
39172           Op0.getOperand(0).getValueType() == MVT::v4f32)
39173         return Op0.getOperand(0);
39174     }
39175     break;
39176   case ISD::AND:
39177   case ISD::XOR:
39178   case ISD::OR: {
39179     SDValue Op0 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(0), DL);
39180     SDValue Op1 = adjustBitcastSrcVectorSSE1(DAG, Src.getOperand(1), DL);
39181     if (Op0 && Op1)
39182       return DAG.getNode(getAltBitOpcode(Src.getOpcode()), DL, MVT::v4f32, Op0,
39183                          Op1);
39184     break;
39185   }
39186   }
39187   return SDValue();
39188 }
39189 
39190 // Helper to push sign extension of vXi1 SETCC result through bitops.
39191 static SDValue signExtendBitcastSrcVector(SelectionDAG &DAG, EVT SExtVT,
39192                                           SDValue Src, const SDLoc &DL) {
39193   switch (Src.getOpcode()) {
39194   case ISD::SETCC:
39195     return DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
39196   case ISD::AND:
39197   case ISD::XOR:
39198   case ISD::OR:
39199     return DAG.getNode(
39200         Src.getOpcode(), DL, SExtVT,
39201         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(0), DL),
39202         signExtendBitcastSrcVector(DAG, SExtVT, Src.getOperand(1), DL));
39203   }
39204   llvm_unreachable("Unexpected node type for vXi1 sign extension");
39205 }
39206 
39207 // Try to match patterns such as
39208 // (i16 bitcast (v16i1 x))
39209 // ->
39210 // (i16 movmsk (16i8 sext (v16i1 x)))
39211 // before the illegal vector is scalarized on subtargets that don't have legal
39212 // vxi1 types.
39213 static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
39214                                   const SDLoc &DL,
39215                                   const X86Subtarget &Subtarget) {
39216   EVT SrcVT = Src.getValueType();
39217   if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
39218     return SDValue();
39219 
39220   // Recognize the IR pattern for the movmsk intrinsic under SSE1 before type
39221   // legalization destroys the v4i32 type.
39222   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2()) {
39223     if (SDValue V = adjustBitcastSrcVectorSSE1(DAG, Src, DL)) {
39224       V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32,
39225                       DAG.getBitcast(MVT::v4f32, V));
39226       return DAG.getZExtOrTrunc(V, DL, VT);
39227     }
39228   }
39229 
39230   // If the input is a truncate from v16i8 or v32i8 go ahead and use a
39231   // movmskb even with avx512. This will be better than truncating to vXi1 and
39232   // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
39233   // vpcmpeqb/vpcmpgtb.
39234   bool PreferMovMsk = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
39235                       (Src.getOperand(0).getValueType() == MVT::v16i8 ||
39236                        Src.getOperand(0).getValueType() == MVT::v32i8 ||
39237                        Src.getOperand(0).getValueType() == MVT::v64i8);
39238 
39239   // Prefer movmsk for AVX512 for (bitcast (setlt X, 0)) which can be handled
39240   // directly with vpmovmskb/vmovmskps/vmovmskpd.
39241   if (Src.getOpcode() == ISD::SETCC && Src.hasOneUse() &&
39242       cast<CondCodeSDNode>(Src.getOperand(2))->get() == ISD::SETLT &&
39243       ISD::isBuildVectorAllZeros(Src.getOperand(1).getNode())) {
39244     EVT CmpVT = Src.getOperand(0).getValueType();
39245     EVT EltVT = CmpVT.getVectorElementType();
39246     if (CmpVT.getSizeInBits() <= 256 &&
39247         (EltVT == MVT::i8 || EltVT == MVT::i32 || EltVT == MVT::i64))
39248       PreferMovMsk = true;
39249   }
39250 
39251   // With AVX512 vxi1 types are legal and we prefer using k-regs.
39252   // MOVMSK is supported in SSE2 or later.
39253   if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !PreferMovMsk))
39254     return SDValue();
39255 
39256   // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
39257   // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
39258   // v8i16 and v16i16.
39259   // For these two cases, we can shuffle the upper element bytes to a
39260   // consecutive sequence at the start of the vector and treat the results as
39261   // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
39262   // for v16i16 this is not the case, because the shuffle is expensive, so we
39263   // avoid sign-extending to this type entirely.
39264   // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
39265   // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
39266   MVT SExtVT;
39267   bool PropagateSExt = false;
39268   switch (SrcVT.getSimpleVT().SimpleTy) {
39269   default:
39270     return SDValue();
39271   case MVT::v2i1:
39272     SExtVT = MVT::v2i64;
39273     break;
39274   case MVT::v4i1:
39275     SExtVT = MVT::v4i32;
39276     // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
39277     // sign-extend to a 256-bit operation to avoid truncation.
39278     if (Subtarget.hasAVX() && checkBitcastSrcVectorSize(Src, 256)) {
39279       SExtVT = MVT::v4i64;
39280       PropagateSExt = true;
39281     }
39282     break;
39283   case MVT::v8i1:
39284     SExtVT = MVT::v8i16;
39285     // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
39286     // sign-extend to a 256-bit operation to match the compare.
39287     // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
39288     // 256-bit because the shuffle is cheaper than sign extending the result of
39289     // the compare.
39290     if (Subtarget.hasAVX() && (checkBitcastSrcVectorSize(Src, 256) ||
39291                                checkBitcastSrcVectorSize(Src, 512))) {
39292       SExtVT = MVT::v8i32;
39293       PropagateSExt = true;
39294     }
39295     break;
39296   case MVT::v16i1:
39297     SExtVT = MVT::v16i8;
39298     // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
39299     // it is not profitable to sign-extend to 256-bit because this will
39300     // require an extra cross-lane shuffle which is more expensive than
39301     // truncating the result of the compare to 128-bits.
39302     break;
39303   case MVT::v32i1:
39304     SExtVT = MVT::v32i8;
39305     break;
39306   case MVT::v64i1:
39307     // If we have AVX512F, but not AVX512BW and the input is truncated from
39308     // v64i8 checked earlier. Then split the input and make two pmovmskbs.
39309     if (Subtarget.hasAVX512()) {
39310       if (Subtarget.hasBWI())
39311         return SDValue();
39312       SExtVT = MVT::v64i8;
39313       break;
39314     }
39315     // Split if this is a <64 x i8> comparison result.
39316     if (checkBitcastSrcVectorSize(Src, 512)) {
39317       SExtVT = MVT::v64i8;
39318       break;
39319     }
39320     return SDValue();
39321   };
39322 
39323   SDValue V = PropagateSExt ? signExtendBitcastSrcVector(DAG, SExtVT, Src, DL)
39324                             : DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
39325 
39326   if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8 || SExtVT == MVT::v64i8) {
39327     V = getPMOVMSKB(DL, V, DAG, Subtarget);
39328   } else {
39329     if (SExtVT == MVT::v8i16)
39330       V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
39331                       DAG.getUNDEF(MVT::v8i16));
39332     V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
39333   }
39334 
39335   EVT IntVT =
39336       EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
39337   V = DAG.getZExtOrTrunc(V, DL, IntVT);
39338   return DAG.getBitcast(VT, V);
39339 }
39340 
39341 // Convert a vXi1 constant build vector to the same width scalar integer.
39342 static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
39343   EVT SrcVT = Op.getValueType();
39344   assert(SrcVT.getVectorElementType() == MVT::i1 &&
39345          "Expected a vXi1 vector");
39346   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
39347          "Expected a constant build vector");
39348 
39349   APInt Imm(SrcVT.getVectorNumElements(), 0);
39350   for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
39351     SDValue In = Op.getOperand(Idx);
39352     if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
39353       Imm.setBit(Idx);
39354   }
39355   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
39356   return DAG.getConstant(Imm, SDLoc(Op), IntVT);
39357 }
39358 
39359 static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
39360                                            TargetLowering::DAGCombinerInfo &DCI,
39361                                            const X86Subtarget &Subtarget) {
39362   assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast");
39363 
39364   if (!DCI.isBeforeLegalizeOps())
39365     return SDValue();
39366 
39367   // Only do this if we have k-registers.
39368   if (!Subtarget.hasAVX512())
39369     return SDValue();
39370 
39371   EVT DstVT = N->getValueType(0);
39372   SDValue Op = N->getOperand(0);
39373   EVT SrcVT = Op.getValueType();
39374 
39375   if (!Op.hasOneUse())
39376     return SDValue();
39377 
39378   // Look for logic ops.
39379   if (Op.getOpcode() != ISD::AND &&
39380       Op.getOpcode() != ISD::OR &&
39381       Op.getOpcode() != ISD::XOR)
39382     return SDValue();
39383 
39384   // Make sure we have a bitcast between mask registers and a scalar type.
39385   if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
39386         DstVT.isScalarInteger()) &&
39387       !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
39388         SrcVT.isScalarInteger()))
39389     return SDValue();
39390 
39391   SDValue LHS = Op.getOperand(0);
39392   SDValue RHS = Op.getOperand(1);
39393 
39394   if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
39395       LHS.getOperand(0).getValueType() == DstVT)
39396     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
39397                        DAG.getBitcast(DstVT, RHS));
39398 
39399   if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
39400       RHS.getOperand(0).getValueType() == DstVT)
39401     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
39402                        DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
39403 
39404   // If the RHS is a vXi1 build vector, this is a good reason to flip too.
39405   // Most of these have to move a constant from the scalar domain anyway.
39406   if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
39407     RHS = combinevXi1ConstantToInteger(RHS, DAG);
39408     return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
39409                        DAG.getBitcast(DstVT, LHS), RHS);
39410   }
39411 
39412   return SDValue();
39413 }
39414 
39415 static SDValue createMMXBuildVector(BuildVectorSDNode *BV, SelectionDAG &DAG,
39416                                     const X86Subtarget &Subtarget) {
39417   SDLoc DL(BV);
39418   unsigned NumElts = BV->getNumOperands();
39419   SDValue Splat = BV->getSplatValue();
39420 
39421   // Build MMX element from integer GPR or SSE float values.
39422   auto CreateMMXElement = [&](SDValue V) {
39423     if (V.isUndef())
39424       return DAG.getUNDEF(MVT::x86mmx);
39425     if (V.getValueType().isFloatingPoint()) {
39426       if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
39427         V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
39428         V = DAG.getBitcast(MVT::v2i64, V);
39429         return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
39430       }
39431       V = DAG.getBitcast(MVT::i32, V);
39432     } else {
39433       V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
39434     }
39435     return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
39436   };
39437 
39438   // Convert build vector ops to MMX data in the bottom elements.
39439   SmallVector<SDValue, 8> Ops;
39440 
39441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39442 
39443   // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
39444   if (Splat) {
39445     if (Splat.isUndef())
39446       return DAG.getUNDEF(MVT::x86mmx);
39447 
39448     Splat = CreateMMXElement(Splat);
39449 
39450     if (Subtarget.hasSSE1()) {
39451       // Unpack v8i8 to splat i8 elements to lowest 16-bits.
39452       if (NumElts == 8)
39453         Splat = DAG.getNode(
39454             ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
39455             DAG.getTargetConstant(Intrinsic::x86_mmx_punpcklbw, DL,
39456                                   TLI.getPointerTy(DAG.getDataLayout())),
39457             Splat, Splat);
39458 
39459       // Use PSHUFW to repeat 16-bit elements.
39460       unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
39461       return DAG.getNode(
39462           ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
39463           DAG.getTargetConstant(Intrinsic::x86_sse_pshuf_w, DL,
39464                                 TLI.getPointerTy(DAG.getDataLayout())),
39465           Splat, DAG.getTargetConstant(ShufMask, DL, MVT::i8));
39466     }
39467     Ops.append(NumElts, Splat);
39468   } else {
39469     for (unsigned i = 0; i != NumElts; ++i)
39470       Ops.push_back(CreateMMXElement(BV->getOperand(i)));
39471   }
39472 
39473   // Use tree of PUNPCKLs to build up general MMX vector.
39474   while (Ops.size() > 1) {
39475     unsigned NumOps = Ops.size();
39476     unsigned IntrinOp =
39477         (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
39478                      : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
39479                                     : Intrinsic::x86_mmx_punpcklbw));
39480     SDValue Intrin = DAG.getTargetConstant(
39481         IntrinOp, DL, TLI.getPointerTy(DAG.getDataLayout()));
39482     for (unsigned i = 0; i != NumOps; i += 2)
39483       Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
39484                                Ops[i], Ops[i + 1]);
39485     Ops.resize(NumOps / 2);
39486   }
39487 
39488   return Ops[0];
39489 }
39490 
39491 // Recursive function that attempts to find if a bool vector node was originally
39492 // a vector/float/double that got truncated/extended/bitcast to/from a scalar
39493 // integer. If so, replace the scalar ops with bool vector equivalents back down
39494 // the chain.
39495 static SDValue combineBitcastToBoolVector(EVT VT, SDValue V, const SDLoc &DL,
39496                                           SelectionDAG &DAG,
39497                                           const X86Subtarget &Subtarget) {
39498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39499   unsigned Opc = V.getOpcode();
39500   switch (Opc) {
39501   case ISD::BITCAST: {
39502     // Bitcast from a vector/float/double, we can cheaply bitcast to VT.
39503     SDValue Src = V.getOperand(0);
39504     EVT SrcVT = Src.getValueType();
39505     if (SrcVT.isVector() || SrcVT.isFloatingPoint())
39506       return DAG.getBitcast(VT, Src);
39507     break;
39508   }
39509   case ISD::TRUNCATE: {
39510     // If we find a suitable source, a truncated scalar becomes a subvector.
39511     SDValue Src = V.getOperand(0);
39512     EVT NewSrcVT =
39513         EVT::getVectorVT(*DAG.getContext(), MVT::i1, Src.getValueSizeInBits());
39514     if (TLI.isTypeLegal(NewSrcVT))
39515       if (SDValue N0 =
39516               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
39517         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, N0,
39518                            DAG.getIntPtrConstant(0, DL));
39519     break;
39520   }
39521   case ISD::ANY_EXTEND:
39522   case ISD::ZERO_EXTEND: {
39523     // If we find a suitable source, an extended scalar becomes a subvector.
39524     SDValue Src = V.getOperand(0);
39525     EVT NewSrcVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
39526                                     Src.getScalarValueSizeInBits());
39527     if (TLI.isTypeLegal(NewSrcVT))
39528       if (SDValue N0 =
39529               combineBitcastToBoolVector(NewSrcVT, Src, DL, DAG, Subtarget))
39530         return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
39531                            Opc == ISD::ANY_EXTEND ? DAG.getUNDEF(VT)
39532                                                   : DAG.getConstant(0, DL, VT),
39533                            N0, DAG.getIntPtrConstant(0, DL));
39534     break;
39535   }
39536   case ISD::OR: {
39537     // If we find suitable sources, we can just move an OR to the vector domain.
39538     SDValue Src0 = V.getOperand(0);
39539     SDValue Src1 = V.getOperand(1);
39540     if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
39541       if (SDValue N1 = combineBitcastToBoolVector(VT, Src1, DL, DAG, Subtarget))
39542         return DAG.getNode(Opc, DL, VT, N0, N1);
39543     break;
39544   }
39545   case ISD::SHL: {
39546     // If we find a suitable source, a SHL becomes a KSHIFTL.
39547     SDValue Src0 = V.getOperand(0);
39548     if ((VT == MVT::v8i1 && !Subtarget.hasDQI()) ||
39549         ((VT == MVT::v32i1 || VT == MVT::v64i1) && !Subtarget.hasBWI()))
39550       break;
39551 
39552     if (auto *Amt = dyn_cast<ConstantSDNode>(V.getOperand(1)))
39553       if (SDValue N0 = combineBitcastToBoolVector(VT, Src0, DL, DAG, Subtarget))
39554         return DAG.getNode(
39555             X86ISD::KSHIFTL, DL, VT, N0,
39556             DAG.getTargetConstant(Amt->getZExtValue(), DL, MVT::i8));
39557     break;
39558   }
39559   }
39560   return SDValue();
39561 }
39562 
39563 static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
39564                               TargetLowering::DAGCombinerInfo &DCI,
39565                               const X86Subtarget &Subtarget) {
39566   SDValue N0 = N->getOperand(0);
39567   EVT VT = N->getValueType(0);
39568   EVT SrcVT = N0.getValueType();
39569 
39570   // Try to match patterns such as
39571   // (i16 bitcast (v16i1 x))
39572   // ->
39573   // (i16 movmsk (16i8 sext (v16i1 x)))
39574   // before the setcc result is scalarized on subtargets that don't have legal
39575   // vxi1 types.
39576   if (DCI.isBeforeLegalize()) {
39577     SDLoc dl(N);
39578     if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
39579       return V;
39580 
39581     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
39582     // type, widen both sides to avoid a trip through memory.
39583     if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
39584         Subtarget.hasAVX512()) {
39585       N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
39586       N0 = DAG.getBitcast(MVT::v8i1, N0);
39587       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
39588                          DAG.getIntPtrConstant(0, dl));
39589     }
39590 
39591     // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
39592     // type, widen both sides to avoid a trip through memory.
39593     if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
39594         Subtarget.hasAVX512()) {
39595       // Use zeros for the widening if we already have some zeroes. This can
39596       // allow SimplifyDemandedBits to remove scalar ANDs that may be down
39597       // stream of this.
39598       // FIXME: It might make sense to detect a concat_vectors with a mix of
39599       // zeroes and undef and turn it into insert_subvector for i1 vectors as
39600       // a separate combine. What we can't do is canonicalize the operands of
39601       // such a concat or we'll get into a loop with SimplifyDemandedBits.
39602       if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
39603         SDValue LastOp = N0.getOperand(N0.getNumOperands() - 1);
39604         if (ISD::isBuildVectorAllZeros(LastOp.getNode())) {
39605           SrcVT = LastOp.getValueType();
39606           unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
39607           SmallVector<SDValue, 4> Ops(N0->op_begin(), N0->op_end());
39608           Ops.resize(NumConcats, DAG.getConstant(0, dl, SrcVT));
39609           N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
39610           N0 = DAG.getBitcast(MVT::i8, N0);
39611           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
39612         }
39613       }
39614 
39615       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
39616       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
39617       Ops[0] = N0;
39618       N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
39619       N0 = DAG.getBitcast(MVT::i8, N0);
39620       return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
39621     }
39622   } else {
39623     // If we're bitcasting from iX to vXi1, see if the integer originally
39624     // began as a vXi1 and whether we can remove the bitcast entirely.
39625     if (VT.isVector() && VT.getScalarType() == MVT::i1 &&
39626         SrcVT.isScalarInteger() &&
39627         DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
39628       if (SDValue V =
39629               combineBitcastToBoolVector(VT, N0, SDLoc(N), DAG, Subtarget))
39630         return V;
39631     }
39632   }
39633 
39634   // Look for (i8 (bitcast (v8i1 (extract_subvector (v16i1 X), 0)))) and
39635   // replace with (i8 (trunc (i16 (bitcast (v16i1 X))))). This can occur
39636   // due to insert_subvector legalization on KNL. By promoting the copy to i16
39637   // we can help with known bits propagation from the vXi1 domain to the
39638   // scalar domain.
39639   if (VT == MVT::i8 && SrcVT == MVT::v8i1 && Subtarget.hasAVX512() &&
39640       !Subtarget.hasDQI() && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
39641       N0.getOperand(0).getValueType() == MVT::v16i1 &&
39642       isNullConstant(N0.getOperand(1)))
39643     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT,
39644                        DAG.getBitcast(MVT::i16, N0.getOperand(0)));
39645 
39646   // Canonicalize (bitcast (vbroadcast_load)) so that the output of the bitcast
39647   // and the vbroadcast_load are both integer or both fp. In some cases this
39648   // will remove the bitcast entirely.
39649   if (N0.getOpcode() == X86ISD::VBROADCAST_LOAD && N0.hasOneUse() &&
39650        VT.isFloatingPoint() != SrcVT.isFloatingPoint() && VT.isVector()) {
39651     auto *BCast = cast<MemIntrinsicSDNode>(N0);
39652     unsigned SrcVTSize = SrcVT.getScalarSizeInBits();
39653     unsigned MemSize = BCast->getMemoryVT().getScalarSizeInBits();
39654     // Don't swap i8/i16 since don't have fp types that size.
39655     if (MemSize >= 32) {
39656       MVT MemVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(MemSize)
39657                                        : MVT::getIntegerVT(MemSize);
39658       MVT LoadVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(SrcVTSize)
39659                                         : MVT::getIntegerVT(SrcVTSize);
39660       LoadVT = MVT::getVectorVT(LoadVT, SrcVT.getVectorNumElements());
39661 
39662       SDVTList Tys = DAG.getVTList(LoadVT, MVT::Other);
39663       SDValue Ops[] = { BCast->getChain(), BCast->getBasePtr() };
39664       SDValue ResNode =
39665           DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, SDLoc(N), Tys, Ops,
39666                                   MemVT, BCast->getMemOperand());
39667       DAG.ReplaceAllUsesOfValueWith(SDValue(BCast, 1), ResNode.getValue(1));
39668       return DAG.getBitcast(VT, ResNode);
39669     }
39670   }
39671 
39672   // Since MMX types are special and don't usually play with other vector types,
39673   // it's better to handle them early to be sure we emit efficient code by
39674   // avoiding store-load conversions.
39675   if (VT == MVT::x86mmx) {
39676     // Detect MMX constant vectors.
39677     APInt UndefElts;
39678     SmallVector<APInt, 1> EltBits;
39679     if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
39680       SDLoc DL(N0);
39681       // Handle zero-extension of i32 with MOVD.
39682       if (EltBits[0].countLeadingZeros() >= 32)
39683         return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
39684                            DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
39685       // Else, bitcast to a double.
39686       // TODO - investigate supporting sext 32-bit immediates on x86_64.
39687       APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
39688       return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
39689     }
39690 
39691     // Detect bitcasts to x86mmx low word.
39692     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
39693         (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
39694         N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
39695       bool LowUndef = true, AllUndefOrZero = true;
39696       for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
39697         SDValue Op = N0.getOperand(i);
39698         LowUndef &= Op.isUndef() || (i >= e/2);
39699         AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
39700       }
39701       if (AllUndefOrZero) {
39702         SDValue N00 = N0.getOperand(0);
39703         SDLoc dl(N00);
39704         N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
39705                        : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
39706         return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
39707       }
39708     }
39709 
39710     // Detect bitcasts of 64-bit build vectors and convert to a
39711     // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
39712     // lowest element.
39713     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
39714         (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
39715          SrcVT == MVT::v8i8))
39716       return createMMXBuildVector(cast<BuildVectorSDNode>(N0), DAG, Subtarget);
39717 
39718     // Detect bitcasts between element or subvector extraction to x86mmx.
39719     if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
39720          N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
39721         isNullConstant(N0.getOperand(1))) {
39722       SDValue N00 = N0.getOperand(0);
39723       if (N00.getValueType().is128BitVector())
39724         return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
39725                            DAG.getBitcast(MVT::v2i64, N00));
39726     }
39727 
39728     // Detect bitcasts from FP_TO_SINT to x86mmx.
39729     if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
39730       SDLoc DL(N0);
39731       SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
39732                                 DAG.getUNDEF(MVT::v2i32));
39733       return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
39734                          DAG.getBitcast(MVT::v2i64, Res));
39735     }
39736   }
39737 
39738   // Try to remove a bitcast of constant vXi1 vector. We have to legalize
39739   // most of these to scalar anyway.
39740   if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
39741       SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
39742       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
39743     return combinevXi1ConstantToInteger(N0, DAG);
39744   }
39745 
39746   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
39747       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
39748       isa<ConstantSDNode>(N0)) {
39749     auto *C = cast<ConstantSDNode>(N0);
39750     if (C->isAllOnesValue())
39751       return DAG.getConstant(1, SDLoc(N0), VT);
39752     if (C->isNullValue())
39753       return DAG.getConstant(0, SDLoc(N0), VT);
39754   }
39755 
39756   // Look for MOVMSK that is maybe truncated and then bitcasted to vXi1.
39757   // Turn it into a sign bit compare that produces a k-register. This avoids
39758   // a trip through a GPR.
39759   if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
39760       VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
39761       isPowerOf2_32(VT.getVectorNumElements())) {
39762     unsigned NumElts = VT.getVectorNumElements();
39763     SDValue Src = N0;
39764 
39765     // Peek through truncate.
39766     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
39767       Src = N0.getOperand(0);
39768 
39769     if (Src.getOpcode() == X86ISD::MOVMSK && Src.hasOneUse()) {
39770       SDValue MovmskIn = Src.getOperand(0);
39771       MVT MovmskVT = MovmskIn.getSimpleValueType();
39772       unsigned MovMskElts = MovmskVT.getVectorNumElements();
39773 
39774       // We allow extra bits of the movmsk to be used since they are known zero.
39775       // We can't convert a VPMOVMSKB without avx512bw.
39776       if (MovMskElts <= NumElts &&
39777           (Subtarget.hasBWI() || MovmskVT.getVectorElementType() != MVT::i8)) {
39778         EVT IntVT = EVT(MovmskVT).changeVectorElementTypeToInteger();
39779         MovmskIn = DAG.getBitcast(IntVT, MovmskIn);
39780         SDLoc dl(N);
39781         MVT CmpVT = MVT::getVectorVT(MVT::i1, MovMskElts);
39782         SDValue Cmp = DAG.getSetCC(dl, CmpVT, MovmskIn,
39783                                    DAG.getConstant(0, dl, IntVT), ISD::SETLT);
39784         if (EVT(CmpVT) == VT)
39785           return Cmp;
39786 
39787         // Pad with zeroes up to original VT to replace the zeroes that were
39788         // being used from the MOVMSK.
39789         unsigned NumConcats = NumElts / MovMskElts;
39790         SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, CmpVT));
39791         Ops[0] = Cmp;
39792         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Ops);
39793       }
39794     }
39795   }
39796 
39797   // Try to remove bitcasts from input and output of mask arithmetic to
39798   // remove GPR<->K-register crossings.
39799   if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
39800     return V;
39801 
39802   // Convert a bitcasted integer logic operation that has one bitcasted
39803   // floating-point operand into a floating-point logic operation. This may
39804   // create a load of a constant, but that is cheaper than materializing the
39805   // constant in an integer register and transferring it to an SSE register or
39806   // transferring the SSE operand to integer register and back.
39807   unsigned FPOpcode;
39808   switch (N0.getOpcode()) {
39809     case ISD::AND: FPOpcode = X86ISD::FAND; break;
39810     case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
39811     case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
39812     default: return SDValue();
39813   }
39814 
39815   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
39816         (Subtarget.hasSSE2() && VT == MVT::f64)))
39817     return SDValue();
39818 
39819   SDValue LogicOp0 = N0.getOperand(0);
39820   SDValue LogicOp1 = N0.getOperand(1);
39821   SDLoc DL0(N0);
39822 
39823   // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
39824   if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
39825       LogicOp0.hasOneUse() && LogicOp0.getOperand(0).getValueType() == VT &&
39826       !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
39827     SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
39828     return DAG.getNode(FPOpcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
39829   }
39830   // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
39831   if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
39832       LogicOp1.hasOneUse() && LogicOp1.getOperand(0).getValueType() == VT &&
39833       !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
39834     SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
39835     return DAG.getNode(FPOpcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
39836   }
39837 
39838   return SDValue();
39839 }
39840 
39841 // Given a ABS node, detect the following pattern:
39842 // (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
39843 // This is useful as it is the input into a SAD pattern.
39844 static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
39845   SDValue AbsOp1 = Abs->getOperand(0);
39846   if (AbsOp1.getOpcode() != ISD::SUB)
39847     return false;
39848 
39849   Op0 = AbsOp1.getOperand(0);
39850   Op1 = AbsOp1.getOperand(1);
39851 
39852   // Check if the operands of the sub are zero-extended from vectors of i8.
39853   if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
39854       Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
39855       Op1.getOpcode() != ISD::ZERO_EXTEND ||
39856       Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
39857     return false;
39858 
39859   return true;
39860 }
39861 
39862 // Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
39863 // to these zexts.
39864 static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
39865                             const SDValue &Zext1, const SDLoc &DL,
39866                             const X86Subtarget &Subtarget) {
39867   // Find the appropriate width for the PSADBW.
39868   EVT InVT = Zext0.getOperand(0).getValueType();
39869   unsigned RegSize = std::max(128u, (unsigned)InVT.getSizeInBits());
39870 
39871   // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
39872   // fill in the missing vector elements with 0.
39873   unsigned NumConcat = RegSize / InVT.getSizeInBits();
39874   SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
39875   Ops[0] = Zext0.getOperand(0);
39876   MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
39877   SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
39878   Ops[0] = Zext1.getOperand(0);
39879   SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
39880 
39881   // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
39882   auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
39883                           ArrayRef<SDValue> Ops) {
39884     MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
39885     return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
39886   };
39887   MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
39888   return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
39889                           PSADBWBuilder);
39890 }
39891 
39892 // Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
39893 // PHMINPOSUW.
39894 static SDValue combineMinMaxReduction(SDNode *Extract, SelectionDAG &DAG,
39895                                       const X86Subtarget &Subtarget) {
39896   // Bail without SSE41.
39897   if (!Subtarget.hasSSE41())
39898     return SDValue();
39899 
39900   EVT ExtractVT = Extract->getValueType(0);
39901   if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
39902     return SDValue();
39903 
39904   // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
39905   ISD::NodeType BinOp;
39906   SDValue Src = DAG.matchBinOpReduction(
39907       Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN}, true);
39908   if (!Src)
39909     return SDValue();
39910 
39911   EVT SrcVT = Src.getValueType();
39912   EVT SrcSVT = SrcVT.getScalarType();
39913   if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
39914     return SDValue();
39915 
39916   SDLoc DL(Extract);
39917   SDValue MinPos = Src;
39918 
39919   // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
39920   while (SrcVT.getSizeInBits() > 128) {
39921     SDValue Lo, Hi;
39922     std::tie(Lo, Hi) = splitVector(MinPos, DAG, DL);
39923     SrcVT = Lo.getValueType();
39924     MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
39925   }
39926   assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||
39927           (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
39928          "Unexpected value type");
39929 
39930   // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
39931   // to flip the value accordingly.
39932   SDValue Mask;
39933   unsigned MaskEltsBits = ExtractVT.getSizeInBits();
39934   if (BinOp == ISD::SMAX)
39935     Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
39936   else if (BinOp == ISD::SMIN)
39937     Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
39938   else if (BinOp == ISD::UMAX)
39939     Mask = DAG.getConstant(APInt::getAllOnesValue(MaskEltsBits), DL, SrcVT);
39940 
39941   if (Mask)
39942     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
39943 
39944   // For v16i8 cases we need to perform UMIN on pairs of byte elements,
39945   // shuffling each upper element down and insert zeros. This means that the
39946   // v16i8 UMIN will leave the upper element as zero, performing zero-extension
39947   // ready for the PHMINPOS.
39948   if (ExtractVT == MVT::i8) {
39949     SDValue Upper = DAG.getVectorShuffle(
39950         SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
39951         {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
39952     MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
39953   }
39954 
39955   // Perform the PHMINPOS on a v8i16 vector,
39956   MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
39957   MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
39958   MinPos = DAG.getBitcast(SrcVT, MinPos);
39959 
39960   if (Mask)
39961     MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
39962 
39963   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
39964                      DAG.getIntPtrConstant(0, DL));
39965 }
39966 
39967 // Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
39968 static SDValue combinePredicateReduction(SDNode *Extract, SelectionDAG &DAG,
39969                                          const X86Subtarget &Subtarget) {
39970   // Bail without SSE2.
39971   if (!Subtarget.hasSSE2())
39972     return SDValue();
39973 
39974   EVT ExtractVT = Extract->getValueType(0);
39975   unsigned BitWidth = ExtractVT.getSizeInBits();
39976   if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
39977       ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
39978     return SDValue();
39979 
39980   // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
39981   ISD::NodeType BinOp;
39982   SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
39983   if (!Match && ExtractVT == MVT::i1)
39984     Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
39985   if (!Match)
39986     return SDValue();
39987 
39988   // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
39989   // which we can't support here for now.
39990   if (Match.getScalarValueSizeInBits() != BitWidth)
39991     return SDValue();
39992 
39993   SDValue Movmsk;
39994   SDLoc DL(Extract);
39995   EVT MatchVT = Match.getValueType();
39996   unsigned NumElts = MatchVT.getVectorNumElements();
39997   unsigned MaxElts = Subtarget.hasInt256() ? 32 : 16;
39998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39999 
40000   if (ExtractVT == MVT::i1) {
40001     // Special case for (pre-legalization) vXi1 reductions.
40002     if (NumElts > 64 || !isPowerOf2_32(NumElts))
40003       return SDValue();
40004     if (TLI.isTypeLegal(MatchVT)) {
40005       // If this is a legal AVX512 predicate type then we can just bitcast.
40006       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
40007       Movmsk = DAG.getBitcast(MovmskVT, Match);
40008     } else {
40009       // For all_of(setcc(vec,0,eq)) - avoid vXi64 comparisons if we don't have
40010       // PCMPEQQ (SSE41+), use PCMPEQD instead.
40011       if (BinOp == ISD::AND && !Subtarget.hasSSE41() &&
40012           Match.getOpcode() == ISD::SETCC &&
40013           ISD::isBuildVectorAllZeros(Match.getOperand(1).getNode()) &&
40014           cast<CondCodeSDNode>(Match.getOperand(2))->get() ==
40015               ISD::CondCode::SETEQ) {
40016         SDValue Vec = Match.getOperand(0);
40017         if (Vec.getValueType().getScalarType() == MVT::i64 &&
40018             (2 * NumElts) <= MaxElts) {
40019           NumElts *= 2;
40020           EVT CmpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
40021           MatchVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
40022           Match = DAG.getSetCC(
40023               DL, MatchVT, DAG.getBitcast(CmpVT, Match.getOperand(0)),
40024               DAG.getBitcast(CmpVT, Match.getOperand(1)), ISD::CondCode::SETEQ);
40025         }
40026       }
40027 
40028       // Use combineBitcastvxi1 to create the MOVMSK.
40029       while (NumElts > MaxElts) {
40030         SDValue Lo, Hi;
40031         std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
40032         Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
40033         NumElts /= 2;
40034       }
40035       EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
40036       Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
40037     }
40038     if (!Movmsk)
40039       return SDValue();
40040     Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, NumElts > 32 ? MVT::i64 : MVT::i32);
40041   } else {
40042     // FIXME: Better handling of k-registers or 512-bit vectors?
40043     unsigned MatchSizeInBits = Match.getValueSizeInBits();
40044     if (!(MatchSizeInBits == 128 ||
40045           (MatchSizeInBits == 256 && Subtarget.hasAVX())))
40046       return SDValue();
40047 
40048     // Make sure this isn't a vector of 1 element. The perf win from using
40049     // MOVMSK diminishes with less elements in the reduction, but it is
40050     // generally better to get the comparison over to the GPRs as soon as
40051     // possible to reduce the number of vector ops.
40052     if (Match.getValueType().getVectorNumElements() < 2)
40053       return SDValue();
40054 
40055     // Check that we are extracting a reduction of all sign bits.
40056     if (DAG.ComputeNumSignBits(Match) != BitWidth)
40057       return SDValue();
40058 
40059     if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
40060       SDValue Lo, Hi;
40061       std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
40062       Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
40063       MatchSizeInBits = Match.getValueSizeInBits();
40064     }
40065 
40066     // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
40067     MVT MaskSrcVT;
40068     if (64 == BitWidth || 32 == BitWidth)
40069       MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
40070                                    MatchSizeInBits / BitWidth);
40071     else
40072       MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
40073 
40074     SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
40075     Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
40076     NumElts = MaskSrcVT.getVectorNumElements();
40077   }
40078   assert((NumElts <= 32 || NumElts == 64) &&
40079          "Not expecting more than 64 elements");
40080 
40081   MVT CmpVT = NumElts == 64 ? MVT::i64 : MVT::i32;
40082   if (BinOp == ISD::XOR) {
40083     // parity -> (PARITY(MOVMSK X))
40084     SDValue Result = DAG.getNode(ISD::PARITY, DL, CmpVT, Movmsk);
40085     return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
40086   }
40087 
40088   SDValue CmpC;
40089   ISD::CondCode CondCode;
40090   if (BinOp == ISD::OR) {
40091     // any_of -> MOVMSK != 0
40092     CmpC = DAG.getConstant(0, DL, CmpVT);
40093     CondCode = ISD::CondCode::SETNE;
40094   } else {
40095     // all_of -> MOVMSK == ((1 << NumElts) - 1)
40096     CmpC = DAG.getConstant(APInt::getLowBitsSet(CmpVT.getSizeInBits(), NumElts),
40097                            DL, CmpVT);
40098     CondCode = ISD::CondCode::SETEQ;
40099   }
40100 
40101   // The setcc produces an i8 of 0/1, so extend that to the result width and
40102   // negate to get the final 0/-1 mask value.
40103   EVT SetccVT =
40104       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
40105   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
40106   SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
40107   SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
40108   return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
40109 }
40110 
40111 static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
40112                                       const X86Subtarget &Subtarget) {
40113   // PSADBW is only supported on SSE2 and up.
40114   if (!Subtarget.hasSSE2())
40115     return SDValue();
40116 
40117   EVT ExtractVT = Extract->getValueType(0);
40118   // Verify the type we're extracting is either i32 or i64.
40119   // FIXME: Could support other types, but this is what we have coverage for.
40120   if (ExtractVT != MVT::i32 && ExtractVT != MVT::i64)
40121     return SDValue();
40122 
40123   EVT VT = Extract->getOperand(0).getValueType();
40124   if (!isPowerOf2_32(VT.getVectorNumElements()))
40125     return SDValue();
40126 
40127   // Match shuffle + add pyramid.
40128   ISD::NodeType BinOp;
40129   SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
40130 
40131   // The operand is expected to be zero extended from i8
40132   // (verified in detectZextAbsDiff).
40133   // In order to convert to i64 and above, additional any/zero/sign
40134   // extend is expected.
40135   // The zero extend from 32 bit has no mathematical effect on the result.
40136   // Also the sign extend is basically zero extend
40137   // (extends the sign bit which is zero).
40138   // So it is correct to skip the sign/zero extend instruction.
40139   if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
40140                Root.getOpcode() == ISD::ZERO_EXTEND ||
40141                Root.getOpcode() == ISD::ANY_EXTEND))
40142     Root = Root.getOperand(0);
40143 
40144   // If there was a match, we want Root to be a select that is the root of an
40145   // abs-diff pattern.
40146   if (!Root || Root.getOpcode() != ISD::ABS)
40147     return SDValue();
40148 
40149   // Check whether we have an abs-diff pattern feeding into the select.
40150   SDValue Zext0, Zext1;
40151   if (!detectZextAbsDiff(Root, Zext0, Zext1))
40152     return SDValue();
40153 
40154   // Create the SAD instruction.
40155   SDLoc DL(Extract);
40156   SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
40157 
40158   // If the original vector was wider than 8 elements, sum over the results
40159   // in the SAD vector.
40160   unsigned Stages = Log2_32(VT.getVectorNumElements());
40161   EVT SadVT = SAD.getValueType();
40162   if (Stages > 3) {
40163     unsigned SadElems = SadVT.getVectorNumElements();
40164 
40165     for(unsigned i = Stages - 3; i > 0; --i) {
40166       SmallVector<int, 16> Mask(SadElems, -1);
40167       for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
40168         Mask[j] = MaskEnd + j;
40169 
40170       SDValue Shuffle =
40171           DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
40172       SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
40173     }
40174   }
40175 
40176   unsigned ExtractSizeInBits = ExtractVT.getSizeInBits();
40177   // Return the lowest ExtractSizeInBits bits.
40178   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), ExtractVT,
40179                                SadVT.getSizeInBits() / ExtractSizeInBits);
40180   SAD = DAG.getBitcast(ResVT, SAD);
40181   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, SAD,
40182                      Extract->getOperand(1));
40183 }
40184 
40185 // Attempt to peek through a target shuffle and extract the scalar from the
40186 // source.
40187 static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
40188                                          TargetLowering::DAGCombinerInfo &DCI,
40189                                          const X86Subtarget &Subtarget) {
40190   if (DCI.isBeforeLegalizeOps())
40191     return SDValue();
40192 
40193   SDLoc dl(N);
40194   SDValue Src = N->getOperand(0);
40195   SDValue Idx = N->getOperand(1);
40196 
40197   EVT VT = N->getValueType(0);
40198   EVT SrcVT = Src.getValueType();
40199   EVT SrcSVT = SrcVT.getVectorElementType();
40200   unsigned SrcEltBits = SrcSVT.getSizeInBits();
40201   unsigned NumSrcElts = SrcVT.getVectorNumElements();
40202 
40203   // Don't attempt this for boolean mask vectors or unknown extraction indices.
40204   if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
40205     return SDValue();
40206 
40207   const APInt &IdxC = N->getConstantOperandAPInt(1);
40208   if (IdxC.uge(NumSrcElts))
40209     return SDValue();
40210 
40211   SDValue SrcBC = peekThroughBitcasts(Src);
40212 
40213   // Handle extract(bitcast(broadcast(scalar_value))).
40214   if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
40215     SDValue SrcOp = SrcBC.getOperand(0);
40216     EVT SrcOpVT = SrcOp.getValueType();
40217     if (SrcOpVT.isScalarInteger() && VT.isInteger() &&
40218         (SrcOpVT.getSizeInBits() % SrcEltBits) == 0) {
40219       unsigned Scale = SrcOpVT.getSizeInBits() / SrcEltBits;
40220       unsigned Offset = IdxC.urem(Scale) * SrcEltBits;
40221       // TODO support non-zero offsets.
40222       if (Offset == 0) {
40223         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, SrcVT.getScalarType());
40224         SrcOp = DAG.getZExtOrTrunc(SrcOp, dl, VT);
40225         return SrcOp;
40226       }
40227     }
40228   }
40229 
40230   // If we're extracting a single element from a broadcast load and there are
40231   // no other users, just create a single load.
40232   if (SrcBC.getOpcode() == X86ISD::VBROADCAST_LOAD && SrcBC.hasOneUse()) {
40233     auto *MemIntr = cast<MemIntrinsicSDNode>(SrcBC);
40234     unsigned SrcBCWidth = SrcBC.getScalarValueSizeInBits();
40235     if (MemIntr->getMemoryVT().getSizeInBits() == SrcBCWidth &&
40236         VT.getSizeInBits() == SrcBCWidth && SrcEltBits == SrcBCWidth) {
40237       SDValue Load = DAG.getLoad(VT, dl, MemIntr->getChain(),
40238                                  MemIntr->getBasePtr(),
40239                                  MemIntr->getPointerInfo(),
40240                                  MemIntr->getOriginalAlign(),
40241                                  MemIntr->getMemOperand()->getFlags());
40242       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), Load.getValue(1));
40243       return Load;
40244     }
40245   }
40246 
40247   // Handle extract(bitcast(scalar_to_vector(scalar_value))) for integers.
40248   // TODO: Move to DAGCombine?
40249   if (SrcBC.getOpcode() == ISD::SCALAR_TO_VECTOR && VT.isInteger() &&
40250       SrcBC.getValueType().isInteger() &&
40251       (SrcBC.getScalarValueSizeInBits() % SrcEltBits) == 0 &&
40252       SrcBC.getScalarValueSizeInBits() ==
40253           SrcBC.getOperand(0).getValueSizeInBits()) {
40254     unsigned Scale = SrcBC.getScalarValueSizeInBits() / SrcEltBits;
40255     if (IdxC.ult(Scale)) {
40256       unsigned Offset = IdxC.getZExtValue() * SrcVT.getScalarSizeInBits();
40257       SDValue Scl = SrcBC.getOperand(0);
40258       EVT SclVT = Scl.getValueType();
40259       if (Offset) {
40260         Scl = DAG.getNode(ISD::SRL, dl, SclVT, Scl,
40261                           DAG.getShiftAmountConstant(Offset, SclVT, dl));
40262       }
40263       Scl = DAG.getZExtOrTrunc(Scl, dl, SrcVT.getScalarType());
40264       Scl = DAG.getZExtOrTrunc(Scl, dl, VT);
40265       return Scl;
40266     }
40267   }
40268 
40269   // Handle extract(truncate(x)) for 0'th index.
40270   // TODO: Treat this as a faux shuffle?
40271   // TODO: When can we use this for general indices?
40272   if (ISD::TRUNCATE == Src.getOpcode() && IdxC == 0 &&
40273       (SrcVT.getSizeInBits() % 128) == 0) {
40274     Src = extract128BitVector(Src.getOperand(0), 0, DAG, dl);
40275     MVT ExtractVT = MVT::getVectorVT(SrcSVT.getSimpleVT(), 128 / SrcEltBits);
40276     return DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(ExtractVT, Src),
40277                        Idx);
40278   }
40279 
40280   // Resolve the target shuffle inputs and mask.
40281   SmallVector<int, 16> Mask;
40282   SmallVector<SDValue, 2> Ops;
40283   if (!getTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
40284     return SDValue();
40285 
40286   // Shuffle inputs must be the same size as the result.
40287   if (llvm::any_of(Ops, [SrcVT](SDValue Op) {
40288         return SrcVT.getSizeInBits() != Op.getValueSizeInBits();
40289       }))
40290     return SDValue();
40291 
40292   // Attempt to narrow/widen the shuffle mask to the correct size.
40293   if (Mask.size() != NumSrcElts) {
40294     if ((NumSrcElts % Mask.size()) == 0) {
40295       SmallVector<int, 16> ScaledMask;
40296       int Scale = NumSrcElts / Mask.size();
40297       narrowShuffleMaskElts(Scale, Mask, ScaledMask);
40298       Mask = std::move(ScaledMask);
40299     } else if ((Mask.size() % NumSrcElts) == 0) {
40300       // Simplify Mask based on demanded element.
40301       int ExtractIdx = (int)N->getConstantOperandVal(1);
40302       int Scale = Mask.size() / NumSrcElts;
40303       int Lo = Scale * ExtractIdx;
40304       int Hi = Scale * (ExtractIdx + 1);
40305       for (int i = 0, e = (int)Mask.size(); i != e; ++i)
40306         if (i < Lo || Hi <= i)
40307           Mask[i] = SM_SentinelUndef;
40308 
40309       SmallVector<int, 16> WidenedMask;
40310       while (Mask.size() > NumSrcElts &&
40311              canWidenShuffleElements(Mask, WidenedMask))
40312         Mask = std::move(WidenedMask);
40313       // TODO - investigate support for wider shuffle masks with known upper
40314       // undef/zero elements for implicit zero-extension.
40315     }
40316   }
40317 
40318   // Check if narrowing/widening failed.
40319   if (Mask.size() != NumSrcElts)
40320     return SDValue();
40321 
40322   int SrcIdx = Mask[IdxC.getZExtValue()];
40323 
40324   // If the shuffle source element is undef/zero then we can just accept it.
40325   if (SrcIdx == SM_SentinelUndef)
40326     return DAG.getUNDEF(VT);
40327 
40328   if (SrcIdx == SM_SentinelZero)
40329     return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
40330                                 : DAG.getConstant(0, dl, VT);
40331 
40332   SDValue SrcOp = Ops[SrcIdx / Mask.size()];
40333   SrcIdx = SrcIdx % Mask.size();
40334 
40335   // We can only extract other elements from 128-bit vectors and in certain
40336   // circumstances, depending on SSE-level.
40337   // TODO: Investigate using extract_subvector for larger vectors.
40338   // TODO: Investigate float/double extraction if it will be just stored.
40339   if ((SrcVT == MVT::v4i32 || SrcVT == MVT::v2i64) &&
40340       ((SrcIdx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
40341     assert(SrcSVT == VT && "Unexpected extraction type");
40342     SrcOp = DAG.getBitcast(SrcVT, SrcOp);
40343     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcSVT, SrcOp,
40344                        DAG.getIntPtrConstant(SrcIdx, dl));
40345   }
40346 
40347   if ((SrcVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
40348       (SrcVT == MVT::v16i8 && Subtarget.hasSSE41())) {
40349     assert(VT.getSizeInBits() >= SrcEltBits && "Unexpected extraction type");
40350     unsigned OpCode = (SrcVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
40351     SrcOp = DAG.getBitcast(SrcVT, SrcOp);
40352     SDValue ExtOp = DAG.getNode(OpCode, dl, MVT::i32, SrcOp,
40353                                 DAG.getTargetConstant(SrcIdx, dl, MVT::i8));
40354     return DAG.getZExtOrTrunc(ExtOp, dl, VT);
40355   }
40356 
40357   return SDValue();
40358 }
40359 
40360 /// Extracting a scalar FP value from vector element 0 is free, so extract each
40361 /// operand first, then perform the math as a scalar op.
40362 static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG) {
40363   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract");
40364   SDValue Vec = ExtElt->getOperand(0);
40365   SDValue Index = ExtElt->getOperand(1);
40366   EVT VT = ExtElt->getValueType(0);
40367   EVT VecVT = Vec.getValueType();
40368 
40369   // TODO: If this is a unary/expensive/expand op, allow extraction from a
40370   // non-zero element because the shuffle+scalar op will be cheaper?
40371   if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
40372     return SDValue();
40373 
40374   // Vector FP compares don't fit the pattern of FP math ops (propagate, not
40375   // extract, the condition code), so deal with those as a special-case.
40376   if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
40377     EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
40378     if (OpVT != MVT::f32 && OpVT != MVT::f64)
40379       return SDValue();
40380 
40381     // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
40382     SDLoc DL(ExtElt);
40383     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
40384                                Vec.getOperand(0), Index);
40385     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
40386                                Vec.getOperand(1), Index);
40387     return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
40388   }
40389 
40390   if (VT != MVT::f32 && VT != MVT::f64)
40391     return SDValue();
40392 
40393   // Vector FP selects don't fit the pattern of FP math ops (because the
40394   // condition has a different type and we have to change the opcode), so deal
40395   // with those here.
40396   // FIXME: This is restricted to pre type legalization by ensuring the setcc
40397   // has i1 elements. If we loosen this we need to convert vector bool to a
40398   // scalar bool.
40399   if (Vec.getOpcode() == ISD::VSELECT &&
40400       Vec.getOperand(0).getOpcode() == ISD::SETCC &&
40401       Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
40402       Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
40403     // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
40404     SDLoc DL(ExtElt);
40405     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
40406                                Vec.getOperand(0).getValueType().getScalarType(),
40407                                Vec.getOperand(0), Index);
40408     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
40409                                Vec.getOperand(1), Index);
40410     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
40411                                Vec.getOperand(2), Index);
40412     return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
40413   }
40414 
40415   // TODO: This switch could include FNEG and the x86-specific FP logic ops
40416   // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
40417   // missed load folding and fma+fneg combining.
40418   switch (Vec.getOpcode()) {
40419   case ISD::FMA: // Begin 3 operands
40420   case ISD::FMAD:
40421   case ISD::FADD: // Begin 2 operands
40422   case ISD::FSUB:
40423   case ISD::FMUL:
40424   case ISD::FDIV:
40425   case ISD::FREM:
40426   case ISD::FCOPYSIGN:
40427   case ISD::FMINNUM:
40428   case ISD::FMAXNUM:
40429   case ISD::FMINNUM_IEEE:
40430   case ISD::FMAXNUM_IEEE:
40431   case ISD::FMAXIMUM:
40432   case ISD::FMINIMUM:
40433   case X86ISD::FMAX:
40434   case X86ISD::FMIN:
40435   case ISD::FABS: // Begin 1 operand
40436   case ISD::FSQRT:
40437   case ISD::FRINT:
40438   case ISD::FCEIL:
40439   case ISD::FTRUNC:
40440   case ISD::FNEARBYINT:
40441   case ISD::FROUND:
40442   case ISD::FFLOOR:
40443   case X86ISD::FRCP:
40444   case X86ISD::FRSQRT: {
40445     // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
40446     SDLoc DL(ExtElt);
40447     SmallVector<SDValue, 4> ExtOps;
40448     for (SDValue Op : Vec->ops())
40449       ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
40450     return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
40451   }
40452   default:
40453     return SDValue();
40454   }
40455   llvm_unreachable("All opcodes should return within switch");
40456 }
40457 
40458 /// Try to convert a vector reduction sequence composed of binops and shuffles
40459 /// into horizontal ops.
40460 static SDValue combineArithReduction(SDNode *ExtElt, SelectionDAG &DAG,
40461                                      const X86Subtarget &Subtarget) {
40462   assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unexpected caller");
40463 
40464   // We need at least SSE2 to anything here.
40465   if (!Subtarget.hasSSE2())
40466     return SDValue();
40467 
40468   ISD::NodeType Opc;
40469   SDValue Rdx = DAG.matchBinOpReduction(ExtElt, Opc,
40470                                         {ISD::ADD, ISD::MUL, ISD::FADD}, true);
40471   if (!Rdx)
40472     return SDValue();
40473 
40474   SDValue Index = ExtElt->getOperand(1);
40475   assert(isNullConstant(Index) &&
40476          "Reduction doesn't end in an extract from index 0");
40477 
40478   EVT VT = ExtElt->getValueType(0);
40479   EVT VecVT = Rdx.getValueType();
40480   if (VecVT.getScalarType() != VT)
40481     return SDValue();
40482 
40483   SDLoc DL(ExtElt);
40484 
40485   // vXi8 mul reduction - promote to vXi16 mul reduction.
40486   if (Opc == ISD::MUL) {
40487     unsigned NumElts = VecVT.getVectorNumElements();
40488     if (VT != MVT::i8 || NumElts < 4 || !isPowerOf2_32(NumElts))
40489       return SDValue();
40490     if (VecVT.getSizeInBits() >= 128) {
40491       EVT WideVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts / 2);
40492       SDValue Lo = getUnpackl(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
40493       SDValue Hi = getUnpackh(DAG, DL, VecVT, Rdx, DAG.getUNDEF(VecVT));
40494       Lo = DAG.getBitcast(WideVT, Lo);
40495       Hi = DAG.getBitcast(WideVT, Hi);
40496       Rdx = DAG.getNode(Opc, DL, WideVT, Lo, Hi);
40497       while (Rdx.getValueSizeInBits() > 128) {
40498         std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
40499         Rdx = DAG.getNode(Opc, DL, Lo.getValueType(), Lo, Hi);
40500       }
40501     } else {
40502       if (VecVT == MVT::v4i8)
40503         Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
40504                           DAG.getUNDEF(MVT::v4i8));
40505       Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
40506                         DAG.getUNDEF(MVT::v8i8));
40507       Rdx = getUnpackl(DAG, DL, MVT::v16i8, Rdx, DAG.getUNDEF(MVT::v16i8));
40508       Rdx = DAG.getBitcast(MVT::v8i16, Rdx);
40509     }
40510     if (NumElts >= 8)
40511       Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
40512                         DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
40513                                              {4, 5, 6, 7, -1, -1, -1, -1}));
40514     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
40515                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
40516                                            {2, 3, -1, -1, -1, -1, -1, -1}));
40517     Rdx = DAG.getNode(Opc, DL, MVT::v8i16, Rdx,
40518                       DAG.getVectorShuffle(MVT::v8i16, DL, Rdx, Rdx,
40519                                            {1, -1, -1, -1, -1, -1, -1, -1}));
40520     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
40521     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
40522   }
40523 
40524   // vXi8 add reduction - sub 128-bit vector.
40525   if (VecVT == MVT::v4i8 || VecVT == MVT::v8i8) {
40526     if (VecVT == MVT::v4i8) {
40527       // Pad with zero.
40528       if (Subtarget.hasSSE41()) {
40529         Rdx = DAG.getBitcast(MVT::i32, Rdx);
40530         Rdx = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, MVT::v4i32,
40531                           DAG.getConstant(0, DL, MVT::v4i32), Rdx,
40532                           DAG.getIntPtrConstant(0, DL));
40533         Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
40534       } else {
40535         Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i8, Rdx,
40536                           DAG.getConstant(0, DL, VecVT));
40537       }
40538     }
40539     if (Rdx.getValueType() == MVT::v8i8) {
40540       // Pad with undef.
40541       Rdx = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, Rdx,
40542                         DAG.getUNDEF(MVT::v8i8));
40543     }
40544     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
40545                       DAG.getConstant(0, DL, MVT::v16i8));
40546     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
40547     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
40548   }
40549 
40550   // Must be a >=128-bit vector with pow2 elements.
40551   if ((VecVT.getSizeInBits() % 128) != 0 ||
40552       !isPowerOf2_32(VecVT.getVectorNumElements()))
40553     return SDValue();
40554 
40555   // vXi8 add reduction - sum lo/hi halves then use PSADBW.
40556   if (VT == MVT::i8) {
40557     while (Rdx.getValueSizeInBits() > 128) {
40558       SDValue Lo, Hi;
40559       std::tie(Lo, Hi) = splitVector(Rdx, DAG, DL);
40560       VecVT = Lo.getValueType();
40561       Rdx = DAG.getNode(ISD::ADD, DL, VecVT, Lo, Hi);
40562     }
40563     assert(VecVT == MVT::v16i8 && "v16i8 reduction expected");
40564 
40565     SDValue Hi = DAG.getVectorShuffle(
40566         MVT::v16i8, DL, Rdx, Rdx,
40567         {8, 9, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1});
40568     Rdx = DAG.getNode(ISD::ADD, DL, MVT::v16i8, Rdx, Hi);
40569     Rdx = DAG.getNode(X86ISD::PSADBW, DL, MVT::v2i64, Rdx,
40570                       getZeroVector(MVT::v16i8, Subtarget, DAG, DL));
40571     Rdx = DAG.getBitcast(MVT::v16i8, Rdx);
40572     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
40573   }
40574 
40575   // Only use (F)HADD opcodes if they aren't microcoded or minimizes codesize.
40576   if (!shouldUseHorizontalOp(true, DAG, Subtarget))
40577     return SDValue();
40578 
40579   unsigned HorizOpcode = Opc == ISD::ADD ? X86ISD::HADD : X86ISD::FHADD;
40580 
40581   // 256-bit horizontal instructions operate on 128-bit chunks rather than
40582   // across the whole vector, so we need an extract + hop preliminary stage.
40583   // This is the only step where the operands of the hop are not the same value.
40584   // TODO: We could extend this to handle 512-bit or even longer vectors.
40585   if (((VecVT == MVT::v16i16 || VecVT == MVT::v8i32) && Subtarget.hasSSSE3()) ||
40586       ((VecVT == MVT::v8f32 || VecVT == MVT::v4f64) && Subtarget.hasSSE3())) {
40587     unsigned NumElts = VecVT.getVectorNumElements();
40588     SDValue Hi = extract128BitVector(Rdx, NumElts / 2, DAG, DL);
40589     SDValue Lo = extract128BitVector(Rdx, 0, DAG, DL);
40590     Rdx = DAG.getNode(HorizOpcode, DL, Lo.getValueType(), Hi, Lo);
40591     VecVT = Rdx.getValueType();
40592   }
40593   if (!((VecVT == MVT::v8i16 || VecVT == MVT::v4i32) && Subtarget.hasSSSE3()) &&
40594       !((VecVT == MVT::v4f32 || VecVT == MVT::v2f64) && Subtarget.hasSSE3()))
40595     return SDValue();
40596 
40597   // extract (add (shuf X), X), 0 --> extract (hadd X, X), 0
40598   unsigned ReductionSteps = Log2_32(VecVT.getVectorNumElements());
40599   for (unsigned i = 0; i != ReductionSteps; ++i)
40600     Rdx = DAG.getNode(HorizOpcode, DL, VecVT, Rdx, Rdx);
40601 
40602   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Rdx, Index);
40603 }
40604 
40605 /// Detect vector gather/scatter index generation and convert it from being a
40606 /// bunch of shuffles and extracts into a somewhat faster sequence.
40607 /// For i686, the best sequence is apparently storing the value and loading
40608 /// scalars back, while for x64 we should use 64-bit extracts and shifts.
40609 static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
40610                                        TargetLowering::DAGCombinerInfo &DCI,
40611                                        const X86Subtarget &Subtarget) {
40612   if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
40613     return NewOp;
40614 
40615   SDValue InputVector = N->getOperand(0);
40616   SDValue EltIdx = N->getOperand(1);
40617   auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
40618 
40619   EVT SrcVT = InputVector.getValueType();
40620   EVT VT = N->getValueType(0);
40621   SDLoc dl(InputVector);
40622   bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
40623   unsigned NumSrcElts = SrcVT.getVectorNumElements();
40624 
40625   if (CIdx && CIdx->getAPIntValue().uge(NumSrcElts))
40626     return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
40627 
40628   // Integer Constant Folding.
40629   if (CIdx && VT.isInteger()) {
40630     APInt UndefVecElts;
40631     SmallVector<APInt, 16> EltBits;
40632     unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
40633     if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
40634                                       EltBits, true, false)) {
40635       uint64_t Idx = CIdx->getZExtValue();
40636       if (UndefVecElts[Idx])
40637         return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
40638       return DAG.getConstant(EltBits[Idx].zextOrSelf(VT.getScalarSizeInBits()),
40639                              dl, VT);
40640     }
40641   }
40642 
40643   if (IsPextr) {
40644     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40645     if (TLI.SimplifyDemandedBits(
40646             SDValue(N, 0), APInt::getAllOnesValue(VT.getSizeInBits()), DCI))
40647       return SDValue(N, 0);
40648 
40649     // PEXTR*(PINSR*(v, s, c), c) -> s (with implicit zext handling).
40650     if ((InputVector.getOpcode() == X86ISD::PINSRB ||
40651          InputVector.getOpcode() == X86ISD::PINSRW) &&
40652         InputVector.getOperand(2) == EltIdx) {
40653       assert(SrcVT == InputVector.getOperand(0).getValueType() &&
40654              "Vector type mismatch");
40655       SDValue Scl = InputVector.getOperand(1);
40656       Scl = DAG.getNode(ISD::TRUNCATE, dl, SrcVT.getScalarType(), Scl);
40657       return DAG.getZExtOrTrunc(Scl, dl, VT);
40658     }
40659 
40660     // TODO - Remove this once we can handle the implicit zero-extension of
40661     // X86ISD::PEXTRW/X86ISD::PEXTRB in combinePredicateReduction and
40662     // combineBasicSADPattern.
40663     return SDValue();
40664   }
40665 
40666   // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
40667   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
40668       VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
40669     SDValue MMXSrc = InputVector.getOperand(0);
40670 
40671     // The bitcast source is a direct mmx result.
40672     if (MMXSrc.getValueType() == MVT::x86mmx)
40673       return DAG.getBitcast(VT, InputVector);
40674   }
40675 
40676   // Detect mmx to i32 conversion through a v2i32 elt extract.
40677   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
40678       VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
40679     SDValue MMXSrc = InputVector.getOperand(0);
40680 
40681     // The bitcast source is a direct mmx result.
40682     if (MMXSrc.getValueType() == MVT::x86mmx)
40683       return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
40684   }
40685 
40686   // Check whether this extract is the root of a sum of absolute differences
40687   // pattern. This has to be done here because we really want it to happen
40688   // pre-legalization,
40689   if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
40690     return SAD;
40691 
40692   // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
40693   if (SDValue Cmp = combinePredicateReduction(N, DAG, Subtarget))
40694     return Cmp;
40695 
40696   // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
40697   if (SDValue MinMax = combineMinMaxReduction(N, DAG, Subtarget))
40698     return MinMax;
40699 
40700   // Attempt to optimize ADD/FADD/MUL reductions with HADD, promotion etc..
40701   if (SDValue V = combineArithReduction(N, DAG, Subtarget))
40702     return V;
40703 
40704   if (SDValue V = scalarizeExtEltFP(N, DAG))
40705     return V;
40706 
40707   // Attempt to extract a i1 element by using MOVMSK to extract the signbits
40708   // and then testing the relevant element.
40709   //
40710   // Note that we only combine extracts on the *same* result number, i.e.
40711   //   t0 = merge_values a0, a1, a2, a3
40712   //   i1 = extract_vector_elt t0, Constant:i64<2>
40713   //   i1 = extract_vector_elt t0, Constant:i64<3>
40714   // but not
40715   //   i1 = extract_vector_elt t0:1, Constant:i64<2>
40716   // since the latter would need its own MOVMSK.
40717   if (CIdx && SrcVT.getScalarType() == MVT::i1) {
40718     SmallVector<SDNode *, 16> BoolExtracts;
40719     unsigned ResNo = InputVector.getResNo();
40720     auto IsBoolExtract = [&BoolExtracts, &ResNo](SDNode *Use) {
40721       if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
40722           isa<ConstantSDNode>(Use->getOperand(1)) &&
40723           Use->getOperand(0).getResNo() == ResNo &&
40724           Use->getValueType(0) == MVT::i1) {
40725         BoolExtracts.push_back(Use);
40726         return true;
40727       }
40728       return false;
40729     };
40730     if (all_of(InputVector->uses(), IsBoolExtract) &&
40731         BoolExtracts.size() > 1) {
40732       EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
40733       if (SDValue BC =
40734               combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
40735         for (SDNode *Use : BoolExtracts) {
40736           // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
40737           unsigned MaskIdx = Use->getConstantOperandVal(1);
40738           APInt MaskBit = APInt::getOneBitSet(NumSrcElts, MaskIdx);
40739           SDValue Mask = DAG.getConstant(MaskBit, dl, BCVT);
40740           SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
40741           Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
40742           DCI.CombineTo(Use, Res);
40743         }
40744         return SDValue(N, 0);
40745       }
40746     }
40747   }
40748 
40749   return SDValue();
40750 }
40751 
40752 /// If a vector select has an operand that is -1 or 0, try to simplify the
40753 /// select to a bitwise logic operation.
40754 /// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
40755 static SDValue
40756 combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
40757                                  TargetLowering::DAGCombinerInfo &DCI,
40758                                  const X86Subtarget &Subtarget) {
40759   SDValue Cond = N->getOperand(0);
40760   SDValue LHS = N->getOperand(1);
40761   SDValue RHS = N->getOperand(2);
40762   EVT VT = LHS.getValueType();
40763   EVT CondVT = Cond.getValueType();
40764   SDLoc DL(N);
40765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40766 
40767   if (N->getOpcode() != ISD::VSELECT)
40768     return SDValue();
40769 
40770   assert(CondVT.isVector() && "Vector select expects a vector selector!");
40771 
40772   // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
40773   // TODO: Can we assert that both operands are not zeros (because that should
40774   //       get simplified at node creation time)?
40775   bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
40776   bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
40777 
40778   // If both inputs are 0/undef, create a complete zero vector.
40779   // FIXME: As noted above this should be handled by DAGCombiner/getNode.
40780   if (TValIsAllZeros && FValIsAllZeros) {
40781     if (VT.isFloatingPoint())
40782       return DAG.getConstantFP(0.0, DL, VT);
40783     return DAG.getConstant(0, DL, VT);
40784   }
40785 
40786   // To use the condition operand as a bitwise mask, it must have elements that
40787   // are the same size as the select elements. Ie, the condition operand must
40788   // have already been promoted from the IR select condition type <N x i1>.
40789   // Don't check if the types themselves are equal because that excludes
40790   // vector floating-point selects.
40791   if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
40792     return SDValue();
40793 
40794   // Try to invert the condition if true value is not all 1s and false value is
40795   // not all 0s. Only do this if the condition has one use.
40796   bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
40797   if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
40798       // Check if the selector will be produced by CMPP*/PCMP*.
40799       Cond.getOpcode() == ISD::SETCC &&
40800       // Check if SETCC has already been promoted.
40801       TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
40802           CondVT) {
40803     bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
40804 
40805     if (TValIsAllZeros || FValIsAllOnes) {
40806       SDValue CC = Cond.getOperand(2);
40807       ISD::CondCode NewCC = ISD::getSetCCInverse(
40808           cast<CondCodeSDNode>(CC)->get(), Cond.getOperand(0).getValueType());
40809       Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
40810                           NewCC);
40811       std::swap(LHS, RHS);
40812       TValIsAllOnes = FValIsAllOnes;
40813       FValIsAllZeros = TValIsAllZeros;
40814     }
40815   }
40816 
40817   // Cond value must be 'sign splat' to be converted to a logical op.
40818   if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
40819     return SDValue();
40820 
40821   // vselect Cond, 111..., 000... -> Cond
40822   if (TValIsAllOnes && FValIsAllZeros)
40823     return DAG.getBitcast(VT, Cond);
40824 
40825   if (!TLI.isTypeLegal(CondVT))
40826     return SDValue();
40827 
40828   // vselect Cond, 111..., X -> or Cond, X
40829   if (TValIsAllOnes) {
40830     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
40831     SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
40832     return DAG.getBitcast(VT, Or);
40833   }
40834 
40835   // vselect Cond, X, 000... -> and Cond, X
40836   if (FValIsAllZeros) {
40837     SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
40838     SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
40839     return DAG.getBitcast(VT, And);
40840   }
40841 
40842   // vselect Cond, 000..., X -> andn Cond, X
40843   if (TValIsAllZeros) {
40844     SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
40845     SDValue AndN;
40846     // The canonical form differs for i1 vectors - x86andnp is not used
40847     if (CondVT.getScalarType() == MVT::i1)
40848       AndN = DAG.getNode(ISD::AND, DL, CondVT, DAG.getNOT(DL, Cond, CondVT),
40849                          CastRHS);
40850     else
40851       AndN = DAG.getNode(X86ISD::ANDNP, DL, CondVT, Cond, CastRHS);
40852     return DAG.getBitcast(VT, AndN);
40853   }
40854 
40855   return SDValue();
40856 }
40857 
40858 /// If both arms of a vector select are concatenated vectors, split the select,
40859 /// and concatenate the result to eliminate a wide (256-bit) vector instruction:
40860 ///   vselect Cond, (concat T0, T1), (concat F0, F1) -->
40861 ///   concat (vselect (split Cond), T0, F0), (vselect (split Cond), T1, F1)
40862 static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG,
40863                                   const X86Subtarget &Subtarget) {
40864   unsigned Opcode = N->getOpcode();
40865   if (Opcode != X86ISD::BLENDV && Opcode != ISD::VSELECT)
40866     return SDValue();
40867 
40868   // TODO: Split 512-bit vectors too?
40869   EVT VT = N->getValueType(0);
40870   if (!VT.is256BitVector())
40871     return SDValue();
40872 
40873   // TODO: Split as long as any 2 of the 3 operands are concatenated?
40874   SDValue Cond = N->getOperand(0);
40875   SDValue TVal = N->getOperand(1);
40876   SDValue FVal = N->getOperand(2);
40877   SmallVector<SDValue, 4> CatOpsT, CatOpsF;
40878   if (!TVal.hasOneUse() || !FVal.hasOneUse() ||
40879       !collectConcatOps(TVal.getNode(), CatOpsT) ||
40880       !collectConcatOps(FVal.getNode(), CatOpsF))
40881     return SDValue();
40882 
40883   auto makeBlend = [Opcode](SelectionDAG &DAG, const SDLoc &DL,
40884                             ArrayRef<SDValue> Ops) {
40885     return DAG.getNode(Opcode, DL, Ops[1].getValueType(), Ops);
40886   };
40887   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { Cond, TVal, FVal },
40888                           makeBlend, /*CheckBWI*/ false);
40889 }
40890 
40891 static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
40892   SDValue Cond = N->getOperand(0);
40893   SDValue LHS = N->getOperand(1);
40894   SDValue RHS = N->getOperand(2);
40895   SDLoc DL(N);
40896 
40897   auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
40898   auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
40899   if (!TrueC || !FalseC)
40900     return SDValue();
40901 
40902   // Don't do this for crazy integer types.
40903   EVT VT = N->getValueType(0);
40904   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
40905     return SDValue();
40906 
40907   // We're going to use the condition bit in math or logic ops. We could allow
40908   // this with a wider condition value (post-legalization it becomes an i8),
40909   // but if nothing is creating selects that late, it doesn't matter.
40910   if (Cond.getValueType() != MVT::i1)
40911     return SDValue();
40912 
40913   // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
40914   // 3, 5, or 9 with i32/i64, so those get transformed too.
40915   // TODO: For constants that overflow or do not differ by power-of-2 or small
40916   // multiplier, convert to 'and' + 'add'.
40917   const APInt &TrueVal = TrueC->getAPIntValue();
40918   const APInt &FalseVal = FalseC->getAPIntValue();
40919   bool OV;
40920   APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
40921   if (OV)
40922     return SDValue();
40923 
40924   APInt AbsDiff = Diff.abs();
40925   if (AbsDiff.isPowerOf2() ||
40926       ((VT == MVT::i32 || VT == MVT::i64) &&
40927        (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
40928 
40929     // We need a positive multiplier constant for shift/LEA codegen. The 'not'
40930     // of the condition can usually be folded into a compare predicate, but even
40931     // without that, the sequence should be cheaper than a CMOV alternative.
40932     if (TrueVal.slt(FalseVal)) {
40933       Cond = DAG.getNOT(DL, Cond, MVT::i1);
40934       std::swap(TrueC, FalseC);
40935     }
40936 
40937     // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
40938     SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
40939 
40940     // Multiply condition by the difference if non-one.
40941     if (!AbsDiff.isOneValue())
40942       R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
40943 
40944     // Add the base if non-zero.
40945     if (!FalseC->isNullValue())
40946       R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
40947 
40948     return R;
40949   }
40950 
40951   return SDValue();
40952 }
40953 
40954 /// If this is a *dynamic* select (non-constant condition) and we can match
40955 /// this node with one of the variable blend instructions, restructure the
40956 /// condition so that blends can use the high (sign) bit of each element.
40957 /// This function will also call SimplifyDemandedBits on already created
40958 /// BLENDV to perform additional simplifications.
40959 static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
40960                                            TargetLowering::DAGCombinerInfo &DCI,
40961                                            const X86Subtarget &Subtarget) {
40962   SDValue Cond = N->getOperand(0);
40963   if ((N->getOpcode() != ISD::VSELECT &&
40964        N->getOpcode() != X86ISD::BLENDV) ||
40965       ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
40966     return SDValue();
40967 
40968   // Don't optimize before the condition has been transformed to a legal type
40969   // and don't ever optimize vector selects that map to AVX512 mask-registers.
40970   unsigned BitWidth = Cond.getScalarValueSizeInBits();
40971   if (BitWidth < 8 || BitWidth > 64)
40972     return SDValue();
40973 
40974   // We can only handle the cases where VSELECT is directly legal on the
40975   // subtarget. We custom lower VSELECT nodes with constant conditions and
40976   // this makes it hard to see whether a dynamic VSELECT will correctly
40977   // lower, so we both check the operation's status and explicitly handle the
40978   // cases where a *dynamic* blend will fail even though a constant-condition
40979   // blend could be custom lowered.
40980   // FIXME: We should find a better way to handle this class of problems.
40981   // Potentially, we should combine constant-condition vselect nodes
40982   // pre-legalization into shuffles and not mark as many types as custom
40983   // lowered.
40984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40985   EVT VT = N->getValueType(0);
40986   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
40987     return SDValue();
40988   // FIXME: We don't support i16-element blends currently. We could and
40989   // should support them by making *all* the bits in the condition be set
40990   // rather than just the high bit and using an i8-element blend.
40991   if (VT.getVectorElementType() == MVT::i16)
40992     return SDValue();
40993   // Dynamic blending was only available from SSE4.1 onward.
40994   if (VT.is128BitVector() && !Subtarget.hasSSE41())
40995     return SDValue();
40996   // Byte blends are only available in AVX2
40997   if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
40998     return SDValue();
40999   // There are no 512-bit blend instructions that use sign bits.
41000   if (VT.is512BitVector())
41001     return SDValue();
41002 
41003   auto OnlyUsedAsSelectCond = [](SDValue Cond) {
41004     for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
41005          UI != UE; ++UI)
41006       if ((UI->getOpcode() != ISD::VSELECT &&
41007            UI->getOpcode() != X86ISD::BLENDV) ||
41008           UI.getOperandNo() != 0)
41009         return false;
41010 
41011     return true;
41012   };
41013 
41014   APInt DemandedBits(APInt::getSignMask(BitWidth));
41015 
41016   if (OnlyUsedAsSelectCond(Cond)) {
41017     KnownBits Known;
41018     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
41019                                           !DCI.isBeforeLegalizeOps());
41020     if (!TLI.SimplifyDemandedBits(Cond, DemandedBits, Known, TLO, 0, true))
41021       return SDValue();
41022 
41023     // If we changed the computation somewhere in the DAG, this change will
41024     // affect all users of Cond. Update all the nodes so that we do not use
41025     // the generic VSELECT anymore. Otherwise, we may perform wrong
41026     // optimizations as we messed with the actual expectation for the vector
41027     // boolean values.
41028     for (SDNode *U : Cond->uses()) {
41029       if (U->getOpcode() == X86ISD::BLENDV)
41030         continue;
41031 
41032       SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
41033                                Cond, U->getOperand(1), U->getOperand(2));
41034       DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
41035       DCI.AddToWorklist(U);
41036     }
41037     DCI.CommitTargetLoweringOpt(TLO);
41038     return SDValue(N, 0);
41039   }
41040 
41041   // Otherwise we can still at least try to simplify multiple use bits.
41042   if (SDValue V = TLI.SimplifyMultipleUseDemandedBits(Cond, DemandedBits, DAG))
41043       return DAG.getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), V,
41044                          N->getOperand(1), N->getOperand(2));
41045 
41046   return SDValue();
41047 }
41048 
41049 // Try to match:
41050 //   (or (and (M, (sub 0, X)), (pandn M, X)))
41051 // which is a special case of:
41052 //   (select M, (sub 0, X), X)
41053 // Per:
41054 // http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
41055 // We know that, if fNegate is 0 or 1:
41056 //   (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
41057 //
41058 // Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
41059 //   ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
41060 //   ( M      ? -X : X) == ((X ^   M     ) + (M & 1))
41061 // This lets us transform our vselect to:
41062 //   (add (xor X, M), (and M, 1))
41063 // And further to:
41064 //   (sub (xor X, M), M)
41065 static SDValue combineLogicBlendIntoConditionalNegate(
41066     EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
41067     SelectionDAG &DAG, const X86Subtarget &Subtarget) {
41068   EVT MaskVT = Mask.getValueType();
41069   assert(MaskVT.isInteger() &&
41070          DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&
41071          "Mask must be zero/all-bits");
41072 
41073   if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
41074     return SDValue();
41075   if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
41076     return SDValue();
41077 
41078   auto IsNegV = [](SDNode *N, SDValue V) {
41079     return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
41080            ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
41081   };
41082 
41083   SDValue V;
41084   if (IsNegV(Y.getNode(), X))
41085     V = X;
41086   else if (IsNegV(X.getNode(), Y))
41087     V = Y;
41088   else
41089     return SDValue();
41090 
41091   SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
41092   SDValue SubOp2 = Mask;
41093 
41094   // If the negate was on the false side of the select, then
41095   // the operands of the SUB need to be swapped. PR 27251.
41096   // This is because the pattern being matched above is
41097   // (vselect M, (sub (0, X), X)  -> (sub (xor X, M), M)
41098   // but if the pattern matched was
41099   // (vselect M, X, (sub (0, X))), that is really negation of the pattern
41100   // above, -(vselect M, (sub 0, X), X), and therefore the replacement
41101   // pattern also needs to be a negation of the replacement pattern above.
41102   // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
41103   // sub accomplishes the negation of the replacement pattern.
41104   if (V == Y)
41105     std::swap(SubOp1, SubOp2);
41106 
41107   SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
41108   return DAG.getBitcast(VT, Res);
41109 }
41110 
41111 /// Do target-specific dag combines on SELECT and VSELECT nodes.
41112 static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
41113                              TargetLowering::DAGCombinerInfo &DCI,
41114                              const X86Subtarget &Subtarget) {
41115   SDLoc DL(N);
41116   SDValue Cond = N->getOperand(0);
41117   SDValue LHS = N->getOperand(1);
41118   SDValue RHS = N->getOperand(2);
41119 
41120   // Try simplification again because we use this function to optimize
41121   // BLENDV nodes that are not handled by the generic combiner.
41122   if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
41123     return V;
41124 
41125   EVT VT = LHS.getValueType();
41126   EVT CondVT = Cond.getValueType();
41127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41128   bool CondConstantVector = ISD::isBuildVectorOfConstantSDNodes(Cond.getNode());
41129 
41130   // Attempt to combine (select M, (sub 0, X), X) -> (sub (xor X, M), M).
41131   // Limit this to cases of non-constant masks that createShuffleMaskFromVSELECT
41132   // can't catch, plus vXi8 cases where we'd likely end up with BLENDV.
41133   if (CondVT.isVector() && CondVT.isInteger() &&
41134       CondVT.getScalarSizeInBits() == VT.getScalarSizeInBits() &&
41135       (!CondConstantVector || CondVT.getScalarType() == MVT::i8) &&
41136       DAG.ComputeNumSignBits(Cond) == CondVT.getScalarSizeInBits())
41137     if (SDValue V = combineLogicBlendIntoConditionalNegate(VT, Cond, RHS, LHS,
41138                                                            DL, DAG, Subtarget))
41139       return V;
41140 
41141   // Convert vselects with constant condition into shuffles.
41142   if (CondConstantVector && DCI.isBeforeLegalizeOps()) {
41143     SmallVector<int, 64> Mask;
41144     if (createShuffleMaskFromVSELECT(Mask, Cond))
41145       return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
41146   }
41147 
41148   // fold vselect(cond, pshufb(x), pshufb(y)) -> or (pshufb(x), pshufb(y))
41149   // by forcing the unselected elements to zero.
41150   // TODO: Can we handle more shuffles with this?
41151   if (N->getOpcode() == ISD::VSELECT && CondVT.isVector() &&
41152       LHS.getOpcode() == X86ISD::PSHUFB && RHS.getOpcode() == X86ISD::PSHUFB &&
41153       LHS.hasOneUse() && RHS.hasOneUse()) {
41154     MVT SimpleVT = VT.getSimpleVT();
41155     bool LHSUnary, RHSUnary;
41156     SmallVector<SDValue, 1> LHSOps, RHSOps;
41157     SmallVector<int, 64> LHSMask, RHSMask, CondMask;
41158     if (createShuffleMaskFromVSELECT(CondMask, Cond) &&
41159         getTargetShuffleMask(LHS.getNode(), SimpleVT, true, LHSOps, LHSMask,
41160                              LHSUnary) &&
41161         getTargetShuffleMask(RHS.getNode(), SimpleVT, true, RHSOps, RHSMask,
41162                              RHSUnary)) {
41163       int NumElts = VT.getVectorNumElements();
41164       for (int i = 0; i != NumElts; ++i) {
41165         if (CondMask[i] < NumElts)
41166           RHSMask[i] = 0x80;
41167         else
41168           LHSMask[i] = 0x80;
41169       }
41170       LHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, LHS.getOperand(0),
41171                         getConstVector(LHSMask, SimpleVT, DAG, DL, true));
41172       RHS = DAG.getNode(X86ISD::PSHUFB, DL, VT, RHS.getOperand(0),
41173                         getConstVector(RHSMask, SimpleVT, DAG, DL, true));
41174       return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
41175     }
41176   }
41177 
41178   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
41179   // instructions match the semantics of the common C idiom x<y?x:y but not
41180   // x<=y?x:y, because of how they handle negative zero (which can be
41181   // ignored in unsafe-math mode).
41182   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
41183   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
41184       VT != MVT::f80 && VT != MVT::f128 &&
41185       (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
41186       (Subtarget.hasSSE2() ||
41187        (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
41188     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
41189 
41190     unsigned Opcode = 0;
41191     // Check for x CC y ? x : y.
41192     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
41193         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
41194       switch (CC) {
41195       default: break;
41196       case ISD::SETULT:
41197         // Converting this to a min would handle NaNs incorrectly, and swapping
41198         // the operands would cause it to handle comparisons between positive
41199         // and negative zero incorrectly.
41200         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
41201           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41202               !(DAG.isKnownNeverZeroFloat(LHS) ||
41203                 DAG.isKnownNeverZeroFloat(RHS)))
41204             break;
41205           std::swap(LHS, RHS);
41206         }
41207         Opcode = X86ISD::FMIN;
41208         break;
41209       case ISD::SETOLE:
41210         // Converting this to a min would handle comparisons between positive
41211         // and negative zero incorrectly.
41212         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41213             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
41214           break;
41215         Opcode = X86ISD::FMIN;
41216         break;
41217       case ISD::SETULE:
41218         // Converting this to a min would handle both negative zeros and NaNs
41219         // incorrectly, but we can swap the operands to fix both.
41220         std::swap(LHS, RHS);
41221         LLVM_FALLTHROUGH;
41222       case ISD::SETOLT:
41223       case ISD::SETLT:
41224       case ISD::SETLE:
41225         Opcode = X86ISD::FMIN;
41226         break;
41227 
41228       case ISD::SETOGE:
41229         // Converting this to a max would handle comparisons between positive
41230         // and negative zero incorrectly.
41231         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41232             !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
41233           break;
41234         Opcode = X86ISD::FMAX;
41235         break;
41236       case ISD::SETUGT:
41237         // Converting this to a max would handle NaNs incorrectly, and swapping
41238         // the operands would cause it to handle comparisons between positive
41239         // and negative zero incorrectly.
41240         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
41241           if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41242               !(DAG.isKnownNeverZeroFloat(LHS) ||
41243                 DAG.isKnownNeverZeroFloat(RHS)))
41244             break;
41245           std::swap(LHS, RHS);
41246         }
41247         Opcode = X86ISD::FMAX;
41248         break;
41249       case ISD::SETUGE:
41250         // Converting this to a max would handle both negative zeros and NaNs
41251         // incorrectly, but we can swap the operands to fix both.
41252         std::swap(LHS, RHS);
41253         LLVM_FALLTHROUGH;
41254       case ISD::SETOGT:
41255       case ISD::SETGT:
41256       case ISD::SETGE:
41257         Opcode = X86ISD::FMAX;
41258         break;
41259       }
41260     // Check for x CC y ? y : x -- a min/max with reversed arms.
41261     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
41262                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
41263       switch (CC) {
41264       default: break;
41265       case ISD::SETOGE:
41266         // Converting this to a min would handle comparisons between positive
41267         // and negative zero incorrectly, and swapping the operands would
41268         // cause it to handle NaNs incorrectly.
41269         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41270             !(DAG.isKnownNeverZeroFloat(LHS) ||
41271               DAG.isKnownNeverZeroFloat(RHS))) {
41272           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41273             break;
41274           std::swap(LHS, RHS);
41275         }
41276         Opcode = X86ISD::FMIN;
41277         break;
41278       case ISD::SETUGT:
41279         // Converting this to a min would handle NaNs incorrectly.
41280         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41281           break;
41282         Opcode = X86ISD::FMIN;
41283         break;
41284       case ISD::SETUGE:
41285         // Converting this to a min would handle both negative zeros and NaNs
41286         // incorrectly, but we can swap the operands to fix both.
41287         std::swap(LHS, RHS);
41288         LLVM_FALLTHROUGH;
41289       case ISD::SETOGT:
41290       case ISD::SETGT:
41291       case ISD::SETGE:
41292         Opcode = X86ISD::FMIN;
41293         break;
41294 
41295       case ISD::SETULT:
41296         // Converting this to a max would handle NaNs incorrectly.
41297         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41298           break;
41299         Opcode = X86ISD::FMAX;
41300         break;
41301       case ISD::SETOLE:
41302         // Converting this to a max would handle comparisons between positive
41303         // and negative zero incorrectly, and swapping the operands would
41304         // cause it to handle NaNs incorrectly.
41305         if (!DAG.getTarget().Options.NoSignedZerosFPMath &&
41306             !DAG.isKnownNeverZeroFloat(LHS) &&
41307             !DAG.isKnownNeverZeroFloat(RHS)) {
41308           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
41309             break;
41310           std::swap(LHS, RHS);
41311         }
41312         Opcode = X86ISD::FMAX;
41313         break;
41314       case ISD::SETULE:
41315         // Converting this to a max would handle both negative zeros and NaNs
41316         // incorrectly, but we can swap the operands to fix both.
41317         std::swap(LHS, RHS);
41318         LLVM_FALLTHROUGH;
41319       case ISD::SETOLT:
41320       case ISD::SETLT:
41321       case ISD::SETLE:
41322         Opcode = X86ISD::FMAX;
41323         break;
41324       }
41325     }
41326 
41327     if (Opcode)
41328       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
41329   }
41330 
41331   // Some mask scalar intrinsics rely on checking if only one bit is set
41332   // and implement it in C code like this:
41333   // A[0] = (U & 1) ? A[0] : W[0];
41334   // This creates some redundant instructions that break pattern matching.
41335   // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
41336   if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
41337       Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
41338     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
41339     SDValue AndNode = Cond.getOperand(0);
41340     if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
41341         isNullConstant(Cond.getOperand(1)) &&
41342         isOneConstant(AndNode.getOperand(1))) {
41343       // LHS and RHS swapped due to
41344       // setcc outputting 1 when AND resulted in 0 and vice versa.
41345       AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
41346       return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
41347     }
41348   }
41349 
41350   // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
41351   // lowering on KNL. In this case we convert it to
41352   // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
41353   // The same situation all vectors of i8 and i16 without BWI.
41354   // Make sure we extend these even before type legalization gets a chance to
41355   // split wide vectors.
41356   // Since SKX these selects have a proper lowering.
41357   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
41358       CondVT.getVectorElementType() == MVT::i1 &&
41359       (VT.getVectorElementType() == MVT::i8 ||
41360        VT.getVectorElementType() == MVT::i16)) {
41361     Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
41362     return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
41363   }
41364 
41365   // AVX512 - Extend select with zero to merge with target shuffle.
41366   // select(mask, extract_subvector(shuffle(x)), zero) -->
41367   // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
41368   // TODO - support non target shuffles as well.
41369   if (Subtarget.hasAVX512() && CondVT.isVector() &&
41370       CondVT.getVectorElementType() == MVT::i1) {
41371     auto SelectableOp = [&TLI](SDValue Op) {
41372       return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
41373              isTargetShuffle(Op.getOperand(0).getOpcode()) &&
41374              isNullConstant(Op.getOperand(1)) &&
41375              TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
41376              Op.hasOneUse() && Op.getOperand(0).hasOneUse();
41377     };
41378 
41379     bool SelectableLHS = SelectableOp(LHS);
41380     bool SelectableRHS = SelectableOp(RHS);
41381     bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
41382     bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
41383 
41384     if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
41385       EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
41386                                 : RHS.getOperand(0).getValueType();
41387       unsigned NumSrcElts = SrcVT.getVectorNumElements();
41388       EVT SrcCondVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumSrcElts);
41389       LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
41390                             VT.getSizeInBits());
41391       RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
41392                             VT.getSizeInBits());
41393       Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
41394                          DAG.getUNDEF(SrcCondVT), Cond,
41395                          DAG.getIntPtrConstant(0, DL));
41396       SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
41397       return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
41398     }
41399   }
41400 
41401   if (SDValue V = combineSelectOfTwoConstants(N, DAG))
41402     return V;
41403 
41404   // Canonicalize min/max:
41405   // (x > 0) ? x : 0 -> (x >= 0) ? x : 0
41406   // (x < -1) ? x : -1 -> (x <= -1) ? x : -1
41407   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
41408   // the need for an extra compare against zero. e.g.
41409   // (a - b) > 0 : (a - b) ? 0 -> (a - b) >= 0 : (a - b) ? 0
41410   // subl   %esi, %edi
41411   // testl  %edi, %edi
41412   // movl   $0, %eax
41413   // cmovgl %edi, %eax
41414   // =>
41415   // xorl   %eax, %eax
41416   // subl   %esi, $edi
41417   // cmovsl %eax, %edi
41418   //
41419   // We can also canonicalize
41420   //  (x s> 1) ? x : 1 -> (x s>= 1) ? x : 1 -> (x s> 0) ? x : 1
41421   //  (x u> 1) ? x : 1 -> (x u>= 1) ? x : 1 -> (x != 0) ? x : 1
41422   // This allows the use of a test instruction for the compare.
41423   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
41424       Cond.hasOneUse() &&
41425       LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
41426     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
41427     if ((CC == ISD::SETGT && (isNullConstant(RHS) || isOneConstant(RHS))) ||
41428         (CC == ISD::SETLT && isAllOnesConstant(RHS))) {
41429       ISD::CondCode NewCC = CC == ISD::SETGT ? ISD::SETGE : ISD::SETLE;
41430       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
41431                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
41432       return DAG.getSelect(DL, VT, Cond, LHS, RHS);
41433     }
41434     if (CC == ISD::SETUGT && isOneConstant(RHS)) {
41435       ISD::CondCode NewCC = ISD::SETUGE;
41436       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
41437                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
41438       return DAG.getSelect(DL, VT, Cond, LHS, RHS);
41439     }
41440   }
41441 
41442   // Check if the first operand is all zeros and Cond type is vXi1.
41443   // If this an avx512 target we can improve the use of zero masking by
41444   // swapping the operands and inverting the condition.
41445   if (N->getOpcode() == ISD::VSELECT && Cond.hasOneUse() &&
41446        Subtarget.hasAVX512() && CondVT.getVectorElementType() == MVT::i1 &&
41447       ISD::isBuildVectorAllZeros(LHS.getNode()) &&
41448       !ISD::isBuildVectorAllZeros(RHS.getNode())) {
41449     // Invert the cond to not(cond) : xor(op,allones)=not(op)
41450     SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
41451     // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
41452     return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
41453   }
41454 
41455   // Early exit check
41456   if (!TLI.isTypeLegal(VT))
41457     return SDValue();
41458 
41459   if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
41460     return V;
41461 
41462   if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
41463     return V;
41464 
41465   if (SDValue V = narrowVectorSelect(N, DAG, Subtarget))
41466     return V;
41467 
41468   // select(~Cond, X, Y) -> select(Cond, Y, X)
41469   if (CondVT.getScalarType() != MVT::i1) {
41470     if (SDValue CondNot = IsNOT(Cond, DAG))
41471       return DAG.getNode(N->getOpcode(), DL, VT,
41472                          DAG.getBitcast(CondVT, CondNot), RHS, LHS);
41473     // pcmpgt(X, -1) -> pcmpgt(0, X) to help select/blendv just use the signbit.
41474     if (Cond.getOpcode() == X86ISD::PCMPGT && Cond.hasOneUse() &&
41475         ISD::isBuildVectorAllOnes(Cond.getOperand(1).getNode())) {
41476       Cond = DAG.getNode(X86ISD::PCMPGT, DL, CondVT,
41477                          DAG.getConstant(0, DL, CondVT), Cond.getOperand(0));
41478       return DAG.getNode(N->getOpcode(), DL, VT, Cond, RHS, LHS);
41479     }
41480   }
41481 
41482   // Try to optimize vXi1 selects if both operands are either all constants or
41483   // bitcasts from scalar integer type. In that case we can convert the operands
41484   // to integer and use an integer select which will be converted to a CMOV.
41485   // We need to take a little bit of care to avoid creating an i64 type after
41486   // type legalization.
41487   if (N->getOpcode() == ISD::SELECT && VT.isVector() &&
41488       VT.getVectorElementType() == MVT::i1 &&
41489       (DCI.isBeforeLegalize() || (VT != MVT::v64i1 || Subtarget.is64Bit()))) {
41490     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
41491     bool LHSIsConst = ISD::isBuildVectorOfConstantSDNodes(LHS.getNode());
41492     bool RHSIsConst = ISD::isBuildVectorOfConstantSDNodes(RHS.getNode());
41493 
41494     if ((LHSIsConst ||
41495          (LHS.getOpcode() == ISD::BITCAST &&
41496           LHS.getOperand(0).getValueType() == IntVT)) &&
41497         (RHSIsConst ||
41498          (RHS.getOpcode() == ISD::BITCAST &&
41499           RHS.getOperand(0).getValueType() == IntVT))) {
41500       if (LHSIsConst)
41501         LHS = combinevXi1ConstantToInteger(LHS, DAG);
41502       else
41503         LHS = LHS.getOperand(0);
41504 
41505       if (RHSIsConst)
41506         RHS = combinevXi1ConstantToInteger(RHS, DAG);
41507       else
41508         RHS = RHS.getOperand(0);
41509 
41510       SDValue Select = DAG.getSelect(DL, IntVT, Cond, LHS, RHS);
41511       return DAG.getBitcast(VT, Select);
41512     }
41513   }
41514 
41515   // If this is "((X & C) == 0) ? Y : Z" and C is a constant mask vector of
41516   // single bits, then invert the predicate and swap the select operands.
41517   // This can lower using a vector shift bit-hack rather than mask and compare.
41518   if (DCI.isBeforeLegalize() && !Subtarget.hasAVX512() &&
41519       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
41520       Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1 &&
41521       Cond.getOperand(0).getOpcode() == ISD::AND &&
41522       isNullOrNullSplat(Cond.getOperand(1)) &&
41523       cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
41524       Cond.getOperand(0).getValueType() == VT) {
41525     // The 'and' mask must be composed of power-of-2 constants.
41526     SDValue And = Cond.getOperand(0);
41527     auto *C = isConstOrConstSplat(And.getOperand(1));
41528     if (C && C->getAPIntValue().isPowerOf2()) {
41529       // vselect (X & C == 0), LHS, RHS --> vselect (X & C != 0), RHS, LHS
41530       SDValue NotCond =
41531           DAG.getSetCC(DL, CondVT, And, Cond.getOperand(1), ISD::SETNE);
41532       return DAG.getSelect(DL, VT, NotCond, RHS, LHS);
41533     }
41534 
41535     // If we have a non-splat but still powers-of-2 mask, AVX1 can use pmulld
41536     // and AVX2 can use vpsllv{dq}. 8-bit lacks a proper shift or multiply.
41537     // 16-bit lacks a proper blendv.
41538     unsigned EltBitWidth = VT.getScalarSizeInBits();
41539     bool CanShiftBlend =
41540         TLI.isTypeLegal(VT) && ((Subtarget.hasAVX() && EltBitWidth == 32) ||
41541                                 (Subtarget.hasAVX2() && EltBitWidth == 64) ||
41542                                 (Subtarget.hasXOP()));
41543     if (CanShiftBlend &&
41544         ISD::matchUnaryPredicate(And.getOperand(1), [](ConstantSDNode *C) {
41545           return C->getAPIntValue().isPowerOf2();
41546         })) {
41547       // Create a left-shift constant to get the mask bits over to the sign-bit.
41548       SDValue Mask = And.getOperand(1);
41549       SmallVector<int, 32> ShlVals;
41550       for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
41551         auto *MaskVal = cast<ConstantSDNode>(Mask.getOperand(i));
41552         ShlVals.push_back(EltBitWidth - 1 -
41553                           MaskVal->getAPIntValue().exactLogBase2());
41554       }
41555       // vsel ((X & C) == 0), LHS, RHS --> vsel ((shl X, C') < 0), RHS, LHS
41556       SDValue ShlAmt = getConstVector(ShlVals, VT.getSimpleVT(), DAG, DL);
41557       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And.getOperand(0), ShlAmt);
41558       SDValue NewCond =
41559           DAG.getSetCC(DL, CondVT, Shl, Cond.getOperand(1), ISD::SETLT);
41560       return DAG.getSelect(DL, VT, NewCond, RHS, LHS);
41561     }
41562   }
41563 
41564   return SDValue();
41565 }
41566 
41567 /// Combine:
41568 ///   (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
41569 /// to:
41570 ///   (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
41571 /// i.e., reusing the EFLAGS produced by the LOCKed instruction.
41572 /// Note that this is only legal for some op/cc combinations.
41573 static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
41574                                        SelectionDAG &DAG,
41575                                        const X86Subtarget &Subtarget) {
41576   // This combine only operates on CMP-like nodes.
41577   if (!(Cmp.getOpcode() == X86ISD::CMP ||
41578         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
41579     return SDValue();
41580 
41581   // Can't replace the cmp if it has more uses than the one we're looking at.
41582   // FIXME: We would like to be able to handle this, but would need to make sure
41583   // all uses were updated.
41584   if (!Cmp.hasOneUse())
41585     return SDValue();
41586 
41587   // This only applies to variations of the common case:
41588   //   (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
41589   //   (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
41590   //   (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
41591   //   (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
41592   // Using the proper condcodes (see below), overflow is checked for.
41593 
41594   // FIXME: We can generalize both constraints:
41595   // - XOR/OR/AND (if they were made to survive AtomicExpand)
41596   // - LHS != 1
41597   // if the result is compared.
41598 
41599   SDValue CmpLHS = Cmp.getOperand(0);
41600   SDValue CmpRHS = Cmp.getOperand(1);
41601 
41602   if (!CmpLHS.hasOneUse())
41603     return SDValue();
41604 
41605   unsigned Opc = CmpLHS.getOpcode();
41606   if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
41607     return SDValue();
41608 
41609   SDValue OpRHS = CmpLHS.getOperand(2);
41610   auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
41611   if (!OpRHSC)
41612     return SDValue();
41613 
41614   APInt Addend = OpRHSC->getAPIntValue();
41615   if (Opc == ISD::ATOMIC_LOAD_SUB)
41616     Addend = -Addend;
41617 
41618   auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
41619   if (!CmpRHSC)
41620     return SDValue();
41621 
41622   APInt Comparison = CmpRHSC->getAPIntValue();
41623 
41624   // If the addend is the negation of the comparison value, then we can do
41625   // a full comparison by emitting the atomic arithmetic as a locked sub.
41626   if (Comparison == -Addend) {
41627     // The CC is fine, but we need to rewrite the LHS of the comparison as an
41628     // atomic sub.
41629     auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
41630     auto AtomicSub = DAG.getAtomic(
41631         ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpLHS.getValueType(),
41632         /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
41633         /*RHS*/ DAG.getConstant(-Addend, SDLoc(CmpRHS), CmpRHS.getValueType()),
41634         AN->getMemOperand());
41635     auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
41636     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
41637                                   DAG.getUNDEF(CmpLHS.getValueType()));
41638     DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
41639     return LockOp;
41640   }
41641 
41642   // We can handle comparisons with zero in a number of cases by manipulating
41643   // the CC used.
41644   if (!Comparison.isNullValue())
41645     return SDValue();
41646 
41647   if (CC == X86::COND_S && Addend == 1)
41648     CC = X86::COND_LE;
41649   else if (CC == X86::COND_NS && Addend == 1)
41650     CC = X86::COND_G;
41651   else if (CC == X86::COND_G && Addend == -1)
41652     CC = X86::COND_GE;
41653   else if (CC == X86::COND_LE && Addend == -1)
41654     CC = X86::COND_L;
41655   else
41656     return SDValue();
41657 
41658   SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
41659   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
41660                                 DAG.getUNDEF(CmpLHS.getValueType()));
41661   DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
41662   return LockOp;
41663 }
41664 
41665 // Check whether a boolean test is testing a boolean value generated by
41666 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
41667 // code.
41668 //
41669 // Simplify the following patterns:
41670 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
41671 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
41672 // to (Op EFLAGS Cond)
41673 //
41674 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
41675 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
41676 // to (Op EFLAGS !Cond)
41677 //
41678 // where Op could be BRCOND or CMOV.
41679 //
41680 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
41681   // This combine only operates on CMP-like nodes.
41682   if (!(Cmp.getOpcode() == X86ISD::CMP ||
41683         (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
41684     return SDValue();
41685 
41686   // Quit if not used as a boolean value.
41687   if (CC != X86::COND_E && CC != X86::COND_NE)
41688     return SDValue();
41689 
41690   // Check CMP operands. One of them should be 0 or 1 and the other should be
41691   // an SetCC or extended from it.
41692   SDValue Op1 = Cmp.getOperand(0);
41693   SDValue Op2 = Cmp.getOperand(1);
41694 
41695   SDValue SetCC;
41696   const ConstantSDNode* C = nullptr;
41697   bool needOppositeCond = (CC == X86::COND_E);
41698   bool checkAgainstTrue = false; // Is it a comparison against 1?
41699 
41700   if ((C = dyn_cast<ConstantSDNode>(Op1)))
41701     SetCC = Op2;
41702   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
41703     SetCC = Op1;
41704   else // Quit if all operands are not constants.
41705     return SDValue();
41706 
41707   if (C->getZExtValue() == 1) {
41708     needOppositeCond = !needOppositeCond;
41709     checkAgainstTrue = true;
41710   } else if (C->getZExtValue() != 0)
41711     // Quit if the constant is neither 0 or 1.
41712     return SDValue();
41713 
41714   bool truncatedToBoolWithAnd = false;
41715   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
41716   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
41717          SetCC.getOpcode() == ISD::TRUNCATE ||
41718          SetCC.getOpcode() == ISD::AND) {
41719     if (SetCC.getOpcode() == ISD::AND) {
41720       int OpIdx = -1;
41721       if (isOneConstant(SetCC.getOperand(0)))
41722         OpIdx = 1;
41723       if (isOneConstant(SetCC.getOperand(1)))
41724         OpIdx = 0;
41725       if (OpIdx < 0)
41726         break;
41727       SetCC = SetCC.getOperand(OpIdx);
41728       truncatedToBoolWithAnd = true;
41729     } else
41730       SetCC = SetCC.getOperand(0);
41731   }
41732 
41733   switch (SetCC.getOpcode()) {
41734   case X86ISD::SETCC_CARRY:
41735     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
41736     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
41737     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
41738     // truncated to i1 using 'and'.
41739     if (checkAgainstTrue && !truncatedToBoolWithAnd)
41740       break;
41741     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
41742            "Invalid use of SETCC_CARRY!");
41743     LLVM_FALLTHROUGH;
41744   case X86ISD::SETCC:
41745     // Set the condition code or opposite one if necessary.
41746     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
41747     if (needOppositeCond)
41748       CC = X86::GetOppositeBranchCondition(CC);
41749     return SetCC.getOperand(1);
41750   case X86ISD::CMOV: {
41751     // Check whether false/true value has canonical one, i.e. 0 or 1.
41752     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
41753     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
41754     // Quit if true value is not a constant.
41755     if (!TVal)
41756       return SDValue();
41757     // Quit if false value is not a constant.
41758     if (!FVal) {
41759       SDValue Op = SetCC.getOperand(0);
41760       // Skip 'zext' or 'trunc' node.
41761       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
41762           Op.getOpcode() == ISD::TRUNCATE)
41763         Op = Op.getOperand(0);
41764       // A special case for rdrand/rdseed, where 0 is set if false cond is
41765       // found.
41766       if ((Op.getOpcode() != X86ISD::RDRAND &&
41767            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
41768         return SDValue();
41769     }
41770     // Quit if false value is not the constant 0 or 1.
41771     bool FValIsFalse = true;
41772     if (FVal && FVal->getZExtValue() != 0) {
41773       if (FVal->getZExtValue() != 1)
41774         return SDValue();
41775       // If FVal is 1, opposite cond is needed.
41776       needOppositeCond = !needOppositeCond;
41777       FValIsFalse = false;
41778     }
41779     // Quit if TVal is not the constant opposite of FVal.
41780     if (FValIsFalse && TVal->getZExtValue() != 1)
41781       return SDValue();
41782     if (!FValIsFalse && TVal->getZExtValue() != 0)
41783       return SDValue();
41784     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
41785     if (needOppositeCond)
41786       CC = X86::GetOppositeBranchCondition(CC);
41787     return SetCC.getOperand(3);
41788   }
41789   }
41790 
41791   return SDValue();
41792 }
41793 
41794 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
41795 /// Match:
41796 ///   (X86or (X86setcc) (X86setcc))
41797 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
41798 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
41799                                            X86::CondCode &CC1, SDValue &Flags,
41800                                            bool &isAnd) {
41801   if (Cond->getOpcode() == X86ISD::CMP) {
41802     if (!isNullConstant(Cond->getOperand(1)))
41803       return false;
41804 
41805     Cond = Cond->getOperand(0);
41806   }
41807 
41808   isAnd = false;
41809 
41810   SDValue SetCC0, SetCC1;
41811   switch (Cond->getOpcode()) {
41812   default: return false;
41813   case ISD::AND:
41814   case X86ISD::AND:
41815     isAnd = true;
41816     LLVM_FALLTHROUGH;
41817   case ISD::OR:
41818   case X86ISD::OR:
41819     SetCC0 = Cond->getOperand(0);
41820     SetCC1 = Cond->getOperand(1);
41821     break;
41822   };
41823 
41824   // Make sure we have SETCC nodes, using the same flags value.
41825   if (SetCC0.getOpcode() != X86ISD::SETCC ||
41826       SetCC1.getOpcode() != X86ISD::SETCC ||
41827       SetCC0->getOperand(1) != SetCC1->getOperand(1))
41828     return false;
41829 
41830   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
41831   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
41832   Flags = SetCC0->getOperand(1);
41833   return true;
41834 }
41835 
41836 // When legalizing carry, we create carries via add X, -1
41837 // If that comes from an actual carry, via setcc, we use the
41838 // carry directly.
41839 static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
41840   if (EFLAGS.getOpcode() == X86ISD::ADD) {
41841     if (isAllOnesConstant(EFLAGS.getOperand(1))) {
41842       SDValue Carry = EFLAGS.getOperand(0);
41843       while (Carry.getOpcode() == ISD::TRUNCATE ||
41844              Carry.getOpcode() == ISD::ZERO_EXTEND ||
41845              Carry.getOpcode() == ISD::SIGN_EXTEND ||
41846              Carry.getOpcode() == ISD::ANY_EXTEND ||
41847              (Carry.getOpcode() == ISD::AND &&
41848               isOneConstant(Carry.getOperand(1))))
41849         Carry = Carry.getOperand(0);
41850       if (Carry.getOpcode() == X86ISD::SETCC ||
41851           Carry.getOpcode() == X86ISD::SETCC_CARRY) {
41852         // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
41853         uint64_t CarryCC = Carry.getConstantOperandVal(0);
41854         SDValue CarryOp1 = Carry.getOperand(1);
41855         if (CarryCC == X86::COND_B)
41856           return CarryOp1;
41857         if (CarryCC == X86::COND_A) {
41858           // Try to convert COND_A into COND_B in an attempt to facilitate
41859           // materializing "setb reg".
41860           //
41861           // Do not flip "e > c", where "c" is a constant, because Cmp
41862           // instruction cannot take an immediate as its first operand.
41863           //
41864           if (CarryOp1.getOpcode() == X86ISD::SUB &&
41865               CarryOp1.getNode()->hasOneUse() &&
41866               CarryOp1.getValueType().isInteger() &&
41867               !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
41868             SDValue SubCommute =
41869                 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
41870                             CarryOp1.getOperand(1), CarryOp1.getOperand(0));
41871             return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
41872           }
41873         }
41874         // If this is a check of the z flag of an add with 1, switch to the
41875         // C flag.
41876         if (CarryCC == X86::COND_E &&
41877             CarryOp1.getOpcode() == X86ISD::ADD &&
41878             isOneConstant(CarryOp1.getOperand(1)))
41879           return CarryOp1;
41880       }
41881     }
41882   }
41883 
41884   return SDValue();
41885 }
41886 
41887 /// If we are inverting an PTEST/TESTP operand, attempt to adjust the CC
41888 /// to avoid the inversion.
41889 static SDValue combinePTESTCC(SDValue EFLAGS, X86::CondCode &CC,
41890                               SelectionDAG &DAG,
41891                               const X86Subtarget &Subtarget) {
41892   // TODO: Handle X86ISD::KTEST/X86ISD::KORTEST.
41893   if (EFLAGS.getOpcode() != X86ISD::PTEST &&
41894       EFLAGS.getOpcode() != X86ISD::TESTP)
41895     return SDValue();
41896 
41897   // PTEST/TESTP sets EFLAGS as:
41898   // TESTZ: ZF = (Op0 & Op1) == 0
41899   // TESTC: CF = (~Op0 & Op1) == 0
41900   // TESTNZC: ZF == 0 && CF == 0
41901   EVT VT = EFLAGS.getValueType();
41902   SDValue Op0 = EFLAGS.getOperand(0);
41903   SDValue Op1 = EFLAGS.getOperand(1);
41904   EVT OpVT = Op0.getValueType();
41905 
41906   // TEST*(~X,Y) == TEST*(X,Y)
41907   if (SDValue NotOp0 = IsNOT(Op0, DAG)) {
41908     X86::CondCode InvCC;
41909     switch (CC) {
41910     case X86::COND_B:
41911       // testc -> testz.
41912       InvCC = X86::COND_E;
41913       break;
41914     case X86::COND_AE:
41915       // !testc -> !testz.
41916       InvCC = X86::COND_NE;
41917       break;
41918     case X86::COND_E:
41919       // testz -> testc.
41920       InvCC = X86::COND_B;
41921       break;
41922     case X86::COND_NE:
41923       // !testz -> !testc.
41924       InvCC = X86::COND_AE;
41925       break;
41926     case X86::COND_A:
41927     case X86::COND_BE:
41928       // testnzc -> testnzc (no change).
41929       InvCC = CC;
41930       break;
41931     default:
41932       InvCC = X86::COND_INVALID;
41933       break;
41934     }
41935 
41936     if (InvCC != X86::COND_INVALID) {
41937       CC = InvCC;
41938       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
41939                          DAG.getBitcast(OpVT, NotOp0), Op1);
41940     }
41941   }
41942 
41943   if (CC == X86::COND_E || CC == X86::COND_NE) {
41944     // TESTZ(X,~Y) == TESTC(Y,X)
41945     if (SDValue NotOp1 = IsNOT(Op1, DAG)) {
41946       CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
41947       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
41948                          DAG.getBitcast(OpVT, NotOp1), Op0);
41949     }
41950 
41951     if (Op0 == Op1) {
41952       SDValue BC = peekThroughBitcasts(Op0);
41953       EVT BCVT = BC.getValueType();
41954       assert(BCVT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(BCVT) &&
41955              "Unexpected vector type");
41956 
41957       // TESTZ(AND(X,Y),AND(X,Y)) == TESTZ(X,Y)
41958       if (BC.getOpcode() == ISD::AND || BC.getOpcode() == X86ISD::FAND) {
41959         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
41960                            DAG.getBitcast(OpVT, BC.getOperand(0)),
41961                            DAG.getBitcast(OpVT, BC.getOperand(1)));
41962       }
41963 
41964       // TESTZ(AND(~X,Y),AND(~X,Y)) == TESTC(X,Y)
41965       if (BC.getOpcode() == X86ISD::ANDNP || BC.getOpcode() == X86ISD::FANDN) {
41966         CC = (CC == X86::COND_E ? X86::COND_B : X86::COND_AE);
41967         return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT,
41968                            DAG.getBitcast(OpVT, BC.getOperand(0)),
41969                            DAG.getBitcast(OpVT, BC.getOperand(1)));
41970       }
41971 
41972       // If every element is an all-sign value, see if we can use MOVMSK to
41973       // more efficiently extract the sign bits and compare that.
41974       // TODO: Handle TESTC with comparison inversion.
41975       // TODO: Can we remove SimplifyMultipleUseDemandedBits and rely on
41976       // MOVMSK combines to make sure its never worse than PTEST?
41977       unsigned EltBits = BCVT.getScalarSizeInBits();
41978       if (DAG.ComputeNumSignBits(BC) == EltBits) {
41979         assert(VT == MVT::i32 && "Expected i32 EFLAGS comparison result");
41980         APInt SignMask = APInt::getSignMask(EltBits);
41981         const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41982         if (SDValue Res =
41983                 TLI.SimplifyMultipleUseDemandedBits(BC, SignMask, DAG)) {
41984           // For vXi16 cases we need to use pmovmksb and extract every other
41985           // sign bit.
41986           SDLoc DL(EFLAGS);
41987           if (EltBits == 16) {
41988             MVT MovmskVT = BCVT.is128BitVector() ? MVT::v16i8 : MVT::v32i8;
41989             Res = DAG.getBitcast(MovmskVT, Res);
41990             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
41991             Res = DAG.getNode(ISD::AND, DL, MVT::i32, Res,
41992                               DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
41993           } else {
41994             Res = getPMOVMSKB(DL, Res, DAG, Subtarget);
41995           }
41996           return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Res,
41997                              DAG.getConstant(0, DL, MVT::i32));
41998         }
41999       }
42000     }
42001 
42002     // TESTZ(-1,X) == TESTZ(X,X)
42003     if (ISD::isBuildVectorAllOnes(Op0.getNode()))
42004       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op1, Op1);
42005 
42006     // TESTZ(X,-1) == TESTZ(X,X)
42007     if (ISD::isBuildVectorAllOnes(Op1.getNode()))
42008       return DAG.getNode(EFLAGS.getOpcode(), SDLoc(EFLAGS), VT, Op0, Op0);
42009   }
42010 
42011   return SDValue();
42012 }
42013 
42014 // Attempt to simplify the MOVMSK input based on the comparison type.
42015 static SDValue combineSetCCMOVMSK(SDValue EFLAGS, X86::CondCode &CC,
42016                                   SelectionDAG &DAG,
42017                                   const X86Subtarget &Subtarget) {
42018   // Handle eq/ne against zero (any_of).
42019   // Handle eq/ne against -1 (all_of).
42020   if (!(CC == X86::COND_E || CC == X86::COND_NE))
42021     return SDValue();
42022   if (EFLAGS.getValueType() != MVT::i32)
42023     return SDValue();
42024   unsigned CmpOpcode = EFLAGS.getOpcode();
42025   if (CmpOpcode != X86ISD::CMP && CmpOpcode != X86ISD::SUB)
42026     return SDValue();
42027   auto *CmpConstant = dyn_cast<ConstantSDNode>(EFLAGS.getOperand(1));
42028   if (!CmpConstant)
42029     return SDValue();
42030   const APInt &CmpVal = CmpConstant->getAPIntValue();
42031 
42032   SDValue CmpOp = EFLAGS.getOperand(0);
42033   unsigned CmpBits = CmpOp.getValueSizeInBits();
42034   assert(CmpBits == CmpVal.getBitWidth() && "Value size mismatch");
42035 
42036   // Peek through any truncate.
42037   if (CmpOp.getOpcode() == ISD::TRUNCATE)
42038     CmpOp = CmpOp.getOperand(0);
42039 
42040   // Bail if we don't find a MOVMSK.
42041   if (CmpOp.getOpcode() != X86ISD::MOVMSK)
42042     return SDValue();
42043 
42044   SDValue Vec = CmpOp.getOperand(0);
42045   MVT VecVT = Vec.getSimpleValueType();
42046   assert((VecVT.is128BitVector() || VecVT.is256BitVector()) &&
42047          "Unexpected MOVMSK operand");
42048   unsigned NumElts = VecVT.getVectorNumElements();
42049   unsigned NumEltBits = VecVT.getScalarSizeInBits();
42050 
42051   bool IsAnyOf = CmpOpcode == X86ISD::CMP && CmpVal.isNullValue();
42052   bool IsAllOf = CmpOpcode == X86ISD::SUB && NumElts <= CmpBits &&
42053                  CmpVal.isMask(NumElts);
42054   if (!IsAnyOf && !IsAllOf)
42055     return SDValue();
42056 
42057   // See if we can peek through to a vector with a wider element type, if the
42058   // signbits extend down to all the sub-elements as well.
42059   // Calling MOVMSK with the wider type, avoiding the bitcast, helps expose
42060   // potential SimplifyDemandedBits/Elts cases.
42061   if (Vec.getOpcode() == ISD::BITCAST) {
42062     SDValue BC = peekThroughBitcasts(Vec);
42063     MVT BCVT = BC.getSimpleValueType();
42064     unsigned BCNumElts = BCVT.getVectorNumElements();
42065     unsigned BCNumEltBits = BCVT.getScalarSizeInBits();
42066     if ((BCNumEltBits == 32 || BCNumEltBits == 64) &&
42067         BCNumEltBits > NumEltBits &&
42068         DAG.ComputeNumSignBits(BC) > (BCNumEltBits - NumEltBits)) {
42069       SDLoc DL(EFLAGS);
42070       unsigned CmpMask = IsAnyOf ? 0 : ((1 << BCNumElts) - 1);
42071       return DAG.getNode(X86ISD::CMP, DL, MVT::i32,
42072                          DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, BC),
42073                          DAG.getConstant(CmpMask, DL, MVT::i32));
42074     }
42075   }
42076 
42077   // MOVMSK(PCMPEQ(X,0)) == -1 -> PTESTZ(X,X).
42078   // MOVMSK(PCMPEQ(X,0)) != -1 -> !PTESTZ(X,X).
42079   if (IsAllOf && Subtarget.hasSSE41()) {
42080     SDValue BC = peekThroughBitcasts(Vec);
42081     if (BC.getOpcode() == X86ISD::PCMPEQ &&
42082         ISD::isBuildVectorAllZeros(BC.getOperand(1).getNode())) {
42083       MVT TestVT = VecVT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
42084       SDValue V = DAG.getBitcast(TestVT, BC.getOperand(0));
42085       return DAG.getNode(X86ISD::PTEST, SDLoc(EFLAGS), MVT::i32, V, V);
42086     }
42087   }
42088 
42089   // See if we can avoid a PACKSS by calling MOVMSK on the sources.
42090   // For vXi16 cases we can use a v2Xi8 PMOVMSKB. We must mask out
42091   // sign bits prior to the comparison with zero unless we know that
42092   // the vXi16 splats the sign bit down to the lower i8 half.
42093   // TODO: Handle all_of patterns.
42094   if (Vec.getOpcode() == X86ISD::PACKSS && VecVT == MVT::v16i8) {
42095     SDValue VecOp0 = Vec.getOperand(0);
42096     SDValue VecOp1 = Vec.getOperand(1);
42097     bool SignExt0 = DAG.ComputeNumSignBits(VecOp0) > 8;
42098     bool SignExt1 = DAG.ComputeNumSignBits(VecOp1) > 8;
42099     // PMOVMSKB(PACKSSBW(X, undef)) -> PMOVMSKB(BITCAST_v16i8(X)) & 0xAAAA.
42100     if (IsAnyOf && CmpBits == 8 && VecOp1.isUndef()) {
42101       SDLoc DL(EFLAGS);
42102       SDValue Result = DAG.getBitcast(MVT::v16i8, VecOp0);
42103       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42104       Result = DAG.getZExtOrTrunc(Result, DL, MVT::i16);
42105       if (!SignExt0) {
42106         Result = DAG.getNode(ISD::AND, DL, MVT::i16, Result,
42107                              DAG.getConstant(0xAAAA, DL, MVT::i16));
42108       }
42109       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
42110                          DAG.getConstant(0, DL, MVT::i16));
42111     }
42112     // PMOVMSKB(PACKSSBW(LO(X), HI(X)))
42113     // -> PMOVMSKB(BITCAST_v32i8(X)) & 0xAAAAAAAA.
42114     if (CmpBits == 16 && Subtarget.hasInt256() &&
42115         VecOp0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42116         VecOp1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
42117         VecOp0.getOperand(0) == VecOp1.getOperand(0) &&
42118         VecOp0.getConstantOperandAPInt(1) == 0 &&
42119         VecOp1.getConstantOperandAPInt(1) == 8 &&
42120         (IsAnyOf || (SignExt0 && SignExt1))) {
42121       SDLoc DL(EFLAGS);
42122       SDValue Result = DAG.getBitcast(MVT::v32i8, VecOp0.getOperand(0));
42123       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42124       unsigned CmpMask = IsAnyOf ? 0 : 0xFFFFFFFF;
42125       if (!SignExt0 || !SignExt1) {
42126         assert(IsAnyOf && "Only perform v16i16 signmasks for any_of patterns");
42127         Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
42128                              DAG.getConstant(0xAAAAAAAA, DL, MVT::i32));
42129       }
42130       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
42131                          DAG.getConstant(CmpMask, DL, MVT::i32));
42132     }
42133   }
42134 
42135   // MOVMSK(SHUFFLE(X,u)) -> MOVMSK(X) iff every element is referenced.
42136   SmallVector<int, 32> ShuffleMask;
42137   SmallVector<SDValue, 2> ShuffleInputs;
42138   if (NumElts == CmpBits &&
42139       getTargetShuffleInputs(peekThroughBitcasts(Vec), ShuffleInputs,
42140                              ShuffleMask, DAG) &&
42141       ShuffleInputs.size() == 1 && !isAnyZeroOrUndef(ShuffleMask) &&
42142       ShuffleInputs[0].getValueSizeInBits() == VecVT.getSizeInBits()) {
42143     unsigned NumShuffleElts = ShuffleMask.size();
42144     APInt DemandedElts = APInt::getNullValue(NumShuffleElts);
42145     for (int M : ShuffleMask) {
42146       assert(0 <= M && M < (int)NumShuffleElts && "Bad unary shuffle index");
42147       DemandedElts.setBit(M);
42148     }
42149     if (DemandedElts.isAllOnesValue()) {
42150       SDLoc DL(EFLAGS);
42151       SDValue Result = DAG.getBitcast(VecVT, ShuffleInputs[0]);
42152       Result = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
42153       Result =
42154           DAG.getZExtOrTrunc(Result, DL, EFLAGS.getOperand(0).getValueType());
42155       return DAG.getNode(X86ISD::CMP, DL, MVT::i32, Result,
42156                          EFLAGS.getOperand(1));
42157     }
42158   }
42159 
42160   return SDValue();
42161 }
42162 
42163 /// Optimize an EFLAGS definition used according to the condition code \p CC
42164 /// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
42165 /// uses of chain values.
42166 static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
42167                                   SelectionDAG &DAG,
42168                                   const X86Subtarget &Subtarget) {
42169   if (CC == X86::COND_B)
42170     if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
42171       return Flags;
42172 
42173   if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
42174     return R;
42175 
42176   if (SDValue R = combinePTESTCC(EFLAGS, CC, DAG, Subtarget))
42177     return R;
42178 
42179   if (SDValue R = combineSetCCMOVMSK(EFLAGS, CC, DAG, Subtarget))
42180     return R;
42181 
42182   return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
42183 }
42184 
42185 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
42186 static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
42187                            TargetLowering::DAGCombinerInfo &DCI,
42188                            const X86Subtarget &Subtarget) {
42189   SDLoc DL(N);
42190 
42191   SDValue FalseOp = N->getOperand(0);
42192   SDValue TrueOp = N->getOperand(1);
42193   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
42194   SDValue Cond = N->getOperand(3);
42195 
42196   // cmov X, X, ?, ? --> X
42197   if (TrueOp == FalseOp)
42198     return TrueOp;
42199 
42200   // Try to simplify the EFLAGS and condition code operands.
42201   // We can't always do this as FCMOV only supports a subset of X86 cond.
42202   if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
42203     if (!(FalseOp.getValueType() == MVT::f80 ||
42204           (FalseOp.getValueType() == MVT::f64 && !Subtarget.hasSSE2()) ||
42205           (FalseOp.getValueType() == MVT::f32 && !Subtarget.hasSSE1())) ||
42206         !Subtarget.hasCMov() || hasFPCMov(CC)) {
42207       SDValue Ops[] = {FalseOp, TrueOp, DAG.getTargetConstant(CC, DL, MVT::i8),
42208                        Flags};
42209       return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
42210     }
42211   }
42212 
42213   // If this is a select between two integer constants, try to do some
42214   // optimizations.  Note that the operands are ordered the opposite of SELECT
42215   // operands.
42216   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
42217     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
42218       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
42219       // larger than FalseC (the false value).
42220       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
42221         CC = X86::GetOppositeBranchCondition(CC);
42222         std::swap(TrueC, FalseC);
42223         std::swap(TrueOp, FalseOp);
42224       }
42225 
42226       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
42227       // This is efficient for any integer data type (including i8/i16) and
42228       // shift amount.
42229       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
42230         Cond = getSETCC(CC, Cond, DL, DAG);
42231 
42232         // Zero extend the condition if needed.
42233         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
42234 
42235         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
42236         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
42237                            DAG.getConstant(ShAmt, DL, MVT::i8));
42238         return Cond;
42239       }
42240 
42241       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
42242       // for any integer data type, including i8/i16.
42243       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
42244         Cond = getSETCC(CC, Cond, DL, DAG);
42245 
42246         // Zero extend the condition if needed.
42247         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
42248                            FalseC->getValueType(0), Cond);
42249         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
42250                            SDValue(FalseC, 0));
42251         return Cond;
42252       }
42253 
42254       // Optimize cases that will turn into an LEA instruction.  This requires
42255       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
42256       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
42257         APInt Diff = TrueC->getAPIntValue() - FalseC->getAPIntValue();
42258         assert(Diff.getBitWidth() == N->getValueType(0).getSizeInBits() &&
42259                "Implicit constant truncation");
42260 
42261         bool isFastMultiplier = false;
42262         if (Diff.ult(10)) {
42263           switch (Diff.getZExtValue()) {
42264           default: break;
42265           case 1:  // result = add base, cond
42266           case 2:  // result = lea base(    , cond*2)
42267           case 3:  // result = lea base(cond, cond*2)
42268           case 4:  // result = lea base(    , cond*4)
42269           case 5:  // result = lea base(cond, cond*4)
42270           case 8:  // result = lea base(    , cond*8)
42271           case 9:  // result = lea base(cond, cond*8)
42272             isFastMultiplier = true;
42273             break;
42274           }
42275         }
42276 
42277         if (isFastMultiplier) {
42278           Cond = getSETCC(CC, Cond, DL ,DAG);
42279           // Zero extend the condition if needed.
42280           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
42281                              Cond);
42282           // Scale the condition by the difference.
42283           if (Diff != 1)
42284             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
42285                                DAG.getConstant(Diff, DL, Cond.getValueType()));
42286 
42287           // Add the base if non-zero.
42288           if (FalseC->getAPIntValue() != 0)
42289             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
42290                                SDValue(FalseC, 0));
42291           return Cond;
42292         }
42293       }
42294     }
42295   }
42296 
42297   // Handle these cases:
42298   //   (select (x != c), e, c) -> select (x != c), e, x),
42299   //   (select (x == c), c, e) -> select (x == c), x, e)
42300   // where the c is an integer constant, and the "select" is the combination
42301   // of CMOV and CMP.
42302   //
42303   // The rationale for this change is that the conditional-move from a constant
42304   // needs two instructions, however, conditional-move from a register needs
42305   // only one instruction.
42306   //
42307   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
42308   //  some instruction-combining opportunities. This opt needs to be
42309   //  postponed as late as possible.
42310   //
42311   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
42312     // the DCI.xxxx conditions are provided to postpone the optimization as
42313     // late as possible.
42314 
42315     ConstantSDNode *CmpAgainst = nullptr;
42316     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
42317         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
42318         !isa<ConstantSDNode>(Cond.getOperand(0))) {
42319 
42320       if (CC == X86::COND_NE &&
42321           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
42322         CC = X86::GetOppositeBranchCondition(CC);
42323         std::swap(TrueOp, FalseOp);
42324       }
42325 
42326       if (CC == X86::COND_E &&
42327           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
42328         SDValue Ops[] = {FalseOp, Cond.getOperand(0),
42329                          DAG.getTargetConstant(CC, DL, MVT::i8), Cond};
42330         return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
42331       }
42332     }
42333   }
42334 
42335   // Fold and/or of setcc's to double CMOV:
42336   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
42337   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
42338   //
42339   // This combine lets us generate:
42340   //   cmovcc1 (jcc1 if we don't have CMOV)
42341   //   cmovcc2 (same)
42342   // instead of:
42343   //   setcc1
42344   //   setcc2
42345   //   and/or
42346   //   cmovne (jne if we don't have CMOV)
42347   // When we can't use the CMOV instruction, it might increase branch
42348   // mispredicts.
42349   // When we can use CMOV, or when there is no mispredict, this improves
42350   // throughput and reduces register pressure.
42351   //
42352   if (CC == X86::COND_NE) {
42353     SDValue Flags;
42354     X86::CondCode CC0, CC1;
42355     bool isAndSetCC;
42356     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
42357       if (isAndSetCC) {
42358         std::swap(FalseOp, TrueOp);
42359         CC0 = X86::GetOppositeBranchCondition(CC0);
42360         CC1 = X86::GetOppositeBranchCondition(CC1);
42361       }
42362 
42363       SDValue LOps[] = {FalseOp, TrueOp,
42364                         DAG.getTargetConstant(CC0, DL, MVT::i8), Flags};
42365       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
42366       SDValue Ops[] = {LCMOV, TrueOp, DAG.getTargetConstant(CC1, DL, MVT::i8),
42367                        Flags};
42368       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
42369       return CMOV;
42370     }
42371   }
42372 
42373   // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
42374   //      (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
42375   // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
42376   //    (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
42377   if ((CC == X86::COND_NE || CC == X86::COND_E) &&
42378       Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
42379     SDValue Add = TrueOp;
42380     SDValue Const = FalseOp;
42381     // Canonicalize the condition code for easier matching and output.
42382     if (CC == X86::COND_E)
42383       std::swap(Add, Const);
42384 
42385     // We might have replaced the constant in the cmov with the LHS of the
42386     // compare. If so change it to the RHS of the compare.
42387     if (Const == Cond.getOperand(0))
42388       Const = Cond.getOperand(1);
42389 
42390     // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
42391     if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
42392         Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
42393         (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
42394          Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
42395         Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
42396       EVT VT = N->getValueType(0);
42397       // This should constant fold.
42398       SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
42399       SDValue CMov =
42400           DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
42401                       DAG.getTargetConstant(X86::COND_NE, DL, MVT::i8), Cond);
42402       return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
42403     }
42404   }
42405 
42406   return SDValue();
42407 }
42408 
42409 /// Different mul shrinking modes.
42410 enum class ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
42411 
42412 static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
42413   EVT VT = N->getOperand(0).getValueType();
42414   if (VT.getScalarSizeInBits() != 32)
42415     return false;
42416 
42417   assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2");
42418   unsigned SignBits[2] = {1, 1};
42419   bool IsPositive[2] = {false, false};
42420   for (unsigned i = 0; i < 2; i++) {
42421     SDValue Opd = N->getOperand(i);
42422 
42423     SignBits[i] = DAG.ComputeNumSignBits(Opd);
42424     IsPositive[i] = DAG.SignBitIsZero(Opd);
42425   }
42426 
42427   bool AllPositive = IsPositive[0] && IsPositive[1];
42428   unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
42429   // When ranges are from -128 ~ 127, use MULS8 mode.
42430   if (MinSignBits >= 25)
42431     Mode = ShrinkMode::MULS8;
42432   // When ranges are from 0 ~ 255, use MULU8 mode.
42433   else if (AllPositive && MinSignBits >= 24)
42434     Mode = ShrinkMode::MULU8;
42435   // When ranges are from -32768 ~ 32767, use MULS16 mode.
42436   else if (MinSignBits >= 17)
42437     Mode = ShrinkMode::MULS16;
42438   // When ranges are from 0 ~ 65535, use MULU16 mode.
42439   else if (AllPositive && MinSignBits >= 16)
42440     Mode = ShrinkMode::MULU16;
42441   else
42442     return false;
42443   return true;
42444 }
42445 
42446 /// When the operands of vector mul are extended from smaller size values,
42447 /// like i8 and i16, the type of mul may be shrinked to generate more
42448 /// efficient code. Two typical patterns are handled:
42449 /// Pattern1:
42450 ///     %2 = sext/zext <N x i8> %1 to <N x i32>
42451 ///     %4 = sext/zext <N x i8> %3 to <N x i32>
42452 //   or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
42453 ///     %5 = mul <N x i32> %2, %4
42454 ///
42455 /// Pattern2:
42456 ///     %2 = zext/sext <N x i16> %1 to <N x i32>
42457 ///     %4 = zext/sext <N x i16> %3 to <N x i32>
42458 ///  or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
42459 ///     %5 = mul <N x i32> %2, %4
42460 ///
42461 /// There are four mul shrinking modes:
42462 /// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
42463 /// -128 to 128, and the scalar value range of %4 is also -128 to 128,
42464 /// generate pmullw+sext32 for it (MULS8 mode).
42465 /// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
42466 /// 0 to 255, and the scalar value range of %4 is also 0 to 255,
42467 /// generate pmullw+zext32 for it (MULU8 mode).
42468 /// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
42469 /// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
42470 /// generate pmullw+pmulhw for it (MULS16 mode).
42471 /// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
42472 /// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
42473 /// generate pmullw+pmulhuw for it (MULU16 mode).
42474 static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
42475                                const X86Subtarget &Subtarget) {
42476   // Check for legality
42477   // pmullw/pmulhw are not supported by SSE.
42478   if (!Subtarget.hasSSE2())
42479     return SDValue();
42480 
42481   // Check for profitability
42482   // pmulld is supported since SSE41. It is better to use pmulld
42483   // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
42484   // the expansion.
42485   bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
42486   if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
42487     return SDValue();
42488 
42489   ShrinkMode Mode;
42490   if (!canReduceVMulWidth(N, DAG, Mode))
42491     return SDValue();
42492 
42493   SDLoc DL(N);
42494   SDValue N0 = N->getOperand(0);
42495   SDValue N1 = N->getOperand(1);
42496   EVT VT = N->getOperand(0).getValueType();
42497   unsigned NumElts = VT.getVectorNumElements();
42498   if ((NumElts % 2) != 0)
42499     return SDValue();
42500 
42501   EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
42502 
42503   // Shrink the operands of mul.
42504   SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
42505   SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
42506 
42507   // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
42508   // lower part is needed.
42509   SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
42510   if (Mode == ShrinkMode::MULU8 || Mode == ShrinkMode::MULS8)
42511     return DAG.getNode((Mode == ShrinkMode::MULU8) ? ISD::ZERO_EXTEND
42512                                                    : ISD::SIGN_EXTEND,
42513                        DL, VT, MulLo);
42514 
42515   EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts / 2);
42516   // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
42517   // the higher part is also needed.
42518   SDValue MulHi =
42519       DAG.getNode(Mode == ShrinkMode::MULS16 ? ISD::MULHS : ISD::MULHU, DL,
42520                   ReducedVT, NewN0, NewN1);
42521 
42522   // Repack the lower part and higher part result of mul into a wider
42523   // result.
42524   // Generate shuffle functioning as punpcklwd.
42525   SmallVector<int, 16> ShuffleMask(NumElts);
42526   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
42527     ShuffleMask[2 * i] = i;
42528     ShuffleMask[2 * i + 1] = i + NumElts;
42529   }
42530   SDValue ResLo =
42531       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
42532   ResLo = DAG.getBitcast(ResVT, ResLo);
42533   // Generate shuffle functioning as punpckhwd.
42534   for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
42535     ShuffleMask[2 * i] = i + NumElts / 2;
42536     ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
42537   }
42538   SDValue ResHi =
42539       DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
42540   ResHi = DAG.getBitcast(ResVT, ResHi);
42541   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
42542 }
42543 
42544 static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
42545                                  EVT VT, const SDLoc &DL) {
42546 
42547   auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
42548     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
42549                                  DAG.getConstant(Mult, DL, VT));
42550     Result = DAG.getNode(ISD::SHL, DL, VT, Result,
42551                          DAG.getConstant(Shift, DL, MVT::i8));
42552     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
42553                          N->getOperand(0));
42554     return Result;
42555   };
42556 
42557   auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
42558     SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
42559                                  DAG.getConstant(Mul1, DL, VT));
42560     Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
42561                          DAG.getConstant(Mul2, DL, VT));
42562     Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
42563                          N->getOperand(0));
42564     return Result;
42565   };
42566 
42567   switch (MulAmt) {
42568   default:
42569     break;
42570   case 11:
42571     // mul x, 11 => add ((shl (mul x, 5), 1), x)
42572     return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
42573   case 21:
42574     // mul x, 21 => add ((shl (mul x, 5), 2), x)
42575     return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
42576   case 41:
42577     // mul x, 41 => add ((shl (mul x, 5), 3), x)
42578     return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
42579   case 22:
42580     // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
42581     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
42582                        combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
42583   case 19:
42584     // mul x, 19 => add ((shl (mul x, 9), 1), x)
42585     return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
42586   case 37:
42587     // mul x, 37 => add ((shl (mul x, 9), 2), x)
42588     return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
42589   case 73:
42590     // mul x, 73 => add ((shl (mul x, 9), 3), x)
42591     return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
42592   case 13:
42593     // mul x, 13 => add ((shl (mul x, 3), 2), x)
42594     return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
42595   case 23:
42596     // mul x, 23 => sub ((shl (mul x, 3), 3), x)
42597     return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
42598   case 26:
42599     // mul x, 26 => add ((mul (mul x, 5), 5), x)
42600     return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
42601   case 28:
42602     // mul x, 28 => add ((mul (mul x, 9), 3), x)
42603     return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
42604   case 29:
42605     // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
42606     return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
42607                        combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
42608   }
42609 
42610   // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
42611   // by a single LEA.
42612   // First check if this a sum of two power of 2s because that's easy. Then
42613   // count how many zeros are up to the first bit.
42614   // TODO: We can do this even without LEA at a cost of two shifts and an add.
42615   if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
42616     unsigned ScaleShift = countTrailingZeros(MulAmt);
42617     if (ScaleShift >= 1 && ScaleShift < 4) {
42618       unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
42619       SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42620                                    DAG.getConstant(ShiftAmt, DL, MVT::i8));
42621       SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42622                                    DAG.getConstant(ScaleShift, DL, MVT::i8));
42623       return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
42624     }
42625   }
42626 
42627   return SDValue();
42628 }
42629 
42630 // If the upper 17 bits of each element are zero then we can use PMADDWD,
42631 // which is always at least as quick as PMULLD, except on KNL.
42632 static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
42633                                    const X86Subtarget &Subtarget) {
42634   if (!Subtarget.hasSSE2())
42635     return SDValue();
42636 
42637   if (Subtarget.isPMADDWDSlow())
42638     return SDValue();
42639 
42640   EVT VT = N->getValueType(0);
42641 
42642   // Only support vXi32 vectors.
42643   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
42644     return SDValue();
42645 
42646   // Make sure the type is legal or will be widened to a legal type.
42647   if (VT != MVT::v2i32 && !DAG.getTargetLoweringInfo().isTypeLegal(VT))
42648     return SDValue();
42649 
42650   MVT WVT = MVT::getVectorVT(MVT::i16, 2 * VT.getVectorNumElements());
42651 
42652   // Without BWI, we would need to split v32i16.
42653   if (WVT == MVT::v32i16 && !Subtarget.hasBWI())
42654     return SDValue();
42655 
42656   SDValue N0 = N->getOperand(0);
42657   SDValue N1 = N->getOperand(1);
42658 
42659   // If we are zero extending two steps without SSE4.1, its better to reduce
42660   // the vmul width instead.
42661   if (!Subtarget.hasSSE41() &&
42662       (N0.getOpcode() == ISD::ZERO_EXTEND &&
42663        N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
42664       (N1.getOpcode() == ISD::ZERO_EXTEND &&
42665        N1.getOperand(0).getScalarValueSizeInBits() <= 8))
42666     return SDValue();
42667 
42668   APInt Mask17 = APInt::getHighBitsSet(32, 17);
42669   if (!DAG.MaskedValueIsZero(N1, Mask17) ||
42670       !DAG.MaskedValueIsZero(N0, Mask17))
42671     return SDValue();
42672 
42673   // Use SplitOpsAndApply to handle AVX splitting.
42674   auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42675                            ArrayRef<SDValue> Ops) {
42676     MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
42677     return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
42678   };
42679   return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
42680                           { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
42681                           PMADDWDBuilder);
42682 }
42683 
42684 static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
42685                                   const X86Subtarget &Subtarget) {
42686   if (!Subtarget.hasSSE2())
42687     return SDValue();
42688 
42689   EVT VT = N->getValueType(0);
42690 
42691   // Only support vXi64 vectors.
42692   if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
42693       VT.getVectorNumElements() < 2 ||
42694       !isPowerOf2_32(VT.getVectorNumElements()))
42695     return SDValue();
42696 
42697   SDValue N0 = N->getOperand(0);
42698   SDValue N1 = N->getOperand(1);
42699 
42700   // MULDQ returns the 64-bit result of the signed multiplication of the lower
42701   // 32-bits. We can lower with this if the sign bits stretch that far.
42702   if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
42703       DAG.ComputeNumSignBits(N1) > 32) {
42704     auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42705                             ArrayRef<SDValue> Ops) {
42706       return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
42707     };
42708     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
42709                             PMULDQBuilder, /*CheckBWI*/false);
42710   }
42711 
42712   // If the upper bits are zero we can use a single pmuludq.
42713   APInt Mask = APInt::getHighBitsSet(64, 32);
42714   if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
42715     auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42716                              ArrayRef<SDValue> Ops) {
42717       return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
42718     };
42719     return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
42720                             PMULUDQBuilder, /*CheckBWI*/false);
42721   }
42722 
42723   return SDValue();
42724 }
42725 
42726 /// Optimize a single multiply with constant into two operations in order to
42727 /// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
42728 static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
42729                           TargetLowering::DAGCombinerInfo &DCI,
42730                           const X86Subtarget &Subtarget) {
42731   EVT VT = N->getValueType(0);
42732 
42733   if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
42734     return V;
42735 
42736   if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
42737     return V;
42738 
42739   if (DCI.isBeforeLegalize() && VT.isVector())
42740     return reduceVMULWidth(N, DAG, Subtarget);
42741 
42742   if (!MulConstantOptimization)
42743     return SDValue();
42744   // An imul is usually smaller than the alternative sequence.
42745   if (DAG.getMachineFunction().getFunction().hasMinSize())
42746     return SDValue();
42747 
42748   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
42749     return SDValue();
42750 
42751   if (VT != MVT::i64 && VT != MVT::i32)
42752     return SDValue();
42753 
42754   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
42755   if (!C)
42756     return SDValue();
42757   if (isPowerOf2_64(C->getZExtValue()))
42758     return SDValue();
42759 
42760   int64_t SignMulAmt = C->getSExtValue();
42761   assert(SignMulAmt != INT64_MIN && "Int min should have been handled!");
42762   uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
42763 
42764   SDLoc DL(N);
42765   if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
42766     SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
42767                                  DAG.getConstant(AbsMulAmt, DL, VT));
42768     if (SignMulAmt < 0)
42769       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
42770                            NewMul);
42771 
42772     return NewMul;
42773   }
42774 
42775   uint64_t MulAmt1 = 0;
42776   uint64_t MulAmt2 = 0;
42777   if ((AbsMulAmt % 9) == 0) {
42778     MulAmt1 = 9;
42779     MulAmt2 = AbsMulAmt / 9;
42780   } else if ((AbsMulAmt % 5) == 0) {
42781     MulAmt1 = 5;
42782     MulAmt2 = AbsMulAmt / 5;
42783   } else if ((AbsMulAmt % 3) == 0) {
42784     MulAmt1 = 3;
42785     MulAmt2 = AbsMulAmt / 3;
42786   }
42787 
42788   SDValue NewMul;
42789   // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
42790   if (MulAmt2 &&
42791       (isPowerOf2_64(MulAmt2) ||
42792        (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
42793 
42794     if (isPowerOf2_64(MulAmt2) &&
42795         !(SignMulAmt >= 0 && N->hasOneUse() &&
42796           N->use_begin()->getOpcode() == ISD::ADD))
42797       // If second multiplifer is pow2, issue it first. We want the multiply by
42798       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
42799       // is an add. Only do this for positive multiply amounts since the
42800       // negate would prevent it from being used as an address mode anyway.
42801       std::swap(MulAmt1, MulAmt2);
42802 
42803     if (isPowerOf2_64(MulAmt1))
42804       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42805                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
42806     else
42807       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
42808                            DAG.getConstant(MulAmt1, DL, VT));
42809 
42810     if (isPowerOf2_64(MulAmt2))
42811       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
42812                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
42813     else
42814       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
42815                            DAG.getConstant(MulAmt2, DL, VT));
42816 
42817     // Negate the result.
42818     if (SignMulAmt < 0)
42819       NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
42820                            NewMul);
42821   } else if (!Subtarget.slowLEA())
42822     NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
42823 
42824   if (!NewMul) {
42825     assert(C->getZExtValue() != 0 &&
42826            C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&
42827            "Both cases that could cause potential overflows should have "
42828            "already been handled.");
42829     if (isPowerOf2_64(AbsMulAmt - 1)) {
42830       // (mul x, 2^N + 1) => (add (shl x, N), x)
42831       NewMul = DAG.getNode(
42832           ISD::ADD, DL, VT, N->getOperand(0),
42833           DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42834                       DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
42835                                       MVT::i8)));
42836       // To negate, subtract the number from zero
42837       if (SignMulAmt < 0)
42838         NewMul = DAG.getNode(ISD::SUB, DL, VT,
42839                              DAG.getConstant(0, DL, VT), NewMul);
42840     } else if (isPowerOf2_64(AbsMulAmt + 1)) {
42841       // (mul x, 2^N - 1) => (sub (shl x, N), x)
42842       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42843                            DAG.getConstant(Log2_64(AbsMulAmt + 1),
42844                                            DL, MVT::i8));
42845       // To negate, reverse the operands of the subtract.
42846       if (SignMulAmt < 0)
42847         NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
42848       else
42849         NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
42850     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
42851       // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
42852       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42853                            DAG.getConstant(Log2_64(AbsMulAmt - 2),
42854                                            DL, MVT::i8));
42855       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
42856       NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
42857     } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
42858       // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
42859       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
42860                            DAG.getConstant(Log2_64(AbsMulAmt + 2),
42861                                            DL, MVT::i8));
42862       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
42863       NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
42864     }
42865   }
42866 
42867   return NewMul;
42868 }
42869 
42870 // Try to form a MULHU or MULHS node by looking for
42871 // (srl (mul ext, ext), 16)
42872 // TODO: This is X86 specific because we want to be able to handle wide types
42873 // before type legalization. But we can only do it if the vector will be
42874 // legalized via widening/splitting. Type legalization can't handle promotion
42875 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
42876 // combiner.
42877 static SDValue combineShiftToPMULH(SDNode *N, SelectionDAG &DAG,
42878                                    const X86Subtarget &Subtarget) {
42879   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
42880            "SRL or SRA node is required here!");
42881   SDLoc DL(N);
42882 
42883   // Only do this with SSE4.1. On earlier targets reduceVMULWidth will expand
42884   // the multiply.
42885   if (!Subtarget.hasSSE41())
42886     return SDValue();
42887 
42888   // The operation feeding into the shift must be a multiply.
42889   SDValue ShiftOperand = N->getOperand(0);
42890   if (ShiftOperand.getOpcode() != ISD::MUL || !ShiftOperand.hasOneUse())
42891     return SDValue();
42892 
42893   // Input type should be at least vXi32.
42894   EVT VT = N->getValueType(0);
42895   if (!VT.isVector() || VT.getVectorElementType().getSizeInBits() < 32)
42896     return SDValue();
42897 
42898   // Need a shift by 16.
42899   APInt ShiftAmt;
42900   if (!ISD::isConstantSplatVector(N->getOperand(1).getNode(), ShiftAmt) ||
42901       ShiftAmt != 16)
42902     return SDValue();
42903 
42904   SDValue LHS = ShiftOperand.getOperand(0);
42905   SDValue RHS = ShiftOperand.getOperand(1);
42906 
42907   unsigned ExtOpc = LHS.getOpcode();
42908   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
42909       RHS.getOpcode() != ExtOpc)
42910     return SDValue();
42911 
42912   // Peek through the extends.
42913   LHS = LHS.getOperand(0);
42914   RHS = RHS.getOperand(0);
42915 
42916   // Ensure the input types match.
42917   EVT MulVT = LHS.getValueType();
42918   if (MulVT.getVectorElementType() != MVT::i16 || RHS.getValueType() != MulVT)
42919     return SDValue();
42920 
42921   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
42922   SDValue Mulh = DAG.getNode(Opc, DL, MulVT, LHS, RHS);
42923 
42924   ExtOpc = N->getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
42925   return DAG.getNode(ExtOpc, DL, VT, Mulh);
42926 }
42927 
42928 static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
42929   SDValue N0 = N->getOperand(0);
42930   SDValue N1 = N->getOperand(1);
42931   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
42932   EVT VT = N0.getValueType();
42933 
42934   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
42935   // since the result of setcc_c is all zero's or all ones.
42936   if (VT.isInteger() && !VT.isVector() &&
42937       N1C && N0.getOpcode() == ISD::AND &&
42938       N0.getOperand(1).getOpcode() == ISD::Constant) {
42939     SDValue N00 = N0.getOperand(0);
42940     APInt Mask = N0.getConstantOperandAPInt(1);
42941     Mask <<= N1C->getAPIntValue();
42942     bool MaskOK = false;
42943     // We can handle cases concerning bit-widening nodes containing setcc_c if
42944     // we carefully interrogate the mask to make sure we are semantics
42945     // preserving.
42946     // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
42947     // of the underlying setcc_c operation if the setcc_c was zero extended.
42948     // Consider the following example:
42949     //   zext(setcc_c)                 -> i32 0x0000FFFF
42950     //   c1                            -> i32 0x0000FFFF
42951     //   c2                            -> i32 0x00000001
42952     //   (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
42953     //   (and setcc_c, (c1 << c2))     -> i32 0x0000FFFE
42954     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
42955       MaskOK = true;
42956     } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
42957                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
42958       MaskOK = true;
42959     } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
42960                 N00.getOpcode() == ISD::ANY_EXTEND) &&
42961                N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
42962       MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
42963     }
42964     if (MaskOK && Mask != 0) {
42965       SDLoc DL(N);
42966       return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
42967     }
42968   }
42969 
42970   // Hardware support for vector shifts is sparse which makes us scalarize the
42971   // vector operations in many cases. Also, on sandybridge ADD is faster than
42972   // shl.
42973   // (shl V, 1) -> add V,V
42974   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
42975     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
42976       assert(N0.getValueType().isVector() && "Invalid vector shift type");
42977       // We shift all of the values by one. In many cases we do not have
42978       // hardware support for this operation. This is better expressed as an ADD
42979       // of two values.
42980       if (N1SplatC->isOne())
42981         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
42982     }
42983 
42984   return SDValue();
42985 }
42986 
42987 static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG,
42988                                            const X86Subtarget &Subtarget) {
42989   SDValue N0 = N->getOperand(0);
42990   SDValue N1 = N->getOperand(1);
42991   EVT VT = N0.getValueType();
42992   unsigned Size = VT.getSizeInBits();
42993 
42994   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
42995     return V;
42996 
42997   // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
42998   // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
42999   // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
43000   // depending on sign of (SarConst - [56,48,32,24,16])
43001 
43002   // sexts in X86 are MOVs. The MOVs have the same code size
43003   // as above SHIFTs (only SHIFT on 1 has lower code size).
43004   // However the MOVs have 2 advantages to a SHIFT:
43005   // 1. MOVs can write to a register that differs from source
43006   // 2. MOVs accept memory operands
43007 
43008   if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
43009       N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
43010       N0.getOperand(1).getOpcode() != ISD::Constant)
43011     return SDValue();
43012 
43013   SDValue N00 = N0.getOperand(0);
43014   SDValue N01 = N0.getOperand(1);
43015   APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
43016   APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
43017   EVT CVT = N1.getValueType();
43018 
43019   if (SarConst.isNegative())
43020     return SDValue();
43021 
43022   for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
43023     unsigned ShiftSize = SVT.getSizeInBits();
43024     // skipping types without corresponding sext/zext and
43025     // ShlConst that is not one of [56,48,32,24,16]
43026     if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
43027       continue;
43028     SDLoc DL(N);
43029     SDValue NN =
43030         DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
43031     SarConst = SarConst - (Size - ShiftSize);
43032     if (SarConst == 0)
43033       return NN;
43034     else if (SarConst.isNegative())
43035       return DAG.getNode(ISD::SHL, DL, VT, NN,
43036                          DAG.getConstant(-SarConst, DL, CVT));
43037     else
43038       return DAG.getNode(ISD::SRA, DL, VT, NN,
43039                          DAG.getConstant(SarConst, DL, CVT));
43040   }
43041   return SDValue();
43042 }
43043 
43044 static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
43045                                         TargetLowering::DAGCombinerInfo &DCI,
43046                                         const X86Subtarget &Subtarget) {
43047   SDValue N0 = N->getOperand(0);
43048   SDValue N1 = N->getOperand(1);
43049   EVT VT = N0.getValueType();
43050 
43051   if (SDValue V = combineShiftToPMULH(N, DAG, Subtarget))
43052     return V;
43053 
43054   // Only do this on the last DAG combine as it can interfere with other
43055   // combines.
43056   if (!DCI.isAfterLegalizeDAG())
43057     return SDValue();
43058 
43059   // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
43060   // TODO: This is a generic DAG combine that became an x86-only combine to
43061   // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
43062   // and-not ('andn').
43063   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
43064     return SDValue();
43065 
43066   auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
43067   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
43068   if (!ShiftC || !AndC)
43069     return SDValue();
43070 
43071   // If we can shrink the constant mask below 8-bits or 32-bits, then this
43072   // transform should reduce code size. It may also enable secondary transforms
43073   // from improved known-bits analysis or instruction selection.
43074   APInt MaskVal = AndC->getAPIntValue();
43075 
43076   // If this can be matched by a zero extend, don't optimize.
43077   if (MaskVal.isMask()) {
43078     unsigned TO = MaskVal.countTrailingOnes();
43079     if (TO >= 8 && isPowerOf2_32(TO))
43080       return SDValue();
43081   }
43082 
43083   APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
43084   unsigned OldMaskSize = MaskVal.getMinSignedBits();
43085   unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
43086   if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
43087       (OldMaskSize > 32 && NewMaskSize <= 32)) {
43088     // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
43089     SDLoc DL(N);
43090     SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
43091     SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
43092     return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
43093   }
43094   return SDValue();
43095 }
43096 
43097 static SDValue combineHorizOpWithShuffle(SDNode *N, SelectionDAG &DAG,
43098                                          const X86Subtarget &Subtarget) {
43099   unsigned Opcode = N->getOpcode();
43100   assert((X86ISD::HADD == Opcode || X86ISD::FHADD == Opcode ||
43101           X86ISD::HSUB == Opcode || X86ISD::FHSUB == Opcode ||
43102           X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
43103          "Unexpected hadd/hsub/pack opcode");
43104 
43105   EVT VT = N->getValueType(0);
43106   SDValue N0 = N->getOperand(0);
43107   SDValue N1 = N->getOperand(1);
43108   EVT SrcVT = N0.getValueType();
43109 
43110   // Attempt to fold HOP(LOSUBVECTOR(SHUFFLE(X)),HISUBVECTOR(SHUFFLE(X)))
43111   // to SHUFFLE(HOP(LOSUBVECTOR(X),HISUBVECTOR(X))), this is mainly for
43112   // truncation trees that help us avoid lane crossing shuffles.
43113   // TODO: There's a lot more we can do for PACK/HADD style shuffle combines.
43114   // TODO: We don't handle vXf64 shuffles yet.
43115   if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
43116       N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
43117       N0.getConstantOperandAPInt(1) == 0 &&
43118       N1.getConstantOperandAPInt(1) == SrcVT.getVectorNumElements() &&
43119       N0.getOperand(0) == N1.getOperand(0) && VT.is128BitVector() &&
43120       N0.getOperand(0).getValueType().is256BitVector() &&
43121       SrcVT.getScalarSizeInBits() <= 32) {
43122     // TODO - support target/faux shuffles.
43123     SDValue Vec = peekThroughBitcasts(N0.getOperand(0));
43124     if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Vec)) {
43125       // To keep the HOP LHS/RHS coherency, we must be able to scale the unary
43126       // shuffle to a vXi64 width - we can probably relax this in the future.
43127       SmallVector<int, 4> ShuffleMask;
43128       if (SVN->getOperand(1).isUndef() &&
43129           scaleShuffleElements(SVN->getMask(), 4, ShuffleMask)) {
43130         SDLoc DL(N);
43131         SDValue Lo, Hi;
43132         MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
43133         std::tie(Lo, Hi) = DAG.SplitVector(SVN->getOperand(0), DL);
43134         Lo = DAG.getBitcast(N0.getValueType(), Lo);
43135         Hi = DAG.getBitcast(N1.getValueType(), Hi);
43136         SDValue Res = DAG.getNode(Opcode, DL, VT, Lo, Hi);
43137         Res = DAG.getBitcast(ShufVT, Res);
43138         Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
43139         return DAG.getBitcast(VT, Res);
43140       }
43141     }
43142   }
43143 
43144   // Attempt to fold HOP(SHUFFLE(X),SHUFFLE(Y)) -> SHUFFLE(HOP(X,Y)).
43145   // TODO: Merge with binary shuffle folds below.
43146   if (VT.is128BitVector() && SrcVT.getScalarSizeInBits() <= 32) {
43147     int PostShuffle[4] = {0, 1, 2, 3};
43148 
43149     // If the op is an unary shuffle that can scale to v2x64,
43150     // then we can perform this as a v4x32 post shuffle.
43151     auto AdjustOp = [&](SDValue V, int Offset) {
43152       auto *SVN = dyn_cast<ShuffleVectorSDNode>(V);
43153       SmallVector<int, 2> ScaledMask;
43154       if (!SVN || !SVN->getOperand(1).isUndef() ||
43155           !scaleShuffleElements(SVN->getMask(), 2, ScaledMask) ||
43156           !N->isOnlyUserOf(V.getNode()))
43157         return SDValue();
43158       PostShuffle[Offset + 0] = ScaledMask[0] < 0 ? -1 : Offset + ScaledMask[0];
43159       PostShuffle[Offset + 1] = ScaledMask[1] < 0 ? -1 : Offset + ScaledMask[1];
43160       return SVN->getOperand(0);
43161     };
43162 
43163     SDValue Src0 = AdjustOp(N0, 0);
43164     SDValue Src1 = AdjustOp(N1, 2);
43165     if (Src0 || Src1) {
43166       Src0 = Src0 ? Src0 : N0;
43167       Src1 = Src1 ? Src1 : N1;
43168       SDLoc DL(N);
43169       MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f32 : MVT::v4i32;
43170       SDValue Res = DAG.getNode(Opcode, DL, VT, Src0, Src1);
43171       Res = DAG.getBitcast(ShufVT, Res);
43172       Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, PostShuffle);
43173       return DAG.getBitcast(VT, Res);
43174     }
43175   }
43176 
43177   // Attempt to fold HOP(SHUFFLE(X,Y),SHUFFLE(X,Y)) -> SHUFFLE(HOP(X,Y)).
43178   // TODO: Relax shuffle scaling to support sub-128-bit subvector shuffles.
43179   if (VT.is256BitVector() && Subtarget.hasInt256()) {
43180     SmallVector<int> Mask0, Mask1;
43181     SmallVector<SDValue> Ops0, Ops1;
43182     if (getTargetShuffleInputs(N0, Ops0, Mask0, DAG) && !isAnyZero(Mask0) &&
43183         getTargetShuffleInputs(N1, Ops1, Mask1, DAG) && !isAnyZero(Mask1) &&
43184         !Ops0.empty() && !Ops1.empty()) {
43185       SDValue Op00 = Ops0.front(), Op01 = Ops0.back();
43186       SDValue Op10 = Ops1.front(), Op11 = Ops1.back();
43187       SmallVector<int, 2> ShuffleMask0, ShuffleMask1;
43188       if (Op00.getValueType() == SrcVT && Op01.getValueType() == SrcVT &&
43189           Op11.getValueType() == SrcVT && Op11.getValueType() == SrcVT &&
43190           scaleShuffleElements(Mask0, 2, ShuffleMask0) &&
43191           scaleShuffleElements(Mask1, 2, ShuffleMask1)) {
43192         if ((Op00 == Op11) && (Op01 == Op10)) {
43193           std::swap(Op10, Op11);
43194           ShuffleVectorSDNode::commuteMask(ShuffleMask1);
43195         }
43196         if ((Op00 == Op10) && (Op01 == Op11)) {
43197           SmallVector<int, 4> ShuffleMask;
43198           ShuffleMask.append(ShuffleMask0.begin(), ShuffleMask0.end());
43199           ShuffleMask.append(ShuffleMask1.begin(), ShuffleMask1.end());
43200           SDLoc DL(N);
43201           MVT ShufVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
43202           SDValue Res = DAG.getNode(Opcode, DL, VT, Op00, Op01);
43203           Res = DAG.getBitcast(ShufVT, Res);
43204           Res = DAG.getVectorShuffle(ShufVT, DL, Res, Res, ShuffleMask);
43205           return DAG.getBitcast(VT, Res);
43206         }
43207       }
43208     }
43209   }
43210 
43211   return SDValue();
43212 }
43213 
43214 static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
43215                                  TargetLowering::DAGCombinerInfo &DCI,
43216                                  const X86Subtarget &Subtarget) {
43217   unsigned Opcode = N->getOpcode();
43218   assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
43219          "Unexpected pack opcode");
43220 
43221   EVT VT = N->getValueType(0);
43222   SDValue N0 = N->getOperand(0);
43223   SDValue N1 = N->getOperand(1);
43224   unsigned NumDstElts = VT.getVectorNumElements();
43225   unsigned DstBitsPerElt = VT.getScalarSizeInBits();
43226   unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
43227   assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&
43228          N1.getScalarValueSizeInBits() == SrcBitsPerElt &&
43229          "Unexpected PACKSS/PACKUS input type");
43230 
43231   bool IsSigned = (X86ISD::PACKSS == Opcode);
43232 
43233   // Constant Folding.
43234   APInt UndefElts0, UndefElts1;
43235   SmallVector<APInt, 32> EltBits0, EltBits1;
43236   if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
43237       (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
43238       getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
43239       getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
43240     unsigned NumLanes = VT.getSizeInBits() / 128;
43241     unsigned NumSrcElts = NumDstElts / 2;
43242     unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
43243     unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
43244 
43245     APInt Undefs(NumDstElts, 0);
43246     SmallVector<APInt, 32> Bits(NumDstElts, APInt::getNullValue(DstBitsPerElt));
43247     for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
43248       for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
43249         unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
43250         auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
43251         auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
43252 
43253         if (UndefElts[SrcIdx]) {
43254           Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
43255           continue;
43256         }
43257 
43258         APInt &Val = EltBits[SrcIdx];
43259         if (IsSigned) {
43260           // PACKSS: Truncate signed value with signed saturation.
43261           // Source values less than dst minint are saturated to minint.
43262           // Source values greater than dst maxint are saturated to maxint.
43263           if (Val.isSignedIntN(DstBitsPerElt))
43264             Val = Val.trunc(DstBitsPerElt);
43265           else if (Val.isNegative())
43266             Val = APInt::getSignedMinValue(DstBitsPerElt);
43267           else
43268             Val = APInt::getSignedMaxValue(DstBitsPerElt);
43269         } else {
43270           // PACKUS: Truncate signed value with unsigned saturation.
43271           // Source values less than zero are saturated to zero.
43272           // Source values greater than dst maxuint are saturated to maxuint.
43273           if (Val.isIntN(DstBitsPerElt))
43274             Val = Val.trunc(DstBitsPerElt);
43275           else if (Val.isNegative())
43276             Val = APInt::getNullValue(DstBitsPerElt);
43277           else
43278             Val = APInt::getAllOnesValue(DstBitsPerElt);
43279         }
43280         Bits[Lane * NumDstEltsPerLane + Elt] = Val;
43281       }
43282     }
43283 
43284     return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
43285   }
43286 
43287   // Try to fold PACK(SHUFFLE(),SHUFFLE()) -> SHUFFLE(PACK()).
43288   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
43289     return V;
43290 
43291   // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
43292   // truncate to create a larger truncate.
43293   if (Subtarget.hasAVX512() &&
43294       N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
43295       N0.getOperand(0).getValueType() == MVT::v8i32) {
43296     if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
43297         (!IsSigned &&
43298          DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
43299       if (Subtarget.hasVLX())
43300         return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
43301 
43302       // Widen input to v16i32 so we can truncate that.
43303       SDLoc dl(N);
43304       SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
43305                                    N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
43306       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
43307     }
43308   }
43309 
43310   // Try to fold PACK(EXTEND(X),EXTEND(Y)) -> CONCAT(X,Y) subvectors.
43311   if (VT.is128BitVector()) {
43312     unsigned ExtOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
43313     SDValue Src0, Src1;
43314     if (N0.getOpcode() == ExtOpc &&
43315         N0.getOperand(0).getValueType().is64BitVector() &&
43316         N0.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
43317       Src0 = N0.getOperand(0);
43318     }
43319     if (N1.getOpcode() == ExtOpc &&
43320         N1.getOperand(0).getValueType().is64BitVector() &&
43321         N1.getOperand(0).getScalarValueSizeInBits() == DstBitsPerElt) {
43322       Src1 = N1.getOperand(0);
43323     }
43324     if ((Src0 || N0.isUndef()) && (Src1 || N1.isUndef())) {
43325       assert((Src0 || Src1) && "Found PACK(UNDEF,UNDEF)");
43326       Src0 = Src0 ? Src0 : DAG.getUNDEF(Src1.getValueType());
43327       Src1 = Src1 ? Src1 : DAG.getUNDEF(Src0.getValueType());
43328       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Src0, Src1);
43329     }
43330   }
43331 
43332   // Attempt to combine as shuffle.
43333   SDValue Op(N, 0);
43334   if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43335     return Res;
43336 
43337   return SDValue();
43338 }
43339 
43340 static SDValue combineVectorHADDSUB(SDNode *N, SelectionDAG &DAG,
43341                                     TargetLowering::DAGCombinerInfo &DCI,
43342                                     const X86Subtarget &Subtarget) {
43343   assert((X86ISD::HADD == N->getOpcode() || X86ISD::FHADD == N->getOpcode() ||
43344           X86ISD::HSUB == N->getOpcode() || X86ISD::FHSUB == N->getOpcode()) &&
43345          "Unexpected horizontal add/sub opcode");
43346 
43347   // Try to fold HOP(SHUFFLE(),SHUFFLE()) -> SHUFFLE(HOP()).
43348   if (SDValue V = combineHorizOpWithShuffle(N, DAG, Subtarget))
43349     return V;
43350 
43351   return SDValue();
43352 }
43353 
43354 static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
43355                                      TargetLowering::DAGCombinerInfo &DCI,
43356                                      const X86Subtarget &Subtarget) {
43357   assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||
43358           X86ISD::VSRL == N->getOpcode()) &&
43359          "Unexpected shift opcode");
43360   EVT VT = N->getValueType(0);
43361   SDValue N0 = N->getOperand(0);
43362   SDValue N1 = N->getOperand(1);
43363 
43364   // Shift zero -> zero.
43365   if (ISD::isBuildVectorAllZeros(N0.getNode()))
43366     return DAG.getConstant(0, SDLoc(N), VT);
43367 
43368   // Detect constant shift amounts.
43369   APInt UndefElts;
43370   SmallVector<APInt, 32> EltBits;
43371   if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
43372     unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
43373     return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
43374                                       EltBits[0].getZExtValue(), DAG);
43375   }
43376 
43377   APInt KnownUndef, KnownZero;
43378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43379   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
43380   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
43381                                      KnownZero, DCI))
43382     return SDValue(N, 0);
43383 
43384   return SDValue();
43385 }
43386 
43387 static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
43388                                      TargetLowering::DAGCombinerInfo &DCI,
43389                                      const X86Subtarget &Subtarget) {
43390   unsigned Opcode = N->getOpcode();
43391   assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||
43392           X86ISD::VSRLI == Opcode) &&
43393          "Unexpected shift opcode");
43394   bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
43395   EVT VT = N->getValueType(0);
43396   SDValue N0 = N->getOperand(0);
43397   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
43398   assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&
43399          "Unexpected value type");
43400   assert(N->getOperand(1).getValueType() == MVT::i8 &&
43401          "Unexpected shift amount type");
43402 
43403   // Out of range logical bit shifts are guaranteed to be zero.
43404   // Out of range arithmetic bit shifts splat the sign bit.
43405   unsigned ShiftVal = N->getConstantOperandVal(1);
43406   if (ShiftVal >= NumBitsPerElt) {
43407     if (LogicalShift)
43408       return DAG.getConstant(0, SDLoc(N), VT);
43409     ShiftVal = NumBitsPerElt - 1;
43410   }
43411 
43412   // (shift X, 0) -> X
43413   if (!ShiftVal)
43414     return N0;
43415 
43416   // (shift 0, C) -> 0
43417   if (ISD::isBuildVectorAllZeros(N0.getNode()))
43418     // N0 is all zeros or undef. We guarantee that the bits shifted into the
43419     // result are all zeros, not undef.
43420     return DAG.getConstant(0, SDLoc(N), VT);
43421 
43422   // (VSRAI -1, C) -> -1
43423   if (!LogicalShift && ISD::isBuildVectorAllOnes(N0.getNode()))
43424     // N0 is all ones or undef. We guarantee that the bits shifted into the
43425     // result are all ones, not undef.
43426     return DAG.getConstant(-1, SDLoc(N), VT);
43427 
43428   // (shift (shift X, C2), C1) -> (shift X, (C1 + C2))
43429   if (Opcode == N0.getOpcode()) {
43430     unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
43431     unsigned NewShiftVal = ShiftVal + ShiftVal2;
43432     if (NewShiftVal >= NumBitsPerElt) {
43433       // Out of range logical bit shifts are guaranteed to be zero.
43434       // Out of range arithmetic bit shifts splat the sign bit.
43435       if (LogicalShift)
43436         return DAG.getConstant(0, SDLoc(N), VT);
43437       NewShiftVal = NumBitsPerElt - 1;
43438     }
43439     return DAG.getNode(Opcode, SDLoc(N), VT, N0.getOperand(0),
43440                        DAG.getTargetConstant(NewShiftVal, SDLoc(N), MVT::i8));
43441   }
43442 
43443   // We can decode 'whole byte' logical bit shifts as shuffles.
43444   if (LogicalShift && (ShiftVal % 8) == 0) {
43445     SDValue Op(N, 0);
43446     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43447       return Res;
43448   }
43449 
43450   // Constant Folding.
43451   APInt UndefElts;
43452   SmallVector<APInt, 32> EltBits;
43453   if (N->isOnlyUserOf(N0.getNode()) &&
43454       getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
43455     assert(EltBits.size() == VT.getVectorNumElements() &&
43456            "Unexpected shift value type");
43457     // Undef elements need to fold to 0. It's possible SimplifyDemandedBits
43458     // created an undef input due to no input bits being demanded, but user
43459     // still expects 0 in other bits.
43460     for (unsigned i = 0, e = EltBits.size(); i != e; ++i) {
43461       APInt &Elt = EltBits[i];
43462       if (UndefElts[i])
43463         Elt = 0;
43464       else if (X86ISD::VSHLI == Opcode)
43465         Elt <<= ShiftVal;
43466       else if (X86ISD::VSRAI == Opcode)
43467         Elt.ashrInPlace(ShiftVal);
43468       else
43469         Elt.lshrInPlace(ShiftVal);
43470     }
43471     // Reset undef elements since they were zeroed above.
43472     UndefElts = 0;
43473     return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
43474   }
43475 
43476   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43477   if (TLI.SimplifyDemandedBits(SDValue(N, 0),
43478                                APInt::getAllOnesValue(NumBitsPerElt), DCI))
43479     return SDValue(N, 0);
43480 
43481   return SDValue();
43482 }
43483 
43484 static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
43485                                    TargetLowering::DAGCombinerInfo &DCI,
43486                                    const X86Subtarget &Subtarget) {
43487   EVT VT = N->getValueType(0);
43488   assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||
43489           (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16) ||
43490           N->getOpcode() == ISD::INSERT_VECTOR_ELT) &&
43491          "Unexpected vector insertion");
43492 
43493   if (N->getOpcode() == X86ISD::PINSRB || N->getOpcode() == X86ISD::PINSRW) {
43494     unsigned NumBitsPerElt = VT.getScalarSizeInBits();
43495     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43496     if (TLI.SimplifyDemandedBits(SDValue(N, 0),
43497                                  APInt::getAllOnesValue(NumBitsPerElt), DCI))
43498       return SDValue(N, 0);
43499   }
43500 
43501   // Attempt to combine insertion patterns to a shuffle.
43502   if (VT.isSimple() && DCI.isAfterLegalizeDAG()) {
43503     SDValue Op(N, 0);
43504     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43505       return Res;
43506   }
43507 
43508   return SDValue();
43509 }
43510 
43511 /// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
43512 /// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
43513 /// OR -> CMPNEQSS.
43514 static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
43515                                    TargetLowering::DAGCombinerInfo &DCI,
43516                                    const X86Subtarget &Subtarget) {
43517   unsigned opcode;
43518 
43519   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
43520   // we're requiring SSE2 for both.
43521   if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
43522     SDValue N0 = N->getOperand(0);
43523     SDValue N1 = N->getOperand(1);
43524     SDValue CMP0 = N0.getOperand(1);
43525     SDValue CMP1 = N1.getOperand(1);
43526     SDLoc DL(N);
43527 
43528     // The SETCCs should both refer to the same CMP.
43529     if (CMP0.getOpcode() != X86ISD::FCMP || CMP0 != CMP1)
43530       return SDValue();
43531 
43532     SDValue CMP00 = CMP0->getOperand(0);
43533     SDValue CMP01 = CMP0->getOperand(1);
43534     EVT     VT    = CMP00.getValueType();
43535 
43536     if (VT == MVT::f32 || VT == MVT::f64) {
43537       bool ExpectingFlags = false;
43538       // Check for any users that want flags:
43539       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
43540            !ExpectingFlags && UI != UE; ++UI)
43541         switch (UI->getOpcode()) {
43542         default:
43543         case ISD::BR_CC:
43544         case ISD::BRCOND:
43545         case ISD::SELECT:
43546           ExpectingFlags = true;
43547           break;
43548         case ISD::CopyToReg:
43549         case ISD::SIGN_EXTEND:
43550         case ISD::ZERO_EXTEND:
43551         case ISD::ANY_EXTEND:
43552           break;
43553         }
43554 
43555       if (!ExpectingFlags) {
43556         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
43557         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
43558 
43559         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
43560           X86::CondCode tmp = cc0;
43561           cc0 = cc1;
43562           cc1 = tmp;
43563         }
43564 
43565         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
43566             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
43567           // FIXME: need symbolic constants for these magic numbers.
43568           // See X86ATTInstPrinter.cpp:printSSECC().
43569           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
43570           if (Subtarget.hasAVX512()) {
43571             SDValue FSetCC =
43572                 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
43573                             DAG.getTargetConstant(x86cc, DL, MVT::i8));
43574             // Need to fill with zeros to ensure the bitcast will produce zeroes
43575             // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
43576             SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
43577                                       DAG.getConstant(0, DL, MVT::v16i1),
43578                                       FSetCC, DAG.getIntPtrConstant(0, DL));
43579             return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
43580                                       N->getSimpleValueType(0));
43581           }
43582           SDValue OnesOrZeroesF =
43583               DAG.getNode(X86ISD::FSETCC, DL, CMP00.getValueType(), CMP00,
43584                           CMP01, DAG.getTargetConstant(x86cc, DL, MVT::i8));
43585 
43586           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
43587           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
43588 
43589           if (is64BitFP && !Subtarget.is64Bit()) {
43590             // On a 32-bit target, we cannot bitcast the 64-bit float to a
43591             // 64-bit integer, since that's not a legal type. Since
43592             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
43593             // bits, but can do this little dance to extract the lowest 32 bits
43594             // and work with those going forward.
43595             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
43596                                            OnesOrZeroesF);
43597             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
43598             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
43599                                         Vector32, DAG.getIntPtrConstant(0, DL));
43600             IntVT = MVT::i32;
43601           }
43602 
43603           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
43604           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
43605                                       DAG.getConstant(1, DL, IntVT));
43606           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
43607                                               ANDed);
43608           return OneBitOfTruth;
43609         }
43610       }
43611     }
43612   }
43613   return SDValue();
43614 }
43615 
43616 /// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
43617 static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
43618   assert(N->getOpcode() == ISD::AND);
43619 
43620   MVT VT = N->getSimpleValueType(0);
43621   if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
43622     return SDValue();
43623 
43624   SDValue X, Y;
43625   SDValue N0 = N->getOperand(0);
43626   SDValue N1 = N->getOperand(1);
43627 
43628   auto GetNot = [&VT, &DAG](SDValue V) {
43629     // Basic X = NOT(Y) detection.
43630     if (SDValue Not = IsNOT(V, DAG))
43631       return Not;
43632     // Fold BROADCAST(NOT(Y)) -> BROADCAST(Y).
43633     if (V.getOpcode() == X86ISD::VBROADCAST) {
43634       SDValue Src = V.getOperand(0);
43635       EVT SrcVT = Src.getValueType();
43636       if (!SrcVT.isVector())
43637         return SDValue();
43638       if (SDValue Not = IsNOT(Src, DAG))
43639         return DAG.getNode(X86ISD::VBROADCAST, SDLoc(V), VT,
43640                            DAG.getBitcast(SrcVT, Not));
43641     }
43642     return SDValue();
43643   };
43644 
43645   if (SDValue Not = GetNot(N0)) {
43646     X = Not;
43647     Y = N1;
43648   } else if (SDValue Not = GetNot(N1)) {
43649     X = Not;
43650     Y = N0;
43651   } else
43652     return SDValue();
43653 
43654   X = DAG.getBitcast(VT, X);
43655   Y = DAG.getBitcast(VT, Y);
43656   return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
43657 }
43658 
43659 // Try to widen AND, OR and XOR nodes to VT in order to remove casts around
43660 // logical operations, like in the example below.
43661 //   or (and (truncate x, truncate y)),
43662 //      (xor (truncate z, build_vector (constants)))
43663 // Given a target type \p VT, we generate
43664 //   or (and x, y), (xor z, zext(build_vector (constants)))
43665 // given x, y and z are of type \p VT. We can do so, if operands are either
43666 // truncates from VT types, the second operand is a vector of constants or can
43667 // be recursively promoted.
43668 static SDValue PromoteMaskArithmetic(SDNode *N, EVT VT, SelectionDAG &DAG,
43669                                      unsigned Depth) {
43670   // Limit recursion to avoid excessive compile times.
43671   if (Depth >= SelectionDAG::MaxRecursionDepth)
43672     return SDValue();
43673 
43674   if (N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND &&
43675       N->getOpcode() != ISD::OR)
43676     return SDValue();
43677 
43678   SDValue N0 = N->getOperand(0);
43679   SDValue N1 = N->getOperand(1);
43680   SDLoc DL(N);
43681 
43682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43683   if (!TLI.isOperationLegalOrPromote(N->getOpcode(), VT))
43684     return SDValue();
43685 
43686   if (SDValue NN0 = PromoteMaskArithmetic(N0.getNode(), VT, DAG, Depth + 1))
43687     N0 = NN0;
43688   else {
43689     // The Left side has to be a trunc.
43690     if (N0.getOpcode() != ISD::TRUNCATE)
43691       return SDValue();
43692 
43693     // The type of the truncated inputs.
43694     if (N0.getOperand(0).getValueType() != VT)
43695       return SDValue();
43696 
43697     N0 = N0.getOperand(0);
43698   }
43699 
43700   if (SDValue NN1 = PromoteMaskArithmetic(N1.getNode(), VT, DAG, Depth + 1))
43701     N1 = NN1;
43702   else {
43703     // The right side has to be a 'trunc' or a constant vector.
43704     bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
43705                     N1.getOperand(0).getValueType() == VT;
43706     if (!RHSTrunc && !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
43707       return SDValue();
43708 
43709     if (RHSTrunc)
43710       N1 = N1.getOperand(0);
43711     else
43712       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
43713   }
43714 
43715   return DAG.getNode(N->getOpcode(), DL, VT, N0, N1);
43716 }
43717 
43718 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
43719 // register. In most cases we actually compare or select YMM-sized registers
43720 // and mixing the two types creates horrible code. This method optimizes
43721 // some of the transition sequences.
43722 // Even with AVX-512 this is still useful for removing casts around logical
43723 // operations on vXi1 mask types.
43724 static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
43725                                      const X86Subtarget &Subtarget) {
43726   EVT VT = N->getValueType(0);
43727   assert(VT.isVector() && "Expected vector type");
43728 
43729   SDLoc DL(N);
43730   assert((N->getOpcode() == ISD::ANY_EXTEND ||
43731           N->getOpcode() == ISD::ZERO_EXTEND ||
43732           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
43733 
43734   SDValue Narrow = N->getOperand(0);
43735   EVT NarrowVT = Narrow.getValueType();
43736 
43737   // Generate the wide operation.
43738   SDValue Op = PromoteMaskArithmetic(Narrow.getNode(), VT, DAG, 0);
43739   if (!Op)
43740     return SDValue();
43741   switch (N->getOpcode()) {
43742   default: llvm_unreachable("Unexpected opcode");
43743   case ISD::ANY_EXTEND:
43744     return Op;
43745   case ISD::ZERO_EXTEND:
43746     return DAG.getZeroExtendInReg(Op, DL, NarrowVT);
43747   case ISD::SIGN_EXTEND:
43748     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
43749                        Op, DAG.getValueType(NarrowVT));
43750   }
43751 }
43752 
43753 static unsigned convertIntLogicToFPLogicOpcode(unsigned Opcode) {
43754   unsigned FPOpcode;
43755   switch (Opcode) {
43756   default: llvm_unreachable("Unexpected input node for FP logic conversion");
43757   case ISD::AND: FPOpcode = X86ISD::FAND; break;
43758   case ISD::OR:  FPOpcode = X86ISD::FOR;  break;
43759   case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
43760   }
43761   return FPOpcode;
43762 }
43763 
43764 /// If both input operands of a logic op are being cast from floating point
43765 /// types, try to convert this into a floating point logic node to avoid
43766 /// unnecessary moves from SSE to integer registers.
43767 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
43768                                         const X86Subtarget &Subtarget) {
43769   EVT VT = N->getValueType(0);
43770   SDValue N0 = N->getOperand(0);
43771   SDValue N1 = N->getOperand(1);
43772   SDLoc DL(N);
43773 
43774   if (N0.getOpcode() != ISD::BITCAST || N1.getOpcode() != ISD::BITCAST)
43775     return SDValue();
43776 
43777   SDValue N00 = N0.getOperand(0);
43778   SDValue N10 = N1.getOperand(0);
43779   EVT N00Type = N00.getValueType();
43780   EVT N10Type = N10.getValueType();
43781 
43782   // Ensure that both types are the same and are legal scalar fp types.
43783   if (N00Type != N10Type ||
43784       !((Subtarget.hasSSE1() && N00Type == MVT::f32) ||
43785         (Subtarget.hasSSE2() && N00Type == MVT::f64)))
43786     return SDValue();
43787 
43788   unsigned FPOpcode = convertIntLogicToFPLogicOpcode(N->getOpcode());
43789   SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
43790   return DAG.getBitcast(VT, FPLogic);
43791 }
43792 
43793 // Attempt to fold BITOP(MOVMSK(X),MOVMSK(Y)) -> MOVMSK(BITOP(X,Y))
43794 // to reduce XMM->GPR traffic.
43795 static SDValue combineBitOpWithMOVMSK(SDNode *N, SelectionDAG &DAG) {
43796   unsigned Opc = N->getOpcode();
43797   assert((Opc == ISD::OR || Opc == ISD::AND || Opc == ISD::XOR) &&
43798          "Unexpected bit opcode");
43799 
43800   SDValue N0 = N->getOperand(0);
43801   SDValue N1 = N->getOperand(1);
43802 
43803   // Both operands must be single use MOVMSK.
43804   if (N0.getOpcode() != X86ISD::MOVMSK || !N0.hasOneUse() ||
43805       N1.getOpcode() != X86ISD::MOVMSK || !N1.hasOneUse())
43806     return SDValue();
43807 
43808   SDValue Vec0 = N0.getOperand(0);
43809   SDValue Vec1 = N1.getOperand(0);
43810   EVT VecVT0 = Vec0.getValueType();
43811   EVT VecVT1 = Vec1.getValueType();
43812 
43813   // Both MOVMSK operands must be from vectors of the same size and same element
43814   // size, but its OK for a fp/int diff.
43815   if (VecVT0.getSizeInBits() != VecVT1.getSizeInBits() ||
43816       VecVT0.getScalarSizeInBits() != VecVT1.getScalarSizeInBits())
43817     return SDValue();
43818 
43819   SDLoc DL(N);
43820   unsigned VecOpc =
43821       VecVT0.isFloatingPoint() ? convertIntLogicToFPLogicOpcode(Opc) : Opc;
43822   SDValue Result =
43823       DAG.getNode(VecOpc, DL, VecVT0, Vec0, DAG.getBitcast(VecVT0, Vec1));
43824   return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Result);
43825 }
43826 
43827 /// If this is a zero/all-bits result that is bitwise-anded with a low bits
43828 /// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
43829 /// with a shift-right to eliminate loading the vector constant mask value.
43830 static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
43831                                      const X86Subtarget &Subtarget) {
43832   SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
43833   SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
43834   EVT VT0 = Op0.getValueType();
43835   EVT VT1 = Op1.getValueType();
43836 
43837   if (VT0 != VT1 || !VT0.isSimple() || !VT0.isInteger())
43838     return SDValue();
43839 
43840   APInt SplatVal;
43841   if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
43842       !SplatVal.isMask())
43843     return SDValue();
43844 
43845   // Don't prevent creation of ANDN.
43846   if (isBitwiseNot(Op0))
43847     return SDValue();
43848 
43849   if (!SupportedVectorShiftWithImm(VT0.getSimpleVT(), Subtarget, ISD::SRL))
43850     return SDValue();
43851 
43852   unsigned EltBitWidth = VT0.getScalarSizeInBits();
43853   if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
43854     return SDValue();
43855 
43856   SDLoc DL(N);
43857   unsigned ShiftVal = SplatVal.countTrailingOnes();
43858   SDValue ShAmt = DAG.getTargetConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
43859   SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
43860   return DAG.getBitcast(N->getValueType(0), Shift);
43861 }
43862 
43863 // Get the index node from the lowered DAG of a GEP IR instruction with one
43864 // indexing dimension.
43865 static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
43866   if (Ld->isIndexed())
43867     return SDValue();
43868 
43869   SDValue Base = Ld->getBasePtr();
43870 
43871   if (Base.getOpcode() != ISD::ADD)
43872     return SDValue();
43873 
43874   SDValue ShiftedIndex = Base.getOperand(0);
43875 
43876   if (ShiftedIndex.getOpcode() != ISD::SHL)
43877     return SDValue();
43878 
43879   return ShiftedIndex.getOperand(0);
43880 
43881 }
43882 
43883 static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
43884   if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
43885     switch (VT.getSizeInBits()) {
43886     default: return false;
43887     case 64: return Subtarget.is64Bit() ? true : false;
43888     case 32: return true;
43889     }
43890   }
43891   return false;
43892 }
43893 
43894 // This function recognizes cases where X86 bzhi instruction can replace and
43895 // 'and-load' sequence.
43896 // In case of loading integer value from an array of constants which is defined
43897 // as follows:
43898 //
43899 //   int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
43900 //
43901 // then applying a bitwise and on the result with another input.
43902 // It's equivalent to performing bzhi (zero high bits) on the input, with the
43903 // same index of the load.
43904 static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
43905                                     const X86Subtarget &Subtarget) {
43906   MVT VT = Node->getSimpleValueType(0);
43907   SDLoc dl(Node);
43908 
43909   // Check if subtarget has BZHI instruction for the node's type
43910   if (!hasBZHI(Subtarget, VT))
43911     return SDValue();
43912 
43913   // Try matching the pattern for both operands.
43914   for (unsigned i = 0; i < 2; i++) {
43915     SDValue N = Node->getOperand(i);
43916     LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
43917 
43918      // continue if the operand is not a load instruction
43919     if (!Ld)
43920       return SDValue();
43921 
43922     const Value *MemOp = Ld->getMemOperand()->getValue();
43923 
43924     if (!MemOp)
43925       return SDValue();
43926 
43927     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
43928       if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
43929         if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
43930 
43931           Constant *Init = GV->getInitializer();
43932           Type *Ty = Init->getType();
43933           if (!isa<ConstantDataArray>(Init) ||
43934               !Ty->getArrayElementType()->isIntegerTy() ||
43935               Ty->getArrayElementType()->getScalarSizeInBits() !=
43936                   VT.getSizeInBits() ||
43937               Ty->getArrayNumElements() >
43938                   Ty->getArrayElementType()->getScalarSizeInBits())
43939             continue;
43940 
43941           // Check if the array's constant elements are suitable to our case.
43942           uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
43943           bool ConstantsMatch = true;
43944           for (uint64_t j = 0; j < ArrayElementCount; j++) {
43945             ConstantInt *Elem =
43946                 dyn_cast<ConstantInt>(Init->getAggregateElement(j));
43947             if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
43948               ConstantsMatch = false;
43949               break;
43950             }
43951           }
43952           if (!ConstantsMatch)
43953             continue;
43954 
43955           // Do the transformation (For 32-bit type):
43956           // -> (and (load arr[idx]), inp)
43957           // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
43958           //    that will be replaced with one bzhi instruction.
43959           SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
43960           SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
43961 
43962           // Get the Node which indexes into the array.
43963           SDValue Index = getIndexFromUnindexedLoad(Ld);
43964           if (!Index)
43965             return SDValue();
43966           Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
43967 
43968           SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
43969           Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
43970 
43971           SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
43972           SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
43973 
43974           return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
43975         }
43976       }
43977     }
43978   }
43979   return SDValue();
43980 }
43981 
43982 // Look for (and (bitcast (vXi1 (concat_vectors (vYi1 setcc), undef,))), C)
43983 // Where C is a mask containing the same number of bits as the setcc and
43984 // where the setcc will freely 0 upper bits of k-register. We can replace the
43985 // undef in the concat with 0s and remove the AND. This mainly helps with
43986 // v2i1/v4i1 setcc being casted to scalar.
43987 static SDValue combineScalarAndWithMaskSetcc(SDNode *N, SelectionDAG &DAG,
43988                                              const X86Subtarget &Subtarget) {
43989   assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
43990 
43991   EVT VT = N->getValueType(0);
43992 
43993   // Make sure this is an AND with constant. We will check the value of the
43994   // constant later.
43995   if (!isa<ConstantSDNode>(N->getOperand(1)))
43996     return SDValue();
43997 
43998   // This is implied by the ConstantSDNode.
43999   assert(!VT.isVector() && "Expected scalar VT!");
44000 
44001   if (N->getOperand(0).getOpcode() != ISD::BITCAST ||
44002       !N->getOperand(0).hasOneUse() ||
44003       !N->getOperand(0).getOperand(0).hasOneUse())
44004     return SDValue();
44005 
44006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44007   SDValue Src = N->getOperand(0).getOperand(0);
44008   EVT SrcVT = Src.getValueType();
44009   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::i1 ||
44010       !TLI.isTypeLegal(SrcVT))
44011     return SDValue();
44012 
44013   if (Src.getOpcode() != ISD::CONCAT_VECTORS)
44014     return SDValue();
44015 
44016   // We only care about the first subvector of the concat, we expect the
44017   // other subvectors to be ignored due to the AND if we make the change.
44018   SDValue SubVec = Src.getOperand(0);
44019   EVT SubVecVT = SubVec.getValueType();
44020 
44021   // First subvector should be a setcc with a legal result type. The RHS of the
44022   // AND should be a mask with this many bits.
44023   if (SubVec.getOpcode() != ISD::SETCC || !TLI.isTypeLegal(SubVecVT) ||
44024       !N->getConstantOperandAPInt(1).isMask(SubVecVT.getVectorNumElements()))
44025     return SDValue();
44026 
44027   EVT SetccVT = SubVec.getOperand(0).getValueType();
44028   if (!TLI.isTypeLegal(SetccVT) ||
44029       !(Subtarget.hasVLX() || SetccVT.is512BitVector()))
44030     return SDValue();
44031 
44032   if (!(Subtarget.hasBWI() || SetccVT.getScalarSizeInBits() >= 32))
44033     return SDValue();
44034 
44035   // We passed all the checks. Rebuild the concat_vectors with zeroes
44036   // and cast it back to VT.
44037   SDLoc dl(N);
44038   SmallVector<SDValue, 4> Ops(Src.getNumOperands(),
44039                               DAG.getConstant(0, dl, SubVecVT));
44040   Ops[0] = SubVec;
44041   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT,
44042                                Ops);
44043   return DAG.getBitcast(VT, Concat);
44044 }
44045 
44046 static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
44047                           TargetLowering::DAGCombinerInfo &DCI,
44048                           const X86Subtarget &Subtarget) {
44049   EVT VT = N->getValueType(0);
44050 
44051   // If this is SSE1 only convert to FAND to avoid scalarization.
44052   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
44053     return DAG.getBitcast(
44054         MVT::v4i32, DAG.getNode(X86ISD::FAND, SDLoc(N), MVT::v4f32,
44055                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
44056                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
44057   }
44058 
44059   // Use a 32-bit and+zext if upper bits known zero.
44060   if (VT == MVT::i64 && Subtarget.is64Bit() &&
44061       !isa<ConstantSDNode>(N->getOperand(1))) {
44062     APInt HiMask = APInt::getHighBitsSet(64, 32);
44063     if (DAG.MaskedValueIsZero(N->getOperand(1), HiMask) ||
44064         DAG.MaskedValueIsZero(N->getOperand(0), HiMask)) {
44065       SDLoc dl(N);
44066       SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(0));
44067       SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(1));
44068       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
44069                          DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
44070     }
44071   }
44072 
44073   // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
44074   // TODO: Support multiple SrcOps.
44075   if (VT == MVT::i1) {
44076     SmallVector<SDValue, 2> SrcOps;
44077     SmallVector<APInt, 2> SrcPartials;
44078     if (matchScalarReduction(SDValue(N, 0), ISD::AND, SrcOps, &SrcPartials) &&
44079         SrcOps.size() == 1) {
44080       SDLoc dl(N);
44081       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44082       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
44083       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
44084       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
44085       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
44086         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
44087       if (Mask) {
44088         assert(SrcPartials[0].getBitWidth() == NumElts &&
44089                "Unexpected partial reduction mask");
44090         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
44091         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
44092         return DAG.getSetCC(dl, MVT::i1, Mask, PartialBits, ISD::SETEQ);
44093       }
44094     }
44095   }
44096 
44097   if (SDValue V = combineScalarAndWithMaskSetcc(N, DAG, Subtarget))
44098     return V;
44099 
44100   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
44101     return R;
44102 
44103   if (DCI.isBeforeLegalizeOps())
44104     return SDValue();
44105 
44106   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
44107     return R;
44108 
44109   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
44110     return FPLogic;
44111 
44112   if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
44113     return R;
44114 
44115   if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
44116     return ShiftRight;
44117 
44118   if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
44119     return R;
44120 
44121   // Attempt to recursively combine a bitmask AND with shuffles.
44122   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
44123     SDValue Op(N, 0);
44124     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
44125       return Res;
44126   }
44127 
44128   // Attempt to combine a scalar bitmask AND with an extracted shuffle.
44129   if ((VT.getScalarSizeInBits() % 8) == 0 &&
44130       N->getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
44131       isa<ConstantSDNode>(N->getOperand(0).getOperand(1))) {
44132     SDValue BitMask = N->getOperand(1);
44133     SDValue SrcVec = N->getOperand(0).getOperand(0);
44134     EVT SrcVecVT = SrcVec.getValueType();
44135 
44136     // Check that the constant bitmask masks whole bytes.
44137     APInt UndefElts;
44138     SmallVector<APInt, 64> EltBits;
44139     if (VT == SrcVecVT.getScalarType() &&
44140         N->getOperand(0)->isOnlyUserOf(SrcVec.getNode()) &&
44141         getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
44142         llvm::all_of(EltBits, [](const APInt &M) {
44143           return M.isNullValue() || M.isAllOnesValue();
44144         })) {
44145       unsigned NumElts = SrcVecVT.getVectorNumElements();
44146       unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
44147       unsigned Idx = N->getOperand(0).getConstantOperandVal(1);
44148 
44149       // Create a root shuffle mask from the byte mask and the extracted index.
44150       SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
44151       for (unsigned i = 0; i != Scale; ++i) {
44152         if (UndefElts[i])
44153           continue;
44154         int VecIdx = Scale * Idx + i;
44155         ShuffleMask[VecIdx] =
44156             EltBits[i].isNullValue() ? SM_SentinelZero : VecIdx;
44157       }
44158 
44159       if (SDValue Shuffle = combineX86ShufflesRecursively(
44160               {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 1,
44161               X86::MaxShuffleCombineDepth,
44162               /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
44163         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), VT, Shuffle,
44164                            N->getOperand(0).getOperand(1));
44165     }
44166   }
44167 
44168   return SDValue();
44169 }
44170 
44171 // Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
44172 static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
44173                                      const X86Subtarget &Subtarget) {
44174   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
44175 
44176   MVT VT = N->getSimpleValueType(0);
44177   if (!VT.isVector() || (VT.getScalarSizeInBits() % 8) != 0)
44178     return SDValue();
44179 
44180   SDValue N0 = peekThroughBitcasts(N->getOperand(0));
44181   SDValue N1 = peekThroughBitcasts(N->getOperand(1));
44182   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
44183     return SDValue();
44184 
44185   // On XOP we'll lower to PCMOV so accept one use. With AVX512, we can use
44186   // VPTERNLOG. Otherwise only do this if either mask has multiple uses already.
44187   bool UseVPTERNLOG = (Subtarget.hasAVX512() && VT.is512BitVector()) ||
44188                       Subtarget.hasVLX();
44189   if (!(Subtarget.hasXOP() || UseVPTERNLOG ||
44190         !N0.getOperand(1).hasOneUse() || !N1.getOperand(1).hasOneUse()))
44191     return SDValue();
44192 
44193   // Attempt to extract constant byte masks.
44194   APInt UndefElts0, UndefElts1;
44195   SmallVector<APInt, 32> EltBits0, EltBits1;
44196   if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
44197                                      false, false))
44198     return SDValue();
44199   if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
44200                                      false, false))
44201     return SDValue();
44202 
44203   for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
44204     // TODO - add UNDEF elts support.
44205     if (UndefElts0[i] || UndefElts1[i])
44206       return SDValue();
44207     if (EltBits0[i] != ~EltBits1[i])
44208       return SDValue();
44209   }
44210 
44211   SDLoc DL(N);
44212 
44213   if (UseVPTERNLOG) {
44214     // Emit a VPTERNLOG node directly.
44215     SDValue A = DAG.getBitcast(VT, N0.getOperand(1));
44216     SDValue B = DAG.getBitcast(VT, N0.getOperand(0));
44217     SDValue C = DAG.getBitcast(VT, N1.getOperand(0));
44218     SDValue Imm = DAG.getTargetConstant(0xCA, DL, MVT::i8);
44219     return DAG.getNode(X86ISD::VPTERNLOG, DL, VT, A, B, C, Imm);
44220   }
44221 
44222   SDValue X = N->getOperand(0);
44223   SDValue Y =
44224       DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
44225                   DAG.getBitcast(VT, N1.getOperand(0)));
44226   return DAG.getNode(ISD::OR, DL, VT, X, Y);
44227 }
44228 
44229 // Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
44230 static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
44231   if (N->getOpcode() != ISD::OR)
44232     return false;
44233 
44234   SDValue N0 = N->getOperand(0);
44235   SDValue N1 = N->getOperand(1);
44236 
44237   // Canonicalize AND to LHS.
44238   if (N1.getOpcode() == ISD::AND)
44239     std::swap(N0, N1);
44240 
44241   // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
44242   if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
44243     return false;
44244 
44245   Mask = N1.getOperand(0);
44246   X = N1.getOperand(1);
44247 
44248   // Check to see if the mask appeared in both the AND and ANDNP.
44249   if (N0.getOperand(0) == Mask)
44250     Y = N0.getOperand(1);
44251   else if (N0.getOperand(1) == Mask)
44252     Y = N0.getOperand(0);
44253   else
44254     return false;
44255 
44256   // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
44257   // ANDNP combine allows other combines to happen that prevent matching.
44258   return true;
44259 }
44260 
44261 // Try to fold:
44262 //   (or (and (m, y), (pandn m, x)))
44263 // into:
44264 //   (vselect m, x, y)
44265 // As a special case, try to fold:
44266 //   (or (and (m, (sub 0, x)), (pandn m, x)))
44267 // into:
44268 //   (sub (xor X, M), M)
44269 static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
44270                                             const X86Subtarget &Subtarget) {
44271   assert(N->getOpcode() == ISD::OR && "Unexpected Opcode");
44272 
44273   EVT VT = N->getValueType(0);
44274   if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
44275         (VT.is256BitVector() && Subtarget.hasInt256())))
44276     return SDValue();
44277 
44278   SDValue X, Y, Mask;
44279   if (!matchLogicBlend(N, X, Y, Mask))
44280     return SDValue();
44281 
44282   // Validate that X, Y, and Mask are bitcasts, and see through them.
44283   Mask = peekThroughBitcasts(Mask);
44284   X = peekThroughBitcasts(X);
44285   Y = peekThroughBitcasts(Y);
44286 
44287   EVT MaskVT = Mask.getValueType();
44288   unsigned EltBits = MaskVT.getScalarSizeInBits();
44289 
44290   // TODO: Attempt to handle floating point cases as well?
44291   if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
44292     return SDValue();
44293 
44294   SDLoc DL(N);
44295 
44296   // Attempt to combine to conditional negate: (sub (xor X, M), M)
44297   if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
44298                                                            DAG, Subtarget))
44299     return Res;
44300 
44301   // PBLENDVB is only available on SSE 4.1.
44302   if (!Subtarget.hasSSE41())
44303     return SDValue();
44304 
44305   // If we have VPTERNLOG we should prefer that since PBLENDVB is multiple uops.
44306   if (Subtarget.hasVLX())
44307     return SDValue();
44308 
44309   MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
44310 
44311   X = DAG.getBitcast(BlendVT, X);
44312   Y = DAG.getBitcast(BlendVT, Y);
44313   Mask = DAG.getBitcast(BlendVT, Mask);
44314   Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
44315   return DAG.getBitcast(VT, Mask);
44316 }
44317 
44318 // Helper function for combineOrCmpEqZeroToCtlzSrl
44319 // Transforms:
44320 //   seteq(cmp x, 0)
44321 //   into:
44322 //   srl(ctlz x), log2(bitsize(x))
44323 // Input pattern is checked by caller.
44324 static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
44325                                           SelectionDAG &DAG) {
44326   SDValue Cmp = Op.getOperand(1);
44327   EVT VT = Cmp.getOperand(0).getValueType();
44328   unsigned Log2b = Log2_32(VT.getSizeInBits());
44329   SDLoc dl(Op);
44330   SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
44331   // The result of the shift is true or false, and on X86, the 32-bit
44332   // encoding of shr and lzcnt is more desirable.
44333   SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
44334   SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
44335                             DAG.getConstant(Log2b, dl, MVT::i8));
44336   return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
44337 }
44338 
44339 // Try to transform:
44340 //   zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
44341 //   into:
44342 //   srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
44343 // Will also attempt to match more generic cases, eg:
44344 //   zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
44345 // Only applies if the target supports the FastLZCNT feature.
44346 static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
44347                                            TargetLowering::DAGCombinerInfo &DCI,
44348                                            const X86Subtarget &Subtarget) {
44349   if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
44350     return SDValue();
44351 
44352   auto isORCandidate = [](SDValue N) {
44353     return (N->getOpcode() == ISD::OR && N->hasOneUse());
44354   };
44355 
44356   // Check the zero extend is extending to 32-bit or more. The code generated by
44357   // srl(ctlz) for 16-bit or less variants of the pattern would require extra
44358   // instructions to clear the upper bits.
44359   if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
44360       !isORCandidate(N->getOperand(0)))
44361     return SDValue();
44362 
44363   // Check the node matches: setcc(eq, cmp 0)
44364   auto isSetCCCandidate = [](SDValue N) {
44365     return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
44366            X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
44367            N->getOperand(1).getOpcode() == X86ISD::CMP &&
44368            isNullConstant(N->getOperand(1).getOperand(1)) &&
44369            N->getOperand(1).getValueType().bitsGE(MVT::i32);
44370   };
44371 
44372   SDNode *OR = N->getOperand(0).getNode();
44373   SDValue LHS = OR->getOperand(0);
44374   SDValue RHS = OR->getOperand(1);
44375 
44376   // Save nodes matching or(or, setcc(eq, cmp 0)).
44377   SmallVector<SDNode *, 2> ORNodes;
44378   while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
44379           (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
44380     ORNodes.push_back(OR);
44381     OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
44382     LHS = OR->getOperand(0);
44383     RHS = OR->getOperand(1);
44384   }
44385 
44386   // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
44387   if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
44388       !isORCandidate(SDValue(OR, 0)))
44389     return SDValue();
44390 
44391   // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
44392   // to
44393   // or(srl(ctlz),srl(ctlz)).
44394   // The dag combiner can then fold it into:
44395   // srl(or(ctlz, ctlz)).
44396   EVT VT = OR->getValueType(0);
44397   SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
44398   SDValue Ret, NewRHS;
44399   if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
44400     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
44401 
44402   if (!Ret)
44403     return SDValue();
44404 
44405   // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
44406   while (ORNodes.size() > 0) {
44407     OR = ORNodes.pop_back_val();
44408     LHS = OR->getOperand(0);
44409     RHS = OR->getOperand(1);
44410     // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
44411     if (RHS->getOpcode() == ISD::OR)
44412       std::swap(LHS, RHS);
44413     NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
44414     if (!NewRHS)
44415       return SDValue();
44416     Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
44417   }
44418 
44419   if (Ret)
44420     Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
44421 
44422   return Ret;
44423 }
44424 
44425 static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
44426                          TargetLowering::DAGCombinerInfo &DCI,
44427                          const X86Subtarget &Subtarget) {
44428   SDValue N0 = N->getOperand(0);
44429   SDValue N1 = N->getOperand(1);
44430   EVT VT = N->getValueType(0);
44431 
44432   // If this is SSE1 only convert to FOR to avoid scalarization.
44433   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
44434     return DAG.getBitcast(MVT::v4i32,
44435                           DAG.getNode(X86ISD::FOR, SDLoc(N), MVT::v4f32,
44436                                       DAG.getBitcast(MVT::v4f32, N0),
44437                                       DAG.getBitcast(MVT::v4f32, N1)));
44438   }
44439 
44440   // Match any-of bool scalar reductions into a bitcast/movmsk + cmp.
44441   // TODO: Support multiple SrcOps.
44442   if (VT == MVT::i1) {
44443     SmallVector<SDValue, 2> SrcOps;
44444     SmallVector<APInt, 2> SrcPartials;
44445     if (matchScalarReduction(SDValue(N, 0), ISD::OR, SrcOps, &SrcPartials) &&
44446         SrcOps.size() == 1) {
44447       SDLoc dl(N);
44448       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44449       unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
44450       EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
44451       SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
44452       if (!Mask && TLI.isTypeLegal(SrcOps[0].getValueType()))
44453         Mask = DAG.getBitcast(MaskVT, SrcOps[0]);
44454       if (Mask) {
44455         assert(SrcPartials[0].getBitWidth() == NumElts &&
44456                "Unexpected partial reduction mask");
44457         SDValue ZeroBits = DAG.getConstant(0, dl, MaskVT);
44458         SDValue PartialBits = DAG.getConstant(SrcPartials[0], dl, MaskVT);
44459         Mask = DAG.getNode(ISD::AND, dl, MaskVT, Mask, PartialBits);
44460         return DAG.getSetCC(dl, MVT::i1, Mask, ZeroBits, ISD::SETNE);
44461       }
44462     }
44463   }
44464 
44465   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
44466     return R;
44467 
44468   if (DCI.isBeforeLegalizeOps())
44469     return SDValue();
44470 
44471   if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
44472     return R;
44473 
44474   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
44475     return FPLogic;
44476 
44477   if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
44478     return R;
44479 
44480   if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
44481     return R;
44482 
44483   // Combine OR(X,KSHIFTL(Y,Elts/2)) -> CONCAT_VECTORS(X,Y) == KUNPCK(X,Y).
44484   // Combine OR(KSHIFTL(X,Elts/2),Y) -> CONCAT_VECTORS(Y,X) == KUNPCK(Y,X).
44485   // iff the upper elements of the non-shifted arg are zero.
44486   // KUNPCK require 16+ bool vector elements.
44487   if (N0.getOpcode() == X86ISD::KSHIFTL || N1.getOpcode() == X86ISD::KSHIFTL) {
44488     unsigned NumElts = VT.getVectorNumElements();
44489     unsigned HalfElts = NumElts / 2;
44490     APInt UpperElts = APInt::getHighBitsSet(NumElts, HalfElts);
44491     if (NumElts >= 16 && N1.getOpcode() == X86ISD::KSHIFTL &&
44492         N1.getConstantOperandAPInt(1) == HalfElts &&
44493         DAG.MaskedValueIsZero(N0, APInt(1, 1), UpperElts)) {
44494       SDLoc dl(N);
44495       return DAG.getNode(
44496           ISD::CONCAT_VECTORS, dl, VT,
44497           extractSubVector(N0, 0, DAG, dl, HalfElts),
44498           extractSubVector(N1.getOperand(0), 0, DAG, dl, HalfElts));
44499     }
44500     if (NumElts >= 16 && N0.getOpcode() == X86ISD::KSHIFTL &&
44501         N0.getConstantOperandAPInt(1) == HalfElts &&
44502         DAG.MaskedValueIsZero(N1, APInt(1, 1), UpperElts)) {
44503       SDLoc dl(N);
44504       return DAG.getNode(
44505           ISD::CONCAT_VECTORS, dl, VT,
44506           extractSubVector(N1, 0, DAG, dl, HalfElts),
44507           extractSubVector(N0.getOperand(0), 0, DAG, dl, HalfElts));
44508     }
44509   }
44510 
44511   // Attempt to recursively combine an OR of shuffles.
44512   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
44513     SDValue Op(N, 0);
44514     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
44515       return Res;
44516   }
44517 
44518   return SDValue();
44519 }
44520 
44521 /// Try to turn tests against the signbit in the form of:
44522 ///   XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
44523 /// into:
44524 ///   SETGT(X, -1)
44525 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
44526   // This is only worth doing if the output type is i8 or i1.
44527   EVT ResultType = N->getValueType(0);
44528   if (ResultType != MVT::i8 && ResultType != MVT::i1)
44529     return SDValue();
44530 
44531   SDValue N0 = N->getOperand(0);
44532   SDValue N1 = N->getOperand(1);
44533 
44534   // We should be performing an xor against a truncated shift.
44535   if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
44536     return SDValue();
44537 
44538   // Make sure we are performing an xor against one.
44539   if (!isOneConstant(N1))
44540     return SDValue();
44541 
44542   // SetCC on x86 zero extends so only act on this if it's a logical shift.
44543   SDValue Shift = N0.getOperand(0);
44544   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
44545     return SDValue();
44546 
44547   // Make sure we are truncating from one of i16, i32 or i64.
44548   EVT ShiftTy = Shift.getValueType();
44549   if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
44550     return SDValue();
44551 
44552   // Make sure the shift amount extracts the sign bit.
44553   if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
44554       Shift.getConstantOperandAPInt(1) != (ShiftTy.getSizeInBits() - 1))
44555     return SDValue();
44556 
44557   // Create a greater-than comparison against -1.
44558   // N.B. Using SETGE against 0 works but we want a canonical looking
44559   // comparison, using SETGT matches up with what TranslateX86CC.
44560   SDLoc DL(N);
44561   SDValue ShiftOp = Shift.getOperand(0);
44562   EVT ShiftOpTy = ShiftOp.getValueType();
44563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44564   EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
44565                                                *DAG.getContext(), ResultType);
44566   SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
44567                               DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
44568   if (SetCCResultType != ResultType)
44569     Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
44570   return Cond;
44571 }
44572 
44573 /// Turn vector tests of the signbit in the form of:
44574 ///   xor (sra X, elt_size(X)-1), -1
44575 /// into:
44576 ///   pcmpgt X, -1
44577 ///
44578 /// This should be called before type legalization because the pattern may not
44579 /// persist after that.
44580 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
44581                                          const X86Subtarget &Subtarget) {
44582   EVT VT = N->getValueType(0);
44583   if (!VT.isSimple())
44584     return SDValue();
44585 
44586   switch (VT.getSimpleVT().SimpleTy) {
44587   default: return SDValue();
44588   case MVT::v16i8:
44589   case MVT::v8i16:
44590   case MVT::v4i32:
44591   case MVT::v2i64: if (!Subtarget.hasSSE2()) return SDValue(); break;
44592   case MVT::v32i8:
44593   case MVT::v16i16:
44594   case MVT::v8i32:
44595   case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
44596   }
44597 
44598   // There must be a shift right algebraic before the xor, and the xor must be a
44599   // 'not' operation.
44600   SDValue Shift = N->getOperand(0);
44601   SDValue Ones = N->getOperand(1);
44602   if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
44603       !ISD::isBuildVectorAllOnes(Ones.getNode()))
44604     return SDValue();
44605 
44606   // The shift should be smearing the sign bit across each vector element.
44607   auto *ShiftAmt =
44608       isConstOrConstSplat(Shift.getOperand(1), /*AllowUndefs*/ true);
44609   if (!ShiftAmt ||
44610       ShiftAmt->getAPIntValue() != (Shift.getScalarValueSizeInBits() - 1))
44611     return SDValue();
44612 
44613   // Create a greater-than comparison against -1. We don't use the more obvious
44614   // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
44615   return DAG.getSetCC(SDLoc(N), VT, Shift.getOperand(0), Ones, ISD::SETGT);
44616 }
44617 
44618 /// Detect patterns of truncation with unsigned saturation:
44619 ///
44620 /// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
44621 ///   Return the source value x to be truncated or SDValue() if the pattern was
44622 ///   not matched.
44623 ///
44624 /// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
44625 ///   where C1 >= 0 and C2 is unsigned max of destination type.
44626 ///
44627 ///    (truncate (smax (smin (x, C2), C1)) to dest_type)
44628 ///   where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
44629 ///
44630 ///   These two patterns are equivalent to:
44631 ///   (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
44632 ///   So return the smax(x, C1) value to be truncated or SDValue() if the
44633 ///   pattern was not matched.
44634 static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
44635                                  const SDLoc &DL) {
44636   EVT InVT = In.getValueType();
44637 
44638   // Saturation with truncation. We truncate from InVT to VT.
44639   assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
44640          "Unexpected types for truncate operation");
44641 
44642   // Match min/max and return limit value as a parameter.
44643   auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
44644     if (V.getOpcode() == Opcode &&
44645         ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
44646       return V.getOperand(0);
44647     return SDValue();
44648   };
44649 
44650   APInt C1, C2;
44651   if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
44652     // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
44653     // the element size of the destination type.
44654     if (C2.isMask(VT.getScalarSizeInBits()))
44655       return UMin;
44656 
44657   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
44658     if (MatchMinMax(SMin, ISD::SMAX, C1))
44659       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
44660         return SMin;
44661 
44662   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
44663     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
44664       if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
44665           C2.uge(C1)) {
44666         return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
44667       }
44668 
44669   return SDValue();
44670 }
44671 
44672 /// Detect patterns of truncation with signed saturation:
44673 /// (truncate (smin ((smax (x, signed_min_of_dest_type)),
44674 ///                  signed_max_of_dest_type)) to dest_type)
44675 /// or:
44676 /// (truncate (smax ((smin (x, signed_max_of_dest_type)),
44677 ///                  signed_min_of_dest_type)) to dest_type).
44678 /// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
44679 /// Return the source value to be truncated or SDValue() if the pattern was not
44680 /// matched.
44681 static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
44682   unsigned NumDstBits = VT.getScalarSizeInBits();
44683   unsigned NumSrcBits = In.getScalarValueSizeInBits();
44684   assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation");
44685 
44686   auto MatchMinMax = [](SDValue V, unsigned Opcode,
44687                         const APInt &Limit) -> SDValue {
44688     APInt C;
44689     if (V.getOpcode() == Opcode &&
44690         ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
44691       return V.getOperand(0);
44692     return SDValue();
44693   };
44694 
44695   APInt SignedMax, SignedMin;
44696   if (MatchPackUS) {
44697     SignedMax = APInt::getAllOnesValue(NumDstBits).zext(NumSrcBits);
44698     SignedMin = APInt(NumSrcBits, 0);
44699   } else {
44700     SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
44701     SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
44702   }
44703 
44704   if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
44705     if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
44706       return SMax;
44707 
44708   if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
44709     if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
44710       return SMin;
44711 
44712   return SDValue();
44713 }
44714 
44715 static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
44716                                       SelectionDAG &DAG,
44717                                       const X86Subtarget &Subtarget) {
44718   if (!Subtarget.hasSSE2() || !VT.isVector())
44719     return SDValue();
44720 
44721   EVT SVT = VT.getVectorElementType();
44722   EVT InVT = In.getValueType();
44723   EVT InSVT = InVT.getVectorElementType();
44724 
44725   // If we're clamping a signed 32-bit vector to 0-255 and the 32-bit vector is
44726   // split across two registers. We can use a packusdw+perm to clamp to 0-65535
44727   // and concatenate at the same time. Then we can use a final vpmovuswb to
44728   // clip to 0-255.
44729   if (Subtarget.hasBWI() && !Subtarget.useAVX512Regs() &&
44730       InVT == MVT::v16i32 && VT == MVT::v16i8) {
44731     if (auto USatVal = detectSSatPattern(In, VT, true)) {
44732       // Emit a VPACKUSDW+VPERMQ followed by a VPMOVUSWB.
44733       SDValue Mid = truncateVectorWithPACK(X86ISD::PACKUS, MVT::v16i16, USatVal,
44734                                            DL, DAG, Subtarget);
44735       assert(Mid && "Failed to pack!");
44736       return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, Mid);
44737     }
44738   }
44739 
44740   // vXi32 truncate instructions are available with AVX512F.
44741   // vXi16 truncate instructions are only available with AVX512BW.
44742   // For 256-bit or smaller vectors, we require VLX.
44743   // FIXME: We could widen truncates to 512 to remove the VLX restriction.
44744   // If the result type is 256-bits or larger and we have disable 512-bit
44745   // registers, we should go ahead and use the pack instructions if possible.
44746   bool PreferAVX512 = ((Subtarget.hasAVX512() && InSVT == MVT::i32) ||
44747                        (Subtarget.hasBWI() && InSVT == MVT::i16)) &&
44748                       (InVT.getSizeInBits() > 128) &&
44749                       (Subtarget.hasVLX() || InVT.getSizeInBits() > 256) &&
44750                       !(!Subtarget.useAVX512Regs() && VT.getSizeInBits() >= 256);
44751 
44752   if (isPowerOf2_32(VT.getVectorNumElements()) && !PreferAVX512 &&
44753       VT.getSizeInBits() >= 64 &&
44754       (SVT == MVT::i8 || SVT == MVT::i16) &&
44755       (InSVT == MVT::i16 || InSVT == MVT::i32)) {
44756     if (auto USatVal = detectSSatPattern(In, VT, true)) {
44757       // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
44758       // Only do this when the result is at least 64 bits or we'll leaving
44759       // dangling PACKSSDW nodes.
44760       if (SVT == MVT::i8 && InSVT == MVT::i32) {
44761         EVT MidVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
44762                                      VT.getVectorNumElements());
44763         SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
44764                                              DAG, Subtarget);
44765         assert(Mid && "Failed to pack!");
44766         SDValue V = truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
44767                                            Subtarget);
44768         assert(V && "Failed to pack!");
44769         return V;
44770       } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
44771         return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
44772                                       Subtarget);
44773     }
44774     if (auto SSatVal = detectSSatPattern(In, VT))
44775       return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
44776                                     Subtarget);
44777   }
44778 
44779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44780   if (TLI.isTypeLegal(InVT) && InVT.isVector() && SVT != MVT::i1 &&
44781       Subtarget.hasAVX512() && (InSVT != MVT::i16 || Subtarget.hasBWI())) {
44782     unsigned TruncOpc = 0;
44783     SDValue SatVal;
44784     if (auto SSatVal = detectSSatPattern(In, VT)) {
44785       SatVal = SSatVal;
44786       TruncOpc = X86ISD::VTRUNCS;
44787     } else if (auto USatVal = detectUSatPattern(In, VT, DAG, DL)) {
44788       SatVal = USatVal;
44789       TruncOpc = X86ISD::VTRUNCUS;
44790     }
44791     if (SatVal) {
44792       unsigned ResElts = VT.getVectorNumElements();
44793       // If the input type is less than 512 bits and we don't have VLX, we need
44794       // to widen to 512 bits.
44795       if (!Subtarget.hasVLX() && !InVT.is512BitVector()) {
44796         unsigned NumConcats = 512 / InVT.getSizeInBits();
44797         ResElts *= NumConcats;
44798         SmallVector<SDValue, 4> ConcatOps(NumConcats, DAG.getUNDEF(InVT));
44799         ConcatOps[0] = SatVal;
44800         InVT = EVT::getVectorVT(*DAG.getContext(), InSVT,
44801                                 NumConcats * InVT.getVectorNumElements());
44802         SatVal = DAG.getNode(ISD::CONCAT_VECTORS, DL, InVT, ConcatOps);
44803       }
44804       // Widen the result if its narrower than 128 bits.
44805       if (ResElts * SVT.getSizeInBits() < 128)
44806         ResElts = 128 / SVT.getSizeInBits();
44807       EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), SVT, ResElts);
44808       SDValue Res = DAG.getNode(TruncOpc, DL, TruncVT, SatVal);
44809       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
44810                          DAG.getIntPtrConstant(0, DL));
44811     }
44812   }
44813 
44814   return SDValue();
44815 }
44816 
44817 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
44818 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
44819 /// X86ISD::AVG instruction.
44820 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
44821                                 const X86Subtarget &Subtarget,
44822                                 const SDLoc &DL) {
44823   if (!VT.isVector())
44824     return SDValue();
44825   EVT InVT = In.getValueType();
44826   unsigned NumElems = VT.getVectorNumElements();
44827 
44828   EVT ScalarVT = VT.getVectorElementType();
44829   if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) && NumElems >= 2))
44830     return SDValue();
44831 
44832   // InScalarVT is the intermediate type in AVG pattern and it should be greater
44833   // than the original input type (i8/i16).
44834   EVT InScalarVT = InVT.getVectorElementType();
44835   if (InScalarVT.getFixedSizeInBits() <= ScalarVT.getFixedSizeInBits())
44836     return SDValue();
44837 
44838   if (!Subtarget.hasSSE2())
44839     return SDValue();
44840 
44841   // Detect the following pattern:
44842   //
44843   //   %1 = zext <N x i8> %a to <N x i32>
44844   //   %2 = zext <N x i8> %b to <N x i32>
44845   //   %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
44846   //   %4 = add nuw nsw <N x i32> %3, %2
44847   //   %5 = lshr <N x i32> %N, <i32 1 x N>
44848   //   %6 = trunc <N x i32> %5 to <N x i8>
44849   //
44850   // In AVX512, the last instruction can also be a trunc store.
44851   if (In.getOpcode() != ISD::SRL)
44852     return SDValue();
44853 
44854   // A lambda checking the given SDValue is a constant vector and each element
44855   // is in the range [Min, Max].
44856   auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
44857     return ISD::matchUnaryPredicate(V, [Min, Max](ConstantSDNode *C) {
44858       return !(C->getAPIntValue().ult(Min) || C->getAPIntValue().ugt(Max));
44859     });
44860   };
44861 
44862   // Check if each element of the vector is right-shifted by one.
44863   SDValue LHS = In.getOperand(0);
44864   SDValue RHS = In.getOperand(1);
44865   if (!IsConstVectorInRange(RHS, 1, 1))
44866     return SDValue();
44867   if (LHS.getOpcode() != ISD::ADD)
44868     return SDValue();
44869 
44870   // Detect a pattern of a + b + 1 where the order doesn't matter.
44871   SDValue Operands[3];
44872   Operands[0] = LHS.getOperand(0);
44873   Operands[1] = LHS.getOperand(1);
44874 
44875   auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
44876                        ArrayRef<SDValue> Ops) {
44877     return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
44878   };
44879 
44880   auto AVGSplitter = [&](SDValue Op0, SDValue Op1) {
44881     // Pad to a power-of-2 vector, split+apply and extract the original vector.
44882     unsigned NumElemsPow2 = PowerOf2Ceil(NumElems);
44883     EVT Pow2VT = EVT::getVectorVT(*DAG.getContext(), ScalarVT, NumElemsPow2);
44884     if (NumElemsPow2 != NumElems) {
44885       SmallVector<SDValue, 32> Ops0(NumElemsPow2, DAG.getUNDEF(ScalarVT));
44886       SmallVector<SDValue, 32> Ops1(NumElemsPow2, DAG.getUNDEF(ScalarVT));
44887       for (unsigned i = 0; i != NumElems; ++i) {
44888         SDValue Idx = DAG.getIntPtrConstant(i, DL);
44889         Ops0[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op0, Idx);
44890         Ops1[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, Op1, Idx);
44891       }
44892       Op0 = DAG.getBuildVector(Pow2VT, DL, Ops0);
44893       Op1 = DAG.getBuildVector(Pow2VT, DL, Ops1);
44894     }
44895     SDValue Res =
44896         SplitOpsAndApply(DAG, Subtarget, DL, Pow2VT, {Op0, Op1}, AVGBuilder);
44897     if (NumElemsPow2 == NumElems)
44898       return Res;
44899     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
44900                        DAG.getIntPtrConstant(0, DL));
44901   };
44902 
44903   // Take care of the case when one of the operands is a constant vector whose
44904   // element is in the range [1, 256].
44905   if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
44906       Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
44907       Operands[0].getOperand(0).getValueType() == VT) {
44908     // The pattern is detected. Subtract one from the constant vector, then
44909     // demote it and emit X86ISD::AVG instruction.
44910     SDValue VecOnes = DAG.getConstant(1, DL, InVT);
44911     Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
44912     Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
44913     return AVGSplitter(Operands[0].getOperand(0), Operands[1]);
44914   }
44915 
44916   // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
44917   // Match the or case only if its 'add-like' - can be replaced by an add.
44918   auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
44919     if (ISD::ADD == V.getOpcode()) {
44920       Op0 = V.getOperand(0);
44921       Op1 = V.getOperand(1);
44922       return true;
44923     }
44924     if (ISD::ZERO_EXTEND != V.getOpcode())
44925       return false;
44926     V = V.getOperand(0);
44927     if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
44928         !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
44929       return false;
44930     Op0 = V.getOperand(0);
44931     Op1 = V.getOperand(1);
44932     return true;
44933   };
44934 
44935   SDValue Op0, Op1;
44936   if (FindAddLike(Operands[0], Op0, Op1))
44937     std::swap(Operands[0], Operands[1]);
44938   else if (!FindAddLike(Operands[1], Op0, Op1))
44939     return SDValue();
44940   Operands[2] = Op0;
44941   Operands[1] = Op1;
44942 
44943   // Now we have three operands of two additions. Check that one of them is a
44944   // constant vector with ones, and the other two can be promoted from i8/i16.
44945   for (int i = 0; i < 3; ++i) {
44946     if (!IsConstVectorInRange(Operands[i], 1, 1))
44947       continue;
44948     std::swap(Operands[i], Operands[2]);
44949 
44950     // Check if Operands[0] and Operands[1] are results of type promotion.
44951     for (int j = 0; j < 2; ++j)
44952       if (Operands[j].getValueType() != VT) {
44953         if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
44954             Operands[j].getOperand(0).getValueType() != VT)
44955           return SDValue();
44956         Operands[j] = Operands[j].getOperand(0);
44957       }
44958 
44959     // The pattern is detected, emit X86ISD::AVG instruction(s).
44960     return AVGSplitter(Operands[0], Operands[1]);
44961   }
44962 
44963   return SDValue();
44964 }
44965 
44966 static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
44967                            TargetLowering::DAGCombinerInfo &DCI,
44968                            const X86Subtarget &Subtarget) {
44969   LoadSDNode *Ld = cast<LoadSDNode>(N);
44970   EVT RegVT = Ld->getValueType(0);
44971   EVT MemVT = Ld->getMemoryVT();
44972   SDLoc dl(Ld);
44973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
44974 
44975   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
44976   // into two 16-byte operations. Also split non-temporal aligned loads on
44977   // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
44978   ISD::LoadExtType Ext = Ld->getExtensionType();
44979   bool Fast;
44980   if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
44981       Ext == ISD::NON_EXTLOAD &&
44982       ((Ld->isNonTemporal() && !Subtarget.hasInt256() &&
44983         Ld->getAlignment() >= 16) ||
44984        (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
44985                                *Ld->getMemOperand(), &Fast) &&
44986         !Fast))) {
44987     unsigned NumElems = RegVT.getVectorNumElements();
44988     if (NumElems < 2)
44989       return SDValue();
44990 
44991     unsigned HalfOffset = 16;
44992     SDValue Ptr1 = Ld->getBasePtr();
44993     SDValue Ptr2 =
44994         DAG.getMemBasePlusOffset(Ptr1, TypeSize::Fixed(HalfOffset), dl);
44995     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
44996                                   NumElems / 2);
44997     SDValue Load1 =
44998         DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr1, Ld->getPointerInfo(),
44999                     Ld->getOriginalAlign(),
45000                     Ld->getMemOperand()->getFlags());
45001     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr2,
45002                                 Ld->getPointerInfo().getWithOffset(HalfOffset),
45003                                 Ld->getOriginalAlign(),
45004                                 Ld->getMemOperand()->getFlags());
45005     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
45006                              Load1.getValue(1), Load2.getValue(1));
45007 
45008     SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
45009     return DCI.CombineTo(N, NewVec, TF, true);
45010   }
45011 
45012   // Bool vector load - attempt to cast to an integer, as we have good
45013   // (vXiY *ext(vXi1 bitcast(iX))) handling.
45014   if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
45015       RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
45016     unsigned NumElts = RegVT.getVectorNumElements();
45017     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
45018     if (TLI.isTypeLegal(IntVT)) {
45019       SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
45020                                     Ld->getPointerInfo(),
45021                                     Ld->getOriginalAlign(),
45022                                     Ld->getMemOperand()->getFlags());
45023       SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
45024       return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
45025     }
45026   }
45027 
45028   // If we also broadcast this as a subvector to a wider type, then just extract
45029   // the lowest subvector.
45030   if (Ext == ISD::NON_EXTLOAD && Subtarget.hasAVX() && Ld->isSimple() &&
45031       (RegVT.is128BitVector() || RegVT.is256BitVector())) {
45032     SDValue Ptr = Ld->getBasePtr();
45033     SDValue Chain = Ld->getChain();
45034     for (SDNode *User : Ptr->uses()) {
45035       if (User != N && User->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
45036           cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
45037           cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
45038           cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
45039               MemVT.getSizeInBits() &&
45040           !User->hasAnyUseOfValue(1) &&
45041           User->getValueSizeInBits(0).getFixedSize() >
45042               RegVT.getFixedSizeInBits()) {
45043         SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
45044                                            RegVT.getSizeInBits());
45045         Extract = DAG.getBitcast(RegVT, Extract);
45046         return DCI.CombineTo(N, Extract, SDValue(User, 1));
45047       }
45048     }
45049   }
45050 
45051   // Cast ptr32 and ptr64 pointers to the default address space before a load.
45052   unsigned AddrSpace = Ld->getAddressSpace();
45053   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
45054       AddrSpace == X86AS::PTR32_UPTR) {
45055     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
45056     if (PtrVT != Ld->getBasePtr().getSimpleValueType()) {
45057       SDValue Cast =
45058           DAG.getAddrSpaceCast(dl, PtrVT, Ld->getBasePtr(), AddrSpace, 0);
45059       return DAG.getLoad(RegVT, dl, Ld->getChain(), Cast, Ld->getPointerInfo(),
45060                          Ld->getOriginalAlign(),
45061                          Ld->getMemOperand()->getFlags());
45062     }
45063   }
45064 
45065   return SDValue();
45066 }
45067 
45068 /// If V is a build vector of boolean constants and exactly one of those
45069 /// constants is true, return the operand index of that true element.
45070 /// Otherwise, return -1.
45071 static int getOneTrueElt(SDValue V) {
45072   // This needs to be a build vector of booleans.
45073   // TODO: Checking for the i1 type matches the IR definition for the mask,
45074   // but the mask check could be loosened to i8 or other types. That might
45075   // also require checking more than 'allOnesValue'; eg, the x86 HW
45076   // instructions only require that the MSB is set for each mask element.
45077   // The ISD::MSTORE comments/definition do not specify how the mask operand
45078   // is formatted.
45079   auto *BV = dyn_cast<BuildVectorSDNode>(V);
45080   if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
45081     return -1;
45082 
45083   int TrueIndex = -1;
45084   unsigned NumElts = BV->getValueType(0).getVectorNumElements();
45085   for (unsigned i = 0; i < NumElts; ++i) {
45086     const SDValue &Op = BV->getOperand(i);
45087     if (Op.isUndef())
45088       continue;
45089     auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
45090     if (!ConstNode)
45091       return -1;
45092     if (ConstNode->getAPIntValue().countTrailingOnes() >= 1) {
45093       // If we already found a one, this is too many.
45094       if (TrueIndex >= 0)
45095         return -1;
45096       TrueIndex = i;
45097     }
45098   }
45099   return TrueIndex;
45100 }
45101 
45102 /// Given a masked memory load/store operation, return true if it has one mask
45103 /// bit set. If it has one mask bit set, then also return the memory address of
45104 /// the scalar element to load/store, the vector index to insert/extract that
45105 /// scalar element, and the alignment for the scalar memory access.
45106 static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
45107                                          SelectionDAG &DAG, SDValue &Addr,
45108                                          SDValue &Index, Align &Alignment,
45109                                          unsigned &Offset) {
45110   int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
45111   if (TrueMaskElt < 0)
45112     return false;
45113 
45114   // Get the address of the one scalar element that is specified by the mask
45115   // using the appropriate offset from the base pointer.
45116   EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
45117   Offset = 0;
45118   Addr = MaskedOp->getBasePtr();
45119   if (TrueMaskElt != 0) {
45120     Offset = TrueMaskElt * EltVT.getStoreSize();
45121     Addr = DAG.getMemBasePlusOffset(Addr, TypeSize::Fixed(Offset),
45122                                     SDLoc(MaskedOp));
45123   }
45124 
45125   Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
45126   Alignment = commonAlignment(MaskedOp->getOriginalAlign(),
45127                               EltVT.getStoreSize());
45128   return true;
45129 }
45130 
45131 /// If exactly one element of the mask is set for a non-extending masked load,
45132 /// it is a scalar load and vector insert.
45133 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
45134 /// mask have already been optimized in IR, so we don't bother with those here.
45135 static SDValue
45136 reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
45137                              TargetLowering::DAGCombinerInfo &DCI,
45138                              const X86Subtarget &Subtarget) {
45139   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
45140   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
45141   // However, some target hooks may need to be added to know when the transform
45142   // is profitable. Endianness would also have to be considered.
45143 
45144   SDValue Addr, VecIndex;
45145   Align Alignment;
45146   unsigned Offset;
45147   if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment, Offset))
45148     return SDValue();
45149 
45150   // Load the one scalar element that is specified by the mask using the
45151   // appropriate offset from the base pointer.
45152   SDLoc DL(ML);
45153   EVT VT = ML->getValueType(0);
45154   EVT EltVT = VT.getVectorElementType();
45155 
45156   EVT CastVT = VT;
45157   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
45158     EltVT = MVT::f64;
45159     CastVT =
45160         EVT::getVectorVT(*DAG.getContext(), EltVT, VT.getVectorNumElements());
45161   }
45162 
45163   SDValue Load =
45164       DAG.getLoad(EltVT, DL, ML->getChain(), Addr,
45165                   ML->getPointerInfo().getWithOffset(Offset),
45166                   Alignment, ML->getMemOperand()->getFlags());
45167 
45168   SDValue PassThru = DAG.getBitcast(CastVT, ML->getPassThru());
45169 
45170   // Insert the loaded element into the appropriate place in the vector.
45171   SDValue Insert =
45172       DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, CastVT, PassThru, Load, VecIndex);
45173   Insert = DAG.getBitcast(VT, Insert);
45174   return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
45175 }
45176 
45177 static SDValue
45178 combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
45179                               TargetLowering::DAGCombinerInfo &DCI) {
45180   assert(ML->isUnindexed() && "Unexpected indexed masked load!");
45181   if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
45182     return SDValue();
45183 
45184   SDLoc DL(ML);
45185   EVT VT = ML->getValueType(0);
45186 
45187   // If we are loading the first and last elements of a vector, it is safe and
45188   // always faster to load the whole vector. Replace the masked load with a
45189   // vector load and select.
45190   unsigned NumElts = VT.getVectorNumElements();
45191   BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
45192   bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
45193   bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
45194   if (LoadFirstElt && LoadLastElt) {
45195     SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
45196                                 ML->getMemOperand());
45197     SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
45198                                   ML->getPassThru());
45199     return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
45200   }
45201 
45202   // Convert a masked load with a constant mask into a masked load and a select.
45203   // This allows the select operation to use a faster kind of select instruction
45204   // (for example, vblendvps -> vblendps).
45205 
45206   // Don't try this if the pass-through operand is already undefined. That would
45207   // cause an infinite loop because that's what we're about to create.
45208   if (ML->getPassThru().isUndef())
45209     return SDValue();
45210 
45211   if (ISD::isBuildVectorAllZeros(ML->getPassThru().getNode()))
45212     return SDValue();
45213 
45214   // The new masked load has an undef pass-through operand. The select uses the
45215   // original pass-through operand.
45216   SDValue NewML = DAG.getMaskedLoad(
45217       VT, DL, ML->getChain(), ML->getBasePtr(), ML->getOffset(), ML->getMask(),
45218       DAG.getUNDEF(VT), ML->getMemoryVT(), ML->getMemOperand(),
45219       ML->getAddressingMode(), ML->getExtensionType());
45220   SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
45221                                 ML->getPassThru());
45222 
45223   return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
45224 }
45225 
45226 static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
45227                                  TargetLowering::DAGCombinerInfo &DCI,
45228                                  const X86Subtarget &Subtarget) {
45229   auto *Mld = cast<MaskedLoadSDNode>(N);
45230 
45231   // TODO: Expanding load with constant mask may be optimized as well.
45232   if (Mld->isExpandingLoad())
45233     return SDValue();
45234 
45235   if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
45236     if (SDValue ScalarLoad =
45237             reduceMaskedLoadToScalarLoad(Mld, DAG, DCI, Subtarget))
45238       return ScalarLoad;
45239 
45240     // TODO: Do some AVX512 subsets benefit from this transform?
45241     if (!Subtarget.hasAVX512())
45242       if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
45243         return Blend;
45244   }
45245 
45246   // If the mask value has been legalized to a non-boolean vector, try to
45247   // simplify ops leading up to it. We only demand the MSB of each lane.
45248   SDValue Mask = Mld->getMask();
45249   if (Mask.getScalarValueSizeInBits() != 1) {
45250     EVT VT = Mld->getValueType(0);
45251     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45252     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
45253     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
45254       if (N->getOpcode() != ISD::DELETED_NODE)
45255         DCI.AddToWorklist(N);
45256       return SDValue(N, 0);
45257     }
45258     if (SDValue NewMask =
45259             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
45260       return DAG.getMaskedLoad(
45261           VT, SDLoc(N), Mld->getChain(), Mld->getBasePtr(), Mld->getOffset(),
45262           NewMask, Mld->getPassThru(), Mld->getMemoryVT(), Mld->getMemOperand(),
45263           Mld->getAddressingMode(), Mld->getExtensionType());
45264   }
45265 
45266   return SDValue();
45267 }
45268 
45269 /// If exactly one element of the mask is set for a non-truncating masked store,
45270 /// it is a vector extract and scalar store.
45271 /// Note: It is expected that the degenerate cases of an all-zeros or all-ones
45272 /// mask have already been optimized in IR, so we don't bother with those here.
45273 static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
45274                                               SelectionDAG &DAG,
45275                                               const X86Subtarget &Subtarget) {
45276   // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
45277   // However, some target hooks may need to be added to know when the transform
45278   // is profitable. Endianness would also have to be considered.
45279 
45280   SDValue Addr, VecIndex;
45281   Align Alignment;
45282   unsigned Offset;
45283   if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment, Offset))
45284     return SDValue();
45285 
45286   // Extract the one scalar element that is actually being stored.
45287   SDLoc DL(MS);
45288   SDValue Value = MS->getValue();
45289   EVT VT = Value.getValueType();
45290   EVT EltVT = VT.getVectorElementType();
45291   if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
45292     EltVT = MVT::f64;
45293     EVT CastVT =
45294         EVT::getVectorVT(*DAG.getContext(), EltVT, VT.getVectorNumElements());
45295     Value = DAG.getBitcast(CastVT, Value);
45296   }
45297   SDValue Extract =
45298       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Value, VecIndex);
45299 
45300   // Store that element at the appropriate offset from the base pointer.
45301   return DAG.getStore(MS->getChain(), DL, Extract, Addr,
45302                       MS->getPointerInfo().getWithOffset(Offset),
45303                       Alignment, MS->getMemOperand()->getFlags());
45304 }
45305 
45306 static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
45307                                   TargetLowering::DAGCombinerInfo &DCI,
45308                                   const X86Subtarget &Subtarget) {
45309   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
45310   if (Mst->isCompressingStore())
45311     return SDValue();
45312 
45313   EVT VT = Mst->getValue().getValueType();
45314   SDLoc dl(Mst);
45315   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45316 
45317   if (Mst->isTruncatingStore())
45318     return SDValue();
45319 
45320   if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG, Subtarget))
45321     return ScalarStore;
45322 
45323   // If the mask value has been legalized to a non-boolean vector, try to
45324   // simplify ops leading up to it. We only demand the MSB of each lane.
45325   SDValue Mask = Mst->getMask();
45326   if (Mask.getScalarValueSizeInBits() != 1) {
45327     APInt DemandedBits(APInt::getSignMask(VT.getScalarSizeInBits()));
45328     if (TLI.SimplifyDemandedBits(Mask, DemandedBits, DCI)) {
45329       if (N->getOpcode() != ISD::DELETED_NODE)
45330         DCI.AddToWorklist(N);
45331       return SDValue(N, 0);
45332     }
45333     if (SDValue NewMask =
45334             TLI.SimplifyMultipleUseDemandedBits(Mask, DemandedBits, DAG))
45335       return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Mst->getValue(),
45336                                 Mst->getBasePtr(), Mst->getOffset(), NewMask,
45337                                 Mst->getMemoryVT(), Mst->getMemOperand(),
45338                                 Mst->getAddressingMode());
45339   }
45340 
45341   SDValue Value = Mst->getValue();
45342   if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
45343       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
45344                             Mst->getMemoryVT())) {
45345     return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
45346                               Mst->getBasePtr(), Mst->getOffset(), Mask,
45347                               Mst->getMemoryVT(), Mst->getMemOperand(),
45348                               Mst->getAddressingMode(), true);
45349   }
45350 
45351   return SDValue();
45352 }
45353 
45354 static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
45355                             TargetLowering::DAGCombinerInfo &DCI,
45356                             const X86Subtarget &Subtarget) {
45357   StoreSDNode *St = cast<StoreSDNode>(N);
45358   EVT StVT = St->getMemoryVT();
45359   SDLoc dl(St);
45360   SDValue StoredVal = St->getValue();
45361   EVT VT = StoredVal.getValueType();
45362   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45363 
45364   // Convert a store of vXi1 into a store of iX and a bitcast.
45365   if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
45366       VT.getVectorElementType() == MVT::i1) {
45367 
45368     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
45369     StoredVal = DAG.getBitcast(NewVT, StoredVal);
45370 
45371     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
45372                         St->getPointerInfo(), St->getOriginalAlign(),
45373                         St->getMemOperand()->getFlags());
45374   }
45375 
45376   // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
45377   // This will avoid a copy to k-register.
45378   if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
45379       StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
45380       StoredVal.getOperand(0).getValueType() == MVT::i8) {
45381     SDValue Val = StoredVal.getOperand(0);
45382     // We must store zeros to the unused bits.
45383     Val = DAG.getZeroExtendInReg(Val, dl, MVT::i1);
45384     return DAG.getStore(St->getChain(), dl, Val,
45385                         St->getBasePtr(), St->getPointerInfo(),
45386                         St->getOriginalAlign(),
45387                         St->getMemOperand()->getFlags());
45388   }
45389 
45390   // Widen v2i1/v4i1 stores to v8i1.
45391   if ((VT == MVT::v1i1 || VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
45392       Subtarget.hasAVX512()) {
45393     unsigned NumConcats = 8 / VT.getVectorNumElements();
45394     // We must store zeros to the unused bits.
45395     SmallVector<SDValue, 4> Ops(NumConcats, DAG.getConstant(0, dl, VT));
45396     Ops[0] = StoredVal;
45397     StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
45398     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
45399                         St->getPointerInfo(), St->getOriginalAlign(),
45400                         St->getMemOperand()->getFlags());
45401   }
45402 
45403   // Turn vXi1 stores of constants into a scalar store.
45404   if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
45405        VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
45406       ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
45407     // If its a v64i1 store without 64-bit support, we need two stores.
45408     if (!DCI.isBeforeLegalize() && VT == MVT::v64i1 && !Subtarget.is64Bit()) {
45409       SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
45410                                       StoredVal->ops().slice(0, 32));
45411       Lo = combinevXi1ConstantToInteger(Lo, DAG);
45412       SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
45413                                       StoredVal->ops().slice(32, 32));
45414       Hi = combinevXi1ConstantToInteger(Hi, DAG);
45415 
45416       SDValue Ptr0 = St->getBasePtr();
45417       SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, TypeSize::Fixed(4), dl);
45418 
45419       SDValue Ch0 =
45420           DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
45421                        St->getOriginalAlign(),
45422                        St->getMemOperand()->getFlags());
45423       SDValue Ch1 =
45424           DAG.getStore(St->getChain(), dl, Hi, Ptr1,
45425                        St->getPointerInfo().getWithOffset(4),
45426                        St->getOriginalAlign(),
45427                        St->getMemOperand()->getFlags());
45428       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
45429     }
45430 
45431     StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
45432     return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
45433                         St->getPointerInfo(), St->getOriginalAlign(),
45434                         St->getMemOperand()->getFlags());
45435   }
45436 
45437   // If we are saving a 32-byte vector and 32-byte stores are slow, such as on
45438   // Sandy Bridge, perform two 16-byte stores.
45439   bool Fast;
45440   if (VT.is256BitVector() && StVT == VT &&
45441       TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
45442                              *St->getMemOperand(), &Fast) &&
45443       !Fast) {
45444     unsigned NumElems = VT.getVectorNumElements();
45445     if (NumElems < 2)
45446       return SDValue();
45447 
45448     return splitVectorStore(St, DAG);
45449   }
45450 
45451   // Split under-aligned vector non-temporal stores.
45452   if (St->isNonTemporal() && StVT == VT &&
45453       St->getAlignment() < VT.getStoreSize()) {
45454     // ZMM/YMM nt-stores - either it can be stored as a series of shorter
45455     // vectors or the legalizer can scalarize it to use MOVNTI.
45456     if (VT.is256BitVector() || VT.is512BitVector()) {
45457       unsigned NumElems = VT.getVectorNumElements();
45458       if (NumElems < 2)
45459         return SDValue();
45460       return splitVectorStore(St, DAG);
45461     }
45462 
45463     // XMM nt-stores - scalarize this to f64 nt-stores on SSE4A, else i32/i64
45464     // to use MOVNTI.
45465     if (VT.is128BitVector() && Subtarget.hasSSE2()) {
45466       MVT NTVT = Subtarget.hasSSE4A()
45467                      ? MVT::v2f64
45468                      : (TLI.isTypeLegal(MVT::i64) ? MVT::v2i64 : MVT::v4i32);
45469       return scalarizeVectorStore(St, NTVT, DAG);
45470     }
45471   }
45472 
45473   // Try to optimize v16i16->v16i8 truncating stores when BWI is not
45474   // supported, but avx512f is by extending to v16i32 and truncating.
45475   if (!St->isTruncatingStore() && VT == MVT::v16i8 && !Subtarget.hasBWI() &&
45476       St->getValue().getOpcode() == ISD::TRUNCATE &&
45477       St->getValue().getOperand(0).getValueType() == MVT::v16i16 &&
45478       TLI.isTruncStoreLegal(MVT::v16i32, MVT::v16i8) &&
45479       St->getValue().hasOneUse() && !DCI.isBeforeLegalizeOps()) {
45480     SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v16i32, St->getValue());
45481     return DAG.getTruncStore(St->getChain(), dl, Ext, St->getBasePtr(),
45482                              MVT::v16i8, St->getMemOperand());
45483   }
45484 
45485   // Try to fold a VTRUNCUS or VTRUNCS into a truncating store.
45486   if (!St->isTruncatingStore() && StoredVal.hasOneUse() &&
45487       (StoredVal.getOpcode() == X86ISD::VTRUNCUS ||
45488        StoredVal.getOpcode() == X86ISD::VTRUNCS) &&
45489       TLI.isTruncStoreLegal(StoredVal.getOperand(0).getValueType(), VT)) {
45490     bool IsSigned = StoredVal.getOpcode() == X86ISD::VTRUNCS;
45491     return EmitTruncSStore(IsSigned, St->getChain(),
45492                            dl, StoredVal.getOperand(0), St->getBasePtr(),
45493                            VT, St->getMemOperand(), DAG);
45494   }
45495 
45496   // Try to fold a extract_element(VTRUNC) pattern into a truncating store.
45497   if (!St->isTruncatingStore() && StoredVal.hasOneUse()) {
45498     auto IsExtractedElement = [](SDValue V) {
45499       if (V.getOpcode() == ISD::TRUNCATE && V.getOperand(0).hasOneUse())
45500         V = V.getOperand(0);
45501       unsigned Opc = V.getOpcode();
45502       if (Opc == ISD::EXTRACT_VECTOR_ELT || Opc == X86ISD::PEXTRW) {
45503         if (V.getOperand(0).hasOneUse() && isNullConstant(V.getOperand(1)))
45504           return V.getOperand(0);
45505       }
45506       return SDValue();
45507     };
45508     if (SDValue Extract = IsExtractedElement(StoredVal)) {
45509       SDValue Trunc = peekThroughOneUseBitcasts(Extract);
45510       if (Trunc.getOpcode() == X86ISD::VTRUNC) {
45511         SDValue Src = Trunc.getOperand(0);
45512         MVT DstVT = Trunc.getSimpleValueType();
45513         MVT SrcVT = Src.getSimpleValueType();
45514         unsigned NumSrcElts = SrcVT.getVectorNumElements();
45515         unsigned NumTruncBits = DstVT.getScalarSizeInBits() * NumSrcElts;
45516         MVT TruncVT = MVT::getVectorVT(DstVT.getScalarType(), NumSrcElts);
45517         if (NumTruncBits == VT.getSizeInBits() &&
45518             TLI.isTruncStoreLegal(SrcVT, TruncVT)) {
45519           return DAG.getTruncStore(St->getChain(), dl, Src, St->getBasePtr(),
45520                                    TruncVT, St->getMemOperand());
45521         }
45522       }
45523     }
45524   }
45525 
45526   // Optimize trunc store (of multiple scalars) to shuffle and store.
45527   // First, pack all of the elements in one place. Next, store to memory
45528   // in fewer chunks.
45529   if (St->isTruncatingStore() && VT.isVector()) {
45530     // Check if we can detect an AVG pattern from the truncation. If yes,
45531     // replace the trunc store by a normal store with the result of X86ISD::AVG
45532     // instruction.
45533     if (DCI.isBeforeLegalize() || TLI.isTypeLegal(St->getMemoryVT()))
45534       if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
45535                                          Subtarget, dl))
45536         return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
45537                             St->getPointerInfo(), St->getOriginalAlign(),
45538                             St->getMemOperand()->getFlags());
45539 
45540     if (TLI.isTruncStoreLegal(VT, StVT)) {
45541       if (SDValue Val = detectSSatPattern(St->getValue(), St->getMemoryVT()))
45542         return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
45543                                dl, Val, St->getBasePtr(),
45544                                St->getMemoryVT(), St->getMemOperand(), DAG);
45545       if (SDValue Val = detectUSatPattern(St->getValue(), St->getMemoryVT(),
45546                                           DAG, dl))
45547         return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
45548                                dl, Val, St->getBasePtr(),
45549                                St->getMemoryVT(), St->getMemOperand(), DAG);
45550     }
45551 
45552     return SDValue();
45553   }
45554 
45555   // Cast ptr32 and ptr64 pointers to the default address space before a store.
45556   unsigned AddrSpace = St->getAddressSpace();
45557   if (AddrSpace == X86AS::PTR64 || AddrSpace == X86AS::PTR32_SPTR ||
45558       AddrSpace == X86AS::PTR32_UPTR) {
45559     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
45560     if (PtrVT != St->getBasePtr().getSimpleValueType()) {
45561       SDValue Cast =
45562           DAG.getAddrSpaceCast(dl, PtrVT, St->getBasePtr(), AddrSpace, 0);
45563       return DAG.getStore(St->getChain(), dl, StoredVal, Cast,
45564                           St->getPointerInfo(), St->getOriginalAlign(),
45565                           St->getMemOperand()->getFlags(), St->getAAInfo());
45566     }
45567   }
45568 
45569   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
45570   // the FP state in cases where an emms may be missing.
45571   // A preferable solution to the general problem is to figure out the right
45572   // places to insert EMMS.  This qualifies as a quick hack.
45573 
45574   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
45575   if (VT.getSizeInBits() != 64)
45576     return SDValue();
45577 
45578   const Function &F = DAG.getMachineFunction().getFunction();
45579   bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
45580   bool F64IsLegal =
45581       !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
45582   if ((VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit()) &&
45583       isa<LoadSDNode>(St->getValue()) &&
45584       cast<LoadSDNode>(St->getValue())->isSimple() &&
45585       St->getChain().hasOneUse() && St->isSimple()) {
45586     LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
45587 
45588     if (!ISD::isNormalLoad(Ld))
45589       return SDValue();
45590 
45591     // Avoid the transformation if there are multiple uses of the loaded value.
45592     if (!Ld->hasNUsesOfValue(1, 0))
45593       return SDValue();
45594 
45595     SDLoc LdDL(Ld);
45596     SDLoc StDL(N);
45597     // Lower to a single movq load/store pair.
45598     SDValue NewLd = DAG.getLoad(MVT::f64, LdDL, Ld->getChain(),
45599                                 Ld->getBasePtr(), Ld->getMemOperand());
45600 
45601     // Make sure new load is placed in same chain order.
45602     DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
45603     return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
45604                         St->getMemOperand());
45605   }
45606 
45607   // This is similar to the above case, but here we handle a scalar 64-bit
45608   // integer store that is extracted from a vector on a 32-bit target.
45609   // If we have SSE2, then we can treat it like a floating-point double
45610   // to get past legalization. The execution dependencies fixup pass will
45611   // choose the optimal machine instruction for the store if this really is
45612   // an integer or v2f32 rather than an f64.
45613   if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
45614       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
45615     SDValue OldExtract = St->getOperand(1);
45616     SDValue ExtOp0 = OldExtract.getOperand(0);
45617     unsigned VecSize = ExtOp0.getValueSizeInBits();
45618     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
45619     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
45620     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
45621                                      BitCast, OldExtract.getOperand(1));
45622     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
45623                         St->getPointerInfo(), St->getOriginalAlign(),
45624                         St->getMemOperand()->getFlags());
45625   }
45626 
45627   return SDValue();
45628 }
45629 
45630 static SDValue combineVEXTRACT_STORE(SDNode *N, SelectionDAG &DAG,
45631                                      TargetLowering::DAGCombinerInfo &DCI,
45632                                      const X86Subtarget &Subtarget) {
45633   auto *St = cast<MemIntrinsicSDNode>(N);
45634 
45635   SDValue StoredVal = N->getOperand(1);
45636   MVT VT = StoredVal.getSimpleValueType();
45637   EVT MemVT = St->getMemoryVT();
45638 
45639   // Figure out which elements we demand.
45640   unsigned StElts = MemVT.getSizeInBits() / VT.getScalarSizeInBits();
45641   APInt DemandedElts = APInt::getLowBitsSet(VT.getVectorNumElements(), StElts);
45642 
45643   APInt KnownUndef, KnownZero;
45644   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45645   if (TLI.SimplifyDemandedVectorElts(StoredVal, DemandedElts, KnownUndef,
45646                                      KnownZero, DCI)) {
45647     if (N->getOpcode() != ISD::DELETED_NODE)
45648       DCI.AddToWorklist(N);
45649     return SDValue(N, 0);
45650   }
45651 
45652   return SDValue();
45653 }
45654 
45655 /// Return 'true' if this vector operation is "horizontal"
45656 /// and return the operands for the horizontal operation in LHS and RHS.  A
45657 /// horizontal operation performs the binary operation on successive elements
45658 /// of its first operand, then on successive elements of its second operand,
45659 /// returning the resulting values in a vector.  For example, if
45660 ///   A = < float a0, float a1, float a2, float a3 >
45661 /// and
45662 ///   B = < float b0, float b1, float b2, float b3 >
45663 /// then the result of doing a horizontal operation on A and B is
45664 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
45665 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
45666 /// A horizontal-op B, for some already available A and B, and if so then LHS is
45667 /// set to A, RHS to B, and the routine returns 'true'.
45668 static bool isHorizontalBinOp(unsigned HOpcode, SDValue &LHS, SDValue &RHS,
45669                               SelectionDAG &DAG, const X86Subtarget &Subtarget,
45670                               bool IsCommutative,
45671                               SmallVectorImpl<int> &PostShuffleMask) {
45672   // If either operand is undef, bail out. The binop should be simplified.
45673   if (LHS.isUndef() || RHS.isUndef())
45674     return false;
45675 
45676   // Look for the following pattern:
45677   //   A = < float a0, float a1, float a2, float a3 >
45678   //   B = < float b0, float b1, float b2, float b3 >
45679   // and
45680   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
45681   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
45682   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
45683   // which is A horizontal-op B.
45684 
45685   MVT VT = LHS.getSimpleValueType();
45686   assert((VT.is128BitVector() || VT.is256BitVector()) &&
45687          "Unsupported vector type for horizontal add/sub");
45688   unsigned NumElts = VT.getVectorNumElements();
45689 
45690   // TODO - can we make a general helper method that does all of this for us?
45691   auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
45692                         SmallVectorImpl<int> &ShuffleMask) {
45693     if (Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
45694       if (!Op.getOperand(0).isUndef())
45695         N0 = Op.getOperand(0);
45696       if (!Op.getOperand(1).isUndef())
45697         N1 = Op.getOperand(1);
45698       ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
45699       ShuffleMask.append(Mask.begin(), Mask.end());
45700       return;
45701     }
45702     bool UseSubVector = false;
45703     if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
45704         Op.getOperand(0).getValueType().is256BitVector() &&
45705         llvm::isNullConstant(Op.getOperand(1))) {
45706       Op = Op.getOperand(0);
45707       UseSubVector = true;
45708     }
45709     bool IsUnary;
45710     SmallVector<SDValue, 2> SrcOps;
45711     SmallVector<int, 16> SrcShuffleMask;
45712     SDValue BC = peekThroughBitcasts(Op);
45713     if (isTargetShuffle(BC.getOpcode()) &&
45714         getTargetShuffleMask(BC.getNode(), BC.getSimpleValueType(), false,
45715                              SrcOps, SrcShuffleMask, IsUnary)) {
45716       if (!UseSubVector && SrcShuffleMask.size() == NumElts &&
45717           SrcOps.size() <= 2) {
45718         N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
45719         N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
45720         ShuffleMask.append(SrcShuffleMask.begin(), SrcShuffleMask.end());
45721       }
45722       if (UseSubVector && (SrcShuffleMask.size() == (NumElts * 2)) &&
45723           SrcOps.size() == 1) {
45724         N0 = extract128BitVector(SrcOps[0], 0, DAG, SDLoc(Op));
45725         N1 = extract128BitVector(SrcOps[0], NumElts, DAG, SDLoc(Op));
45726         ArrayRef<int> Mask = ArrayRef<int>(SrcShuffleMask).slice(0, NumElts);
45727         ShuffleMask.append(Mask.begin(), Mask.end());
45728       }
45729     }
45730   };
45731 
45732   // View LHS in the form
45733   //   LHS = VECTOR_SHUFFLE A, B, LMask
45734   // If LHS is not a shuffle, then pretend it is the identity shuffle:
45735   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
45736   // NOTE: A default initialized SDValue represents an UNDEF of type VT.
45737   SDValue A, B;
45738   SmallVector<int, 16> LMask;
45739   GetShuffle(LHS, A, B, LMask);
45740 
45741   // Likewise, view RHS in the form
45742   //   RHS = VECTOR_SHUFFLE C, D, RMask
45743   SDValue C, D;
45744   SmallVector<int, 16> RMask;
45745   GetShuffle(RHS, C, D, RMask);
45746 
45747   // At least one of the operands should be a vector shuffle.
45748   unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
45749   if (NumShuffles == 0)
45750     return false;
45751 
45752   if (LMask.empty()) {
45753     A = LHS;
45754     for (unsigned i = 0; i != NumElts; ++i)
45755       LMask.push_back(i);
45756   }
45757 
45758   if (RMask.empty()) {
45759     C = RHS;
45760     for (unsigned i = 0; i != NumElts; ++i)
45761       RMask.push_back(i);
45762   }
45763 
45764   // If A and B occur in reverse order in RHS, then canonicalize by commuting
45765   // RHS operands and shuffle mask.
45766   if (A != C) {
45767     std::swap(C, D);
45768     ShuffleVectorSDNode::commuteMask(RMask);
45769   }
45770   // Check that the shuffles are both shuffling the same vectors.
45771   if (!(A == C && B == D))
45772     return false;
45773 
45774   PostShuffleMask.clear();
45775   PostShuffleMask.append(NumElts, SM_SentinelUndef);
45776 
45777   // LHS and RHS are now:
45778   //   LHS = shuffle A, B, LMask
45779   //   RHS = shuffle A, B, RMask
45780   // Check that the masks correspond to performing a horizontal operation.
45781   // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
45782   // so we just repeat the inner loop if this is a 256-bit op.
45783   unsigned Num128BitChunks = VT.getSizeInBits() / 128;
45784   unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
45785   unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
45786   assert((NumEltsPer128BitChunk % 2 == 0) &&
45787          "Vector type should have an even number of elements in each lane");
45788   for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
45789     for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
45790       // Ignore undefined components.
45791       int LIdx = LMask[i + j], RIdx = RMask[i + j];
45792       if (LIdx < 0 || RIdx < 0 ||
45793           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
45794           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
45795         continue;
45796 
45797       // Check that successive odd/even elements are being operated on. If not,
45798       // this is not a horizontal operation.
45799       if (!((RIdx & 1) == 1 && (LIdx + 1) == RIdx) &&
45800           !((LIdx & 1) == 1 && (RIdx + 1) == LIdx && IsCommutative))
45801         return false;
45802 
45803       // Compute the post-shuffle mask index based on where the element
45804       // is stored in the HOP result, and where it needs to be moved to.
45805       int Base = LIdx & ~1u;
45806       int Index = ((Base % NumEltsPer128BitChunk) / 2) +
45807                   ((Base % NumElts) & ~(NumEltsPer128BitChunk - 1));
45808 
45809       // The  low half of the 128-bit result must choose from A.
45810       // The high half of the 128-bit result must choose from B,
45811       // unless B is undef. In that case, we are always choosing from A.
45812       if ((B && Base >= (int)NumElts) || (!B && i >= NumEltsPer64BitChunk))
45813         Index += NumEltsPer64BitChunk;
45814       PostShuffleMask[i + j] = Index;
45815     }
45816   }
45817 
45818   SDValue NewLHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
45819   SDValue NewRHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
45820 
45821   bool IsIdentityPostShuffle =
45822       isSequentialOrUndefInRange(PostShuffleMask, 0, NumElts, 0);
45823   if (IsIdentityPostShuffle)
45824     PostShuffleMask.clear();
45825 
45826   // Avoid 128-bit multi lane shuffles if pre-AVX2 and FP (integer will split).
45827   if (!IsIdentityPostShuffle && !Subtarget.hasAVX2() && VT.isFloatingPoint() &&
45828       isMultiLaneShuffleMask(128, VT.getScalarSizeInBits(), PostShuffleMask))
45829     return false;
45830 
45831   // If the source nodes are already used in HorizOps then always accept this.
45832   // Shuffle folding should merge these back together.
45833   bool FoundHorizLHS = llvm::any_of(NewLHS->uses(), [&](SDNode *User) {
45834     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
45835   });
45836   bool FoundHorizRHS = llvm::any_of(NewRHS->uses(), [&](SDNode *User) {
45837     return User->getOpcode() == HOpcode && User->getValueType(0) == VT;
45838   });
45839   bool ForceHorizOp = FoundHorizLHS && FoundHorizRHS;
45840 
45841   // Assume a SingleSource HOP if we only shuffle one input and don't need to
45842   // shuffle the result.
45843   if (!ForceHorizOp &&
45844       !shouldUseHorizontalOp(NewLHS == NewRHS &&
45845                                  (NumShuffles < 2 || !IsIdentityPostShuffle),
45846                              DAG, Subtarget))
45847     return false;
45848 
45849   LHS = DAG.getBitcast(VT, NewLHS);
45850   RHS = DAG.getBitcast(VT, NewRHS);
45851   return true;
45852 }
45853 
45854 /// Do target-specific dag combines on floating-point adds/subs.
45855 static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
45856                                const X86Subtarget &Subtarget) {
45857   EVT VT = N->getValueType(0);
45858   SDValue LHS = N->getOperand(0);
45859   SDValue RHS = N->getOperand(1);
45860   bool IsFadd = N->getOpcode() == ISD::FADD;
45861   auto HorizOpcode = IsFadd ? X86ISD::FHADD : X86ISD::FHSUB;
45862   assert((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode");
45863 
45864   // Try to synthesize horizontal add/sub from adds/subs of shuffles.
45865   SmallVector<int, 8> PostShuffleMask;
45866   if (((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
45867        (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
45868       isHorizontalBinOp(HorizOpcode, LHS, RHS, DAG, Subtarget, IsFadd,
45869                         PostShuffleMask)) {
45870     SDValue HorizBinOp = DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
45871     if (!PostShuffleMask.empty())
45872       HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
45873                                         DAG.getUNDEF(VT), PostShuffleMask);
45874     return HorizBinOp;
45875   }
45876 
45877   return SDValue();
45878 }
45879 
45880 /// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
45881 /// the codegen.
45882 /// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
45883 /// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
45884 ///       anything that is guaranteed to be transformed by DAGCombiner.
45885 static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
45886                                           const X86Subtarget &Subtarget,
45887                                           const SDLoc &DL) {
45888   assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode");
45889   SDValue Src = N->getOperand(0);
45890   unsigned SrcOpcode = Src.getOpcode();
45891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
45892 
45893   EVT VT = N->getValueType(0);
45894   EVT SrcVT = Src.getValueType();
45895 
45896   auto IsFreeTruncation = [VT](SDValue Op) {
45897     unsigned TruncSizeInBits = VT.getScalarSizeInBits();
45898 
45899     // See if this has been extended from a smaller/equal size to
45900     // the truncation size, allowing a truncation to combine with the extend.
45901     unsigned Opcode = Op.getOpcode();
45902     if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
45903          Opcode == ISD::ZERO_EXTEND) &&
45904         Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
45905       return true;
45906 
45907     // See if this is a single use constant which can be constant folded.
45908     // NOTE: We don't peek throught bitcasts here because there is currently
45909     // no support for constant folding truncate+bitcast+vector_of_constants. So
45910     // we'll just send up with a truncate on both operands which will
45911     // get turned back into (truncate (binop)) causing an infinite loop.
45912     return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
45913   };
45914 
45915   auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
45916     SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
45917     SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
45918     return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
45919   };
45920 
45921   // Don't combine if the operation has other uses.
45922   if (!Src.hasOneUse())
45923     return SDValue();
45924 
45925   // Only support vector truncation for now.
45926   // TODO: i64 scalar math would benefit as well.
45927   if (!VT.isVector())
45928     return SDValue();
45929 
45930   // In most cases its only worth pre-truncating if we're only facing the cost
45931   // of one truncation.
45932   // i.e. if one of the inputs will constant fold or the input is repeated.
45933   switch (SrcOpcode) {
45934   case ISD::MUL:
45935     // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
45936     // better to truncate if we have the chance.
45937     if (SrcVT.getScalarType() == MVT::i64 &&
45938         TLI.isOperationLegal(SrcOpcode, VT) &&
45939         !TLI.isOperationLegal(SrcOpcode, SrcVT))
45940       return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
45941     LLVM_FALLTHROUGH;
45942   case ISD::AND:
45943   case ISD::XOR:
45944   case ISD::OR:
45945   case ISD::ADD:
45946   case ISD::SUB: {
45947     SDValue Op0 = Src.getOperand(0);
45948     SDValue Op1 = Src.getOperand(1);
45949     if (TLI.isOperationLegal(SrcOpcode, VT) &&
45950         (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
45951       return TruncateArithmetic(Op0, Op1);
45952     break;
45953   }
45954   }
45955 
45956   return SDValue();
45957 }
45958 
45959 /// Truncate using ISD::AND mask and X86ISD::PACKUS.
45960 /// e.g. trunc <8 x i32> X to <8 x i16> -->
45961 /// MaskX = X & 0xffff (clear high bits to prevent saturation)
45962 /// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
45963 static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
45964                                                  const X86Subtarget &Subtarget,
45965                                                  SelectionDAG &DAG) {
45966   SDValue In = N->getOperand(0);
45967   EVT InVT = In.getValueType();
45968   EVT OutVT = N->getValueType(0);
45969 
45970   APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
45971                                     OutVT.getScalarSizeInBits());
45972   In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
45973   return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
45974 }
45975 
45976 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
45977 static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
45978                                                  const X86Subtarget &Subtarget,
45979                                                  SelectionDAG &DAG) {
45980   SDValue In = N->getOperand(0);
45981   EVT InVT = In.getValueType();
45982   EVT OutVT = N->getValueType(0);
45983   In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
45984                    DAG.getValueType(OutVT));
45985   return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
45986 }
45987 
45988 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
45989 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
45990 /// legalization the truncation will be translated into a BUILD_VECTOR with each
45991 /// element that is extracted from a vector and then truncated, and it is
45992 /// difficult to do this optimization based on them.
45993 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
45994                                        const X86Subtarget &Subtarget) {
45995   EVT OutVT = N->getValueType(0);
45996   if (!OutVT.isVector())
45997     return SDValue();
45998 
45999   SDValue In = N->getOperand(0);
46000   if (!In.getValueType().isSimple())
46001     return SDValue();
46002 
46003   EVT InVT = In.getValueType();
46004   unsigned NumElems = OutVT.getVectorNumElements();
46005 
46006   // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
46007   // SSE2, and we need to take care of it specially.
46008   // AVX512 provides vpmovdb.
46009   if (!Subtarget.hasSSE2() || Subtarget.hasAVX2())
46010     return SDValue();
46011 
46012   EVT OutSVT = OutVT.getVectorElementType();
46013   EVT InSVT = InVT.getVectorElementType();
46014   if (!((InSVT == MVT::i16 || InSVT == MVT::i32 || InSVT == MVT::i64) &&
46015         (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
46016         NumElems >= 8))
46017     return SDValue();
46018 
46019   // SSSE3's pshufb results in less instructions in the cases below.
46020   if (Subtarget.hasSSSE3() && NumElems == 8 &&
46021       ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
46022        (InSVT == MVT::i32 && OutSVT == MVT::i16)))
46023     return SDValue();
46024 
46025   SDLoc DL(N);
46026   // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
46027   // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
46028   // truncate 2 x v4i32 to v8i16.
46029   if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
46030     return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
46031   if (InSVT == MVT::i32)
46032     return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
46033 
46034   return SDValue();
46035 }
46036 
46037 /// This function transforms vector truncation of 'extended sign-bits' or
46038 /// 'extended zero-bits' values.
46039 /// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
46040 static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
46041                                                SelectionDAG &DAG,
46042                                                const X86Subtarget &Subtarget) {
46043   // Requires SSE2.
46044   if (!Subtarget.hasSSE2())
46045     return SDValue();
46046 
46047   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
46048     return SDValue();
46049 
46050   SDValue In = N->getOperand(0);
46051   if (!In.getValueType().isSimple())
46052     return SDValue();
46053 
46054   MVT VT = N->getValueType(0).getSimpleVT();
46055   MVT SVT = VT.getScalarType();
46056 
46057   MVT InVT = In.getValueType().getSimpleVT();
46058   MVT InSVT = InVT.getScalarType();
46059 
46060   // Check we have a truncation suited for PACKSS/PACKUS.
46061   if (!isPowerOf2_32(VT.getVectorNumElements()))
46062     return SDValue();
46063   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
46064     return SDValue();
46065   if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
46066     return SDValue();
46067 
46068   // Truncation to sub-128bit vXi32 can be better handled with shuffles.
46069   if (SVT == MVT::i32 && VT.getSizeInBits() < 128)
46070     return SDValue();
46071 
46072   // AVX512 has fast truncate, but if the input is already going to be split,
46073   // there's no harm in trying pack.
46074   if (Subtarget.hasAVX512() &&
46075       !(!Subtarget.useAVX512Regs() && VT.is256BitVector() &&
46076         InVT.is512BitVector())) {
46077     // PACK should still be worth it for 128-bit vectors if the sources were
46078     // originally concatenated from subvectors.
46079     SmallVector<SDValue> ConcatOps;
46080     if (VT.getSizeInBits() > 128 || !collectConcatOps(In.getNode(), ConcatOps))
46081     return SDValue();
46082   }
46083 
46084   unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
46085   unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
46086 
46087   // Use PACKUS if the input has zero-bits that extend all the way to the
46088   // packed/truncated value. e.g. masks, zext_in_reg, etc.
46089   KnownBits Known = DAG.computeKnownBits(In);
46090   unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
46091   if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
46092     return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
46093 
46094   // Use PACKSS if the input has sign-bits that extend all the way to the
46095   // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
46096   unsigned NumSignBits = DAG.ComputeNumSignBits(In);
46097 
46098   // Don't use PACKSS for vXi64 -> vXi32 truncations unless we're dealing with
46099   // a sign splat. ComputeNumSignBits struggles to see through BITCASTs later
46100   // on and combines/simplifications can't then use it.
46101   if (SVT == MVT::i32 && NumSignBits != InSVT.getSizeInBits())
46102     return SDValue();
46103 
46104   unsigned MinSignBits = InSVT.getSizeInBits() - NumPackedSignBits;
46105   if (NumSignBits > MinSignBits)
46106     return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
46107 
46108   // If we have a srl that only generates signbits that we will discard in
46109   // the truncation then we can use PACKSS by converting the srl to a sra.
46110   // SimplifyDemandedBits often relaxes sra to srl so we need to reverse it.
46111   if (In.getOpcode() == ISD::SRL && N->isOnlyUserOf(In.getNode()))
46112     if (const APInt *ShAmt = DAG.getValidShiftAmountConstant(
46113             In, APInt::getAllOnesValue(VT.getVectorNumElements()))) {
46114       if (*ShAmt == MinSignBits) {
46115         SDValue NewIn = DAG.getNode(ISD::SRA, DL, InVT, In->ops());
46116         return truncateVectorWithPACK(X86ISD::PACKSS, VT, NewIn, DL, DAG,
46117                                       Subtarget);
46118       }
46119     }
46120 
46121   return SDValue();
46122 }
46123 
46124 // Try to form a MULHU or MULHS node by looking for
46125 // (trunc (srl (mul ext, ext), 16))
46126 // TODO: This is X86 specific because we want to be able to handle wide types
46127 // before type legalization. But we can only do it if the vector will be
46128 // legalized via widening/splitting. Type legalization can't handle promotion
46129 // of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
46130 // combiner.
46131 static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
46132                             SelectionDAG &DAG, const X86Subtarget &Subtarget) {
46133   // First instruction should be a right shift of a multiply.
46134   if (Src.getOpcode() != ISD::SRL ||
46135       Src.getOperand(0).getOpcode() != ISD::MUL)
46136     return SDValue();
46137 
46138   if (!Subtarget.hasSSE2())
46139     return SDValue();
46140 
46141   // Only handle vXi16 types that are at least 128-bits unless they will be
46142   // widened.
46143   if (!VT.isVector() || VT.getVectorElementType() != MVT::i16)
46144     return SDValue();
46145 
46146   // Input type should be at least vXi32.
46147   EVT InVT = Src.getValueType();
46148   if (InVT.getVectorElementType().getSizeInBits() < 32)
46149     return SDValue();
46150 
46151   // Need a shift by 16.
46152   APInt ShiftAmt;
46153   if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
46154       ShiftAmt != 16)
46155     return SDValue();
46156 
46157   SDValue LHS = Src.getOperand(0).getOperand(0);
46158   SDValue RHS = Src.getOperand(0).getOperand(1);
46159 
46160   unsigned ExtOpc = LHS.getOpcode();
46161   if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
46162       RHS.getOpcode() != ExtOpc)
46163     return SDValue();
46164 
46165   // Peek through the extends.
46166   LHS = LHS.getOperand(0);
46167   RHS = RHS.getOperand(0);
46168 
46169   // Ensure the input types match.
46170   if (LHS.getValueType() != VT || RHS.getValueType() != VT)
46171     return SDValue();
46172 
46173   unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
46174   return DAG.getNode(Opc, DL, VT, LHS, RHS);
46175 }
46176 
46177 // Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
46178 // from one vector with signed bytes from another vector, adds together
46179 // adjacent pairs of 16-bit products, and saturates the result before
46180 // truncating to 16-bits.
46181 //
46182 // Which looks something like this:
46183 // (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
46184 //                 (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
46185 static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
46186                                const X86Subtarget &Subtarget,
46187                                const SDLoc &DL) {
46188   if (!VT.isVector() || !Subtarget.hasSSSE3())
46189     return SDValue();
46190 
46191   unsigned NumElems = VT.getVectorNumElements();
46192   EVT ScalarVT = VT.getVectorElementType();
46193   if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
46194     return SDValue();
46195 
46196   SDValue SSatVal = detectSSatPattern(In, VT);
46197   if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
46198     return SDValue();
46199 
46200   // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
46201   // of multiplies from even/odd elements.
46202   SDValue N0 = SSatVal.getOperand(0);
46203   SDValue N1 = SSatVal.getOperand(1);
46204 
46205   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
46206     return SDValue();
46207 
46208   SDValue N00 = N0.getOperand(0);
46209   SDValue N01 = N0.getOperand(1);
46210   SDValue N10 = N1.getOperand(0);
46211   SDValue N11 = N1.getOperand(1);
46212 
46213   // TODO: Handle constant vectors and use knownbits/computenumsignbits?
46214   // Canonicalize zero_extend to LHS.
46215   if (N01.getOpcode() == ISD::ZERO_EXTEND)
46216     std::swap(N00, N01);
46217   if (N11.getOpcode() == ISD::ZERO_EXTEND)
46218     std::swap(N10, N11);
46219 
46220   // Ensure we have a zero_extend and a sign_extend.
46221   if (N00.getOpcode() != ISD::ZERO_EXTEND ||
46222       N01.getOpcode() != ISD::SIGN_EXTEND ||
46223       N10.getOpcode() != ISD::ZERO_EXTEND ||
46224       N11.getOpcode() != ISD::SIGN_EXTEND)
46225     return SDValue();
46226 
46227   // Peek through the extends.
46228   N00 = N00.getOperand(0);
46229   N01 = N01.getOperand(0);
46230   N10 = N10.getOperand(0);
46231   N11 = N11.getOperand(0);
46232 
46233   // Ensure the extend is from vXi8.
46234   if (N00.getValueType().getVectorElementType() != MVT::i8 ||
46235       N01.getValueType().getVectorElementType() != MVT::i8 ||
46236       N10.getValueType().getVectorElementType() != MVT::i8 ||
46237       N11.getValueType().getVectorElementType() != MVT::i8)
46238     return SDValue();
46239 
46240   // All inputs should be build_vectors.
46241   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
46242       N01.getOpcode() != ISD::BUILD_VECTOR ||
46243       N10.getOpcode() != ISD::BUILD_VECTOR ||
46244       N11.getOpcode() != ISD::BUILD_VECTOR)
46245     return SDValue();
46246 
46247   // N00/N10 are zero extended. N01/N11 are sign extended.
46248 
46249   // For each element, we need to ensure we have an odd element from one vector
46250   // multiplied by the odd element of another vector and the even element from
46251   // one of the same vectors being multiplied by the even element from the
46252   // other vector. So we need to make sure for each element i, this operator
46253   // is being performed:
46254   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
46255   SDValue ZExtIn, SExtIn;
46256   for (unsigned i = 0; i != NumElems; ++i) {
46257     SDValue N00Elt = N00.getOperand(i);
46258     SDValue N01Elt = N01.getOperand(i);
46259     SDValue N10Elt = N10.getOperand(i);
46260     SDValue N11Elt = N11.getOperand(i);
46261     // TODO: Be more tolerant to undefs.
46262     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
46263         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
46264         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
46265         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
46266       return SDValue();
46267     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
46268     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
46269     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
46270     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
46271     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
46272       return SDValue();
46273     unsigned IdxN00 = ConstN00Elt->getZExtValue();
46274     unsigned IdxN01 = ConstN01Elt->getZExtValue();
46275     unsigned IdxN10 = ConstN10Elt->getZExtValue();
46276     unsigned IdxN11 = ConstN11Elt->getZExtValue();
46277     // Add is commutative so indices can be reordered.
46278     if (IdxN00 > IdxN10) {
46279       std::swap(IdxN00, IdxN10);
46280       std::swap(IdxN01, IdxN11);
46281     }
46282     // N0 indices be the even element. N1 indices must be the next odd element.
46283     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
46284         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
46285       return SDValue();
46286     SDValue N00In = N00Elt.getOperand(0);
46287     SDValue N01In = N01Elt.getOperand(0);
46288     SDValue N10In = N10Elt.getOperand(0);
46289     SDValue N11In = N11Elt.getOperand(0);
46290     // First time we find an input capture it.
46291     if (!ZExtIn) {
46292       ZExtIn = N00In;
46293       SExtIn = N01In;
46294     }
46295     if (ZExtIn != N00In || SExtIn != N01In ||
46296         ZExtIn != N10In || SExtIn != N11In)
46297       return SDValue();
46298   }
46299 
46300   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
46301                          ArrayRef<SDValue> Ops) {
46302     // Shrink by adding truncate nodes and let DAGCombine fold with the
46303     // sources.
46304     EVT InVT = Ops[0].getValueType();
46305     assert(InVT.getScalarType() == MVT::i8 &&
46306            "Unexpected scalar element type");
46307     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
46308     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
46309                                  InVT.getVectorNumElements() / 2);
46310     return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
46311   };
46312   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
46313                           PMADDBuilder);
46314 }
46315 
46316 static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
46317                                const X86Subtarget &Subtarget) {
46318   EVT VT = N->getValueType(0);
46319   SDValue Src = N->getOperand(0);
46320   SDLoc DL(N);
46321 
46322   // Attempt to pre-truncate inputs to arithmetic ops instead.
46323   if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
46324     return V;
46325 
46326   // Try to detect AVG pattern first.
46327   if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
46328     return Avg;
46329 
46330   // Try to detect PMADD
46331   if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
46332     return PMAdd;
46333 
46334   // Try to combine truncation with signed/unsigned saturation.
46335   if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
46336     return Val;
46337 
46338   // Try to combine PMULHUW/PMULHW for vXi16.
46339   if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
46340     return V;
46341 
46342   // The bitcast source is a direct mmx result.
46343   // Detect bitcasts between i32 to x86mmx
46344   if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
46345     SDValue BCSrc = Src.getOperand(0);
46346     if (BCSrc.getValueType() == MVT::x86mmx)
46347       return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
46348   }
46349 
46350   // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
46351   if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
46352     return V;
46353 
46354   return combineVectorTruncation(N, DAG, Subtarget);
46355 }
46356 
46357 static SDValue combineVTRUNC(SDNode *N, SelectionDAG &DAG,
46358                              TargetLowering::DAGCombinerInfo &DCI) {
46359   EVT VT = N->getValueType(0);
46360   SDValue In = N->getOperand(0);
46361   SDLoc DL(N);
46362 
46363   if (auto SSatVal = detectSSatPattern(In, VT))
46364     return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
46365   if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
46366     return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
46367 
46368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46369   APInt DemandedMask(APInt::getAllOnesValue(VT.getScalarSizeInBits()));
46370   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
46371     return SDValue(N, 0);
46372 
46373   return SDValue();
46374 }
46375 
46376 /// Returns the negated value if the node \p N flips sign of FP value.
46377 ///
46378 /// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
46379 /// or FSUB(0, x)
46380 /// AVX512F does not have FXOR, so FNEG is lowered as
46381 /// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
46382 /// In this case we go though all bitcasts.
46383 /// This also recognizes splat of a negated value and returns the splat of that
46384 /// value.
46385 static SDValue isFNEG(SelectionDAG &DAG, SDNode *N, unsigned Depth = 0) {
46386   if (N->getOpcode() == ISD::FNEG)
46387     return N->getOperand(0);
46388 
46389   // Don't recurse exponentially.
46390   if (Depth > SelectionDAG::MaxRecursionDepth)
46391     return SDValue();
46392 
46393   unsigned ScalarSize = N->getValueType(0).getScalarSizeInBits();
46394 
46395   SDValue Op = peekThroughBitcasts(SDValue(N, 0));
46396   EVT VT = Op->getValueType(0);
46397 
46398   // Make sure the element size doesn't change.
46399   if (VT.getScalarSizeInBits() != ScalarSize)
46400     return SDValue();
46401 
46402   unsigned Opc = Op.getOpcode();
46403   switch (Opc) {
46404   case ISD::VECTOR_SHUFFLE: {
46405     // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
46406     // of this is VECTOR_SHUFFLE(-VEC1, UNDEF).  The mask can be anything here.
46407     if (!Op.getOperand(1).isUndef())
46408       return SDValue();
46409     if (SDValue NegOp0 = isFNEG(DAG, Op.getOperand(0).getNode(), Depth + 1))
46410       if (NegOp0.getValueType() == VT) // FIXME: Can we do better?
46411         return DAG.getVectorShuffle(VT, SDLoc(Op), NegOp0, DAG.getUNDEF(VT),
46412                                     cast<ShuffleVectorSDNode>(Op)->getMask());
46413     break;
46414   }
46415   case ISD::INSERT_VECTOR_ELT: {
46416     // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
46417     // -V, INDEX).
46418     SDValue InsVector = Op.getOperand(0);
46419     SDValue InsVal = Op.getOperand(1);
46420     if (!InsVector.isUndef())
46421       return SDValue();
46422     if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode(), Depth + 1))
46423       if (NegInsVal.getValueType() == VT.getVectorElementType()) // FIXME
46424         return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
46425                            NegInsVal, Op.getOperand(2));
46426     break;
46427   }
46428   case ISD::FSUB:
46429   case ISD::XOR:
46430   case X86ISD::FXOR: {
46431     SDValue Op1 = Op.getOperand(1);
46432     SDValue Op0 = Op.getOperand(0);
46433 
46434     // For XOR and FXOR, we want to check if constant
46435     // bits of Op1 are sign bit masks. For FSUB, we
46436     // have to check if constant bits of Op0 are sign
46437     // bit masks and hence we swap the operands.
46438     if (Opc == ISD::FSUB)
46439       std::swap(Op0, Op1);
46440 
46441     APInt UndefElts;
46442     SmallVector<APInt, 16> EltBits;
46443     // Extract constant bits and see if they are all
46444     // sign bit masks. Ignore the undef elements.
46445     if (getTargetConstantBitsFromNode(Op1, ScalarSize, UndefElts, EltBits,
46446                                       /* AllowWholeUndefs */ true,
46447                                       /* AllowPartialUndefs */ false)) {
46448       for (unsigned I = 0, E = EltBits.size(); I < E; I++)
46449         if (!UndefElts[I] && !EltBits[I].isSignMask())
46450           return SDValue();
46451 
46452       return peekThroughBitcasts(Op0);
46453     }
46454   }
46455   }
46456 
46457   return SDValue();
46458 }
46459 
46460 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc,
46461                                 bool NegRes) {
46462   if (NegMul) {
46463     switch (Opcode) {
46464     default: llvm_unreachable("Unexpected opcode");
46465     case ISD::FMA:              Opcode = X86ISD::FNMADD;        break;
46466     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FNMADD; break;
46467     case X86ISD::FMADD_RND:     Opcode = X86ISD::FNMADD_RND;    break;
46468     case X86ISD::FMSUB:         Opcode = X86ISD::FNMSUB;        break;
46469     case X86ISD::STRICT_FMSUB:  Opcode = X86ISD::STRICT_FNMSUB; break;
46470     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FNMSUB_RND;    break;
46471     case X86ISD::FNMADD:        Opcode = ISD::FMA;              break;
46472     case X86ISD::STRICT_FNMADD: Opcode = ISD::STRICT_FMA;       break;
46473     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FMADD_RND;     break;
46474     case X86ISD::FNMSUB:        Opcode = X86ISD::FMSUB;         break;
46475     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FMSUB;  break;
46476     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FMSUB_RND;     break;
46477     }
46478   }
46479 
46480   if (NegAcc) {
46481     switch (Opcode) {
46482     default: llvm_unreachable("Unexpected opcode");
46483     case ISD::FMA:              Opcode = X86ISD::FMSUB;         break;
46484     case ISD::STRICT_FMA:       Opcode = X86ISD::STRICT_FMSUB;  break;
46485     case X86ISD::FMADD_RND:     Opcode = X86ISD::FMSUB_RND;     break;
46486     case X86ISD::FMSUB:         Opcode = ISD::FMA;              break;
46487     case X86ISD::STRICT_FMSUB:  Opcode = ISD::STRICT_FMA;       break;
46488     case X86ISD::FMSUB_RND:     Opcode = X86ISD::FMADD_RND;     break;
46489     case X86ISD::FNMADD:        Opcode = X86ISD::FNMSUB;        break;
46490     case X86ISD::STRICT_FNMADD: Opcode = X86ISD::STRICT_FNMSUB; break;
46491     case X86ISD::FNMADD_RND:    Opcode = X86ISD::FNMSUB_RND;    break;
46492     case X86ISD::FNMSUB:        Opcode = X86ISD::FNMADD;        break;
46493     case X86ISD::STRICT_FNMSUB: Opcode = X86ISD::STRICT_FNMADD; break;
46494     case X86ISD::FNMSUB_RND:    Opcode = X86ISD::FNMADD_RND;    break;
46495     case X86ISD::FMADDSUB:      Opcode = X86ISD::FMSUBADD;      break;
46496     case X86ISD::FMADDSUB_RND:  Opcode = X86ISD::FMSUBADD_RND;  break;
46497     case X86ISD::FMSUBADD:      Opcode = X86ISD::FMADDSUB;      break;
46498     case X86ISD::FMSUBADD_RND:  Opcode = X86ISD::FMADDSUB_RND;  break;
46499     }
46500   }
46501 
46502   if (NegRes) {
46503     switch (Opcode) {
46504     // For accuracy reason, we never combine fneg and fma under strict FP.
46505     default: llvm_unreachable("Unexpected opcode");
46506     case ISD::FMA:             Opcode = X86ISD::FNMSUB;       break;
46507     case X86ISD::FMADD_RND:    Opcode = X86ISD::FNMSUB_RND;   break;
46508     case X86ISD::FMSUB:        Opcode = X86ISD::FNMADD;       break;
46509     case X86ISD::FMSUB_RND:    Opcode = X86ISD::FNMADD_RND;   break;
46510     case X86ISD::FNMADD:       Opcode = X86ISD::FMSUB;        break;
46511     case X86ISD::FNMADD_RND:   Opcode = X86ISD::FMSUB_RND;    break;
46512     case X86ISD::FNMSUB:       Opcode = ISD::FMA;             break;
46513     case X86ISD::FNMSUB_RND:   Opcode = X86ISD::FMADD_RND;    break;
46514     }
46515   }
46516 
46517   return Opcode;
46518 }
46519 
46520 /// Do target-specific dag combines on floating point negations.
46521 static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
46522                            TargetLowering::DAGCombinerInfo &DCI,
46523                            const X86Subtarget &Subtarget) {
46524   EVT OrigVT = N->getValueType(0);
46525   SDValue Arg = isFNEG(DAG, N);
46526   if (!Arg)
46527     return SDValue();
46528 
46529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46530   EVT VT = Arg.getValueType();
46531   EVT SVT = VT.getScalarType();
46532   SDLoc DL(N);
46533 
46534   // Let legalize expand this if it isn't a legal type yet.
46535   if (!TLI.isTypeLegal(VT))
46536     return SDValue();
46537 
46538   // If we're negating a FMUL node on a target with FMA, then we can avoid the
46539   // use of a constant by performing (-0 - A*B) instead.
46540   // FIXME: Check rounding control flags as well once it becomes available.
46541   if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
46542       Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
46543     SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
46544     SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
46545                                   Arg.getOperand(1), Zero);
46546     return DAG.getBitcast(OrigVT, NewNode);
46547   }
46548 
46549   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
46550   bool LegalOperations = !DCI.isBeforeLegalizeOps();
46551   if (SDValue NegArg =
46552           TLI.getNegatedExpression(Arg, DAG, LegalOperations, CodeSize))
46553     return DAG.getBitcast(OrigVT, NegArg);
46554 
46555   return SDValue();
46556 }
46557 
46558 SDValue X86TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
46559                                                 bool LegalOperations,
46560                                                 bool ForCodeSize,
46561                                                 NegatibleCost &Cost,
46562                                                 unsigned Depth) const {
46563   // fneg patterns are removable even if they have multiple uses.
46564   if (SDValue Arg = isFNEG(DAG, Op.getNode(), Depth)) {
46565     Cost = NegatibleCost::Cheaper;
46566     return DAG.getBitcast(Op.getValueType(), Arg);
46567   }
46568 
46569   EVT VT = Op.getValueType();
46570   EVT SVT = VT.getScalarType();
46571   unsigned Opc = Op.getOpcode();
46572   switch (Opc) {
46573   case ISD::FMA:
46574   case X86ISD::FMSUB:
46575   case X86ISD::FNMADD:
46576   case X86ISD::FNMSUB:
46577   case X86ISD::FMADD_RND:
46578   case X86ISD::FMSUB_RND:
46579   case X86ISD::FNMADD_RND:
46580   case X86ISD::FNMSUB_RND: {
46581     if (!Op.hasOneUse() || !Subtarget.hasAnyFMA() || !isTypeLegal(VT) ||
46582         !(SVT == MVT::f32 || SVT == MVT::f64) ||
46583         !isOperationLegal(ISD::FMA, VT))
46584       break;
46585 
46586     // This is always negatible for free but we might be able to remove some
46587     // extra operand negations as well.
46588     SmallVector<SDValue, 4> NewOps(Op.getNumOperands(), SDValue());
46589     for (int i = 0; i != 3; ++i)
46590       NewOps[i] = getCheaperNegatedExpression(
46591           Op.getOperand(i), DAG, LegalOperations, ForCodeSize, Depth + 1);
46592 
46593     bool NegA = !!NewOps[0];
46594     bool NegB = !!NewOps[1];
46595     bool NegC = !!NewOps[2];
46596     unsigned NewOpc = negateFMAOpcode(Opc, NegA != NegB, NegC, true);
46597 
46598     Cost = (NegA || NegB || NegC) ? NegatibleCost::Cheaper
46599                                   : NegatibleCost::Neutral;
46600 
46601     // Fill in the non-negated ops with the original values.
46602     for (int i = 0, e = Op.getNumOperands(); i != e; ++i)
46603       if (!NewOps[i])
46604         NewOps[i] = Op.getOperand(i);
46605     return DAG.getNode(NewOpc, SDLoc(Op), VT, NewOps);
46606   }
46607   case X86ISD::FRCP:
46608     if (SDValue NegOp0 =
46609             getNegatedExpression(Op.getOperand(0), DAG, LegalOperations,
46610                                  ForCodeSize, Cost, Depth + 1))
46611       return DAG.getNode(Opc, SDLoc(Op), VT, NegOp0);
46612     break;
46613   }
46614 
46615   return TargetLowering::getNegatedExpression(Op, DAG, LegalOperations,
46616                                               ForCodeSize, Cost, Depth);
46617 }
46618 
46619 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
46620                                  const X86Subtarget &Subtarget) {
46621   MVT VT = N->getSimpleValueType(0);
46622   // If we have integer vector types available, use the integer opcodes.
46623   if (!VT.isVector() || !Subtarget.hasSSE2())
46624     return SDValue();
46625 
46626   SDLoc dl(N);
46627 
46628   unsigned IntBits = VT.getScalarSizeInBits();
46629   MVT IntSVT = MVT::getIntegerVT(IntBits);
46630   MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
46631 
46632   SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
46633   SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
46634   unsigned IntOpcode;
46635   switch (N->getOpcode()) {
46636   default: llvm_unreachable("Unexpected FP logic op");
46637   case X86ISD::FOR:   IntOpcode = ISD::OR; break;
46638   case X86ISD::FXOR:  IntOpcode = ISD::XOR; break;
46639   case X86ISD::FAND:  IntOpcode = ISD::AND; break;
46640   case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
46641   }
46642   SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
46643   return DAG.getBitcast(VT, IntOp);
46644 }
46645 
46646 
46647 /// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
46648 static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
46649   if (N->getOpcode() != ISD::XOR)
46650     return SDValue();
46651 
46652   SDValue LHS = N->getOperand(0);
46653   if (!isOneConstant(N->getOperand(1)) || LHS->getOpcode() != X86ISD::SETCC)
46654     return SDValue();
46655 
46656   X86::CondCode NewCC = X86::GetOppositeBranchCondition(
46657       X86::CondCode(LHS->getConstantOperandVal(0)));
46658   SDLoc DL(N);
46659   return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
46660 }
46661 
46662 static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
46663                           TargetLowering::DAGCombinerInfo &DCI,
46664                           const X86Subtarget &Subtarget) {
46665   // If this is SSE1 only convert to FXOR to avoid scalarization.
46666   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() &&
46667       N->getValueType(0) == MVT::v4i32) {
46668     return DAG.getBitcast(
46669         MVT::v4i32, DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
46670                                 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
46671                                 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
46672   }
46673 
46674   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
46675     return Cmp;
46676 
46677   if (SDValue R = combineBitOpWithMOVMSK(N, DAG))
46678     return R;
46679 
46680   if (DCI.isBeforeLegalizeOps())
46681     return SDValue();
46682 
46683   if (SDValue SetCC = foldXor1SetCC(N, DAG))
46684     return SetCC;
46685 
46686   if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
46687     return RV;
46688 
46689   if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
46690     return FPLogic;
46691 
46692   return combineFneg(N, DAG, DCI, Subtarget);
46693 }
46694 
46695 static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
46696                             TargetLowering::DAGCombinerInfo &DCI,
46697                             const X86Subtarget &Subtarget) {
46698   EVT VT = N->getValueType(0);
46699   unsigned NumBits = VT.getSizeInBits();
46700 
46701   // TODO - Constant Folding.
46702 
46703   // Simplify the inputs.
46704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46705   APInt DemandedMask(APInt::getAllOnesValue(NumBits));
46706   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
46707     return SDValue(N, 0);
46708 
46709   return SDValue();
46710 }
46711 
46712 static bool isNullFPScalarOrVectorConst(SDValue V) {
46713   return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
46714 }
46715 
46716 /// If a value is a scalar FP zero or a vector FP zero (potentially including
46717 /// undefined elements), return a zero constant that may be used to fold away
46718 /// that value. In the case of a vector, the returned constant will not contain
46719 /// undefined elements even if the input parameter does. This makes it suitable
46720 /// to be used as a replacement operand with operations (eg, bitwise-and) where
46721 /// an undef should not propagate.
46722 static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
46723                                         const X86Subtarget &Subtarget) {
46724   if (!isNullFPScalarOrVectorConst(V))
46725     return SDValue();
46726 
46727   if (V.getValueType().isVector())
46728     return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
46729 
46730   return V;
46731 }
46732 
46733 static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
46734                                       const X86Subtarget &Subtarget) {
46735   SDValue N0 = N->getOperand(0);
46736   SDValue N1 = N->getOperand(1);
46737   EVT VT = N->getValueType(0);
46738   SDLoc DL(N);
46739 
46740   // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
46741   if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
46742         (VT == MVT::f64 && Subtarget.hasSSE2()) ||
46743         (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
46744     return SDValue();
46745 
46746   auto isAllOnesConstantFP = [](SDValue V) {
46747     if (V.getSimpleValueType().isVector())
46748       return ISD::isBuildVectorAllOnes(V.getNode());
46749     auto *C = dyn_cast<ConstantFPSDNode>(V);
46750     return C && C->getConstantFPValue()->isAllOnesValue();
46751   };
46752 
46753   // fand (fxor X, -1), Y --> fandn X, Y
46754   if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
46755     return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
46756 
46757   // fand X, (fxor Y, -1) --> fandn Y, X
46758   if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
46759     return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
46760 
46761   return SDValue();
46762 }
46763 
46764 /// Do target-specific dag combines on X86ISD::FAND nodes.
46765 static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
46766                            const X86Subtarget &Subtarget) {
46767   // FAND(0.0, x) -> 0.0
46768   if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
46769     return V;
46770 
46771   // FAND(x, 0.0) -> 0.0
46772   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
46773     return V;
46774 
46775   if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
46776     return V;
46777 
46778   return lowerX86FPLogicOp(N, DAG, Subtarget);
46779 }
46780 
46781 /// Do target-specific dag combines on X86ISD::FANDN nodes.
46782 static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
46783                             const X86Subtarget &Subtarget) {
46784   // FANDN(0.0, x) -> x
46785   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
46786     return N->getOperand(1);
46787 
46788   // FANDN(x, 0.0) -> 0.0
46789   if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
46790     return V;
46791 
46792   return lowerX86FPLogicOp(N, DAG, Subtarget);
46793 }
46794 
46795 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
46796 static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
46797                           TargetLowering::DAGCombinerInfo &DCI,
46798                           const X86Subtarget &Subtarget) {
46799   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
46800 
46801   // F[X]OR(0.0, x) -> x
46802   if (isNullFPScalarOrVectorConst(N->getOperand(0)))
46803     return N->getOperand(1);
46804 
46805   // F[X]OR(x, 0.0) -> x
46806   if (isNullFPScalarOrVectorConst(N->getOperand(1)))
46807     return N->getOperand(0);
46808 
46809   if (SDValue NewVal = combineFneg(N, DAG, DCI, Subtarget))
46810     return NewVal;
46811 
46812   return lowerX86FPLogicOp(N, DAG, Subtarget);
46813 }
46814 
46815 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
46816 static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
46817   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
46818 
46819   // FMIN/FMAX are commutative if no NaNs and no negative zeros are allowed.
46820   if (!DAG.getTarget().Options.NoNaNsFPMath ||
46821       !DAG.getTarget().Options.NoSignedZerosFPMath)
46822     return SDValue();
46823 
46824   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
46825   // into FMINC and FMAXC, which are Commutative operations.
46826   unsigned NewOp = 0;
46827   switch (N->getOpcode()) {
46828     default: llvm_unreachable("unknown opcode");
46829     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
46830     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
46831   }
46832 
46833   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
46834                      N->getOperand(0), N->getOperand(1));
46835 }
46836 
46837 static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
46838                                      const X86Subtarget &Subtarget) {
46839   if (Subtarget.useSoftFloat())
46840     return SDValue();
46841 
46842   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46843 
46844   EVT VT = N->getValueType(0);
46845   if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
46846         (Subtarget.hasSSE2() && VT == MVT::f64) ||
46847         (VT.isVector() && TLI.isTypeLegal(VT))))
46848     return SDValue();
46849 
46850   SDValue Op0 = N->getOperand(0);
46851   SDValue Op1 = N->getOperand(1);
46852   SDLoc DL(N);
46853   auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
46854 
46855   // If we don't have to respect NaN inputs, this is a direct translation to x86
46856   // min/max instructions.
46857   if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
46858     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
46859 
46860   // If one of the operands is known non-NaN use the native min/max instructions
46861   // with the non-NaN input as second operand.
46862   if (DAG.isKnownNeverNaN(Op1))
46863     return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
46864   if (DAG.isKnownNeverNaN(Op0))
46865     return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
46866 
46867   // If we have to respect NaN inputs, this takes at least 3 instructions.
46868   // Favor a library call when operating on a scalar and minimizing code size.
46869   if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
46870     return SDValue();
46871 
46872   EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
46873                                          VT);
46874 
46875   // There are 4 possibilities involving NaN inputs, and these are the required
46876   // outputs:
46877   //                   Op1
46878   //               Num     NaN
46879   //            ----------------
46880   //       Num  |  Max  |  Op0 |
46881   // Op0        ----------------
46882   //       NaN  |  Op1  |  NaN |
46883   //            ----------------
46884   //
46885   // The SSE FP max/min instructions were not designed for this case, but rather
46886   // to implement:
46887   //   Min = Op1 < Op0 ? Op1 : Op0
46888   //   Max = Op1 > Op0 ? Op1 : Op0
46889   //
46890   // So they always return Op0 if either input is a NaN. However, we can still
46891   // use those instructions for fmaxnum by selecting away a NaN input.
46892 
46893   // If either operand is NaN, the 2nd source operand (Op0) is passed through.
46894   SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
46895   SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
46896 
46897   // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
46898   // are NaN, the NaN value of Op1 is the result.
46899   return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
46900 }
46901 
46902 static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
46903                                    TargetLowering::DAGCombinerInfo &DCI) {
46904   EVT VT = N->getValueType(0);
46905   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
46906 
46907   APInt KnownUndef, KnownZero;
46908   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
46909   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
46910                                      KnownZero, DCI))
46911     return SDValue(N, 0);
46912 
46913   // Convert a full vector load into vzload when not all bits are needed.
46914   SDValue In = N->getOperand(0);
46915   MVT InVT = In.getSimpleValueType();
46916   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
46917       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
46918     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
46919     LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(0));
46920     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
46921     MVT MemVT = MVT::getIntegerVT(NumBits);
46922     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
46923     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
46924       SDLoc dl(N);
46925       SDValue Convert = DAG.getNode(N->getOpcode(), dl, VT,
46926                                     DAG.getBitcast(InVT, VZLoad));
46927       DCI.CombineTo(N, Convert);
46928       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
46929       DCI.recursivelyDeleteUnusedNodes(LN);
46930       return SDValue(N, 0);
46931     }
46932   }
46933 
46934   return SDValue();
46935 }
46936 
46937 static SDValue combineCVTP2I_CVTTP2I(SDNode *N, SelectionDAG &DAG,
46938                                      TargetLowering::DAGCombinerInfo &DCI) {
46939   bool IsStrict = N->isTargetStrictFPOpcode();
46940   EVT VT = N->getValueType(0);
46941 
46942   // Convert a full vector load into vzload when not all bits are needed.
46943   SDValue In = N->getOperand(IsStrict ? 1 : 0);
46944   MVT InVT = In.getSimpleValueType();
46945   if (VT.getVectorNumElements() < InVT.getVectorNumElements() &&
46946       ISD::isNormalLoad(In.getNode()) && In.hasOneUse()) {
46947     assert(InVT.is128BitVector() && "Expected 128-bit input vector");
46948     LoadSDNode *LN = cast<LoadSDNode>(In);
46949     unsigned NumBits = InVT.getScalarSizeInBits() * VT.getVectorNumElements();
46950     MVT MemVT = MVT::getFloatingPointVT(NumBits);
46951     MVT LoadVT = MVT::getVectorVT(MemVT, 128 / NumBits);
46952     if (SDValue VZLoad = narrowLoadToVZLoad(LN, MemVT, LoadVT, DAG)) {
46953       SDLoc dl(N);
46954       if (IsStrict) {
46955         SDValue Convert =
46956             DAG.getNode(N->getOpcode(), dl, {VT, MVT::Other},
46957                         {N->getOperand(0), DAG.getBitcast(InVT, VZLoad)});
46958         DCI.CombineTo(N, Convert, Convert.getValue(1));
46959       } else {
46960         SDValue Convert =
46961             DAG.getNode(N->getOpcode(), dl, VT, DAG.getBitcast(InVT, VZLoad));
46962         DCI.CombineTo(N, Convert);
46963       }
46964       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
46965       DCI.recursivelyDeleteUnusedNodes(LN);
46966       return SDValue(N, 0);
46967     }
46968   }
46969 
46970   return SDValue();
46971 }
46972 
46973 /// Do target-specific dag combines on X86ISD::ANDNP nodes.
46974 static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
46975                             TargetLowering::DAGCombinerInfo &DCI,
46976                             const X86Subtarget &Subtarget) {
46977   MVT VT = N->getSimpleValueType(0);
46978 
46979   // ANDNP(0, x) -> x
46980   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
46981     return N->getOperand(1);
46982 
46983   // ANDNP(x, 0) -> 0
46984   if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
46985     return DAG.getConstant(0, SDLoc(N), VT);
46986 
46987   // Turn ANDNP back to AND if input is inverted.
46988   if (SDValue Not = IsNOT(N->getOperand(0), DAG))
46989     return DAG.getNode(ISD::AND, SDLoc(N), VT, DAG.getBitcast(VT, Not),
46990                        N->getOperand(1));
46991 
46992   // Attempt to recursively combine a bitmask ANDNP with shuffles.
46993   if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
46994     SDValue Op(N, 0);
46995     if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
46996       return Res;
46997   }
46998 
46999   return SDValue();
47000 }
47001 
47002 static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
47003                          TargetLowering::DAGCombinerInfo &DCI) {
47004   SDValue N1 = N->getOperand(1);
47005 
47006   // BT ignores high bits in the bit index operand.
47007   unsigned BitWidth = N1.getValueSizeInBits();
47008   APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
47009   if (DAG.getTargetLoweringInfo().SimplifyDemandedBits(N1, DemandedMask, DCI)) {
47010     if (N->getOpcode() != ISD::DELETED_NODE)
47011       DCI.AddToWorklist(N);
47012     return SDValue(N, 0);
47013   }
47014 
47015   return SDValue();
47016 }
47017 
47018 static SDValue combineCVTPH2PS(SDNode *N, SelectionDAG &DAG,
47019                                TargetLowering::DAGCombinerInfo &DCI) {
47020   bool IsStrict = N->getOpcode() == X86ISD::STRICT_CVTPH2PS;
47021   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
47022 
47023   if (N->getValueType(0) == MVT::v4f32 && Src.getValueType() == MVT::v8i16) {
47024     APInt KnownUndef, KnownZero;
47025     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47026     APInt DemandedElts = APInt::getLowBitsSet(8, 4);
47027     if (TLI.SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
47028                                        DCI)) {
47029       if (N->getOpcode() != ISD::DELETED_NODE)
47030         DCI.AddToWorklist(N);
47031       return SDValue(N, 0);
47032     }
47033 
47034     // Convert a full vector load into vzload when not all bits are needed.
47035     if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
47036       LoadSDNode *LN = cast<LoadSDNode>(N->getOperand(IsStrict ? 1 : 0));
47037       if (SDValue VZLoad = narrowLoadToVZLoad(LN, MVT::i64, MVT::v2i64, DAG)) {
47038         SDLoc dl(N);
47039         if (IsStrict) {
47040           SDValue Convert = DAG.getNode(
47041               N->getOpcode(), dl, {MVT::v4f32, MVT::Other},
47042               {N->getOperand(0), DAG.getBitcast(MVT::v8i16, VZLoad)});
47043           DCI.CombineTo(N, Convert, Convert.getValue(1));
47044         } else {
47045           SDValue Convert = DAG.getNode(N->getOpcode(), dl, MVT::v4f32,
47046                                         DAG.getBitcast(MVT::v8i16, VZLoad));
47047           DCI.CombineTo(N, Convert);
47048         }
47049 
47050         DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), VZLoad.getValue(1));
47051         DCI.recursivelyDeleteUnusedNodes(LN);
47052         return SDValue(N, 0);
47053       }
47054     }
47055   }
47056 
47057   return SDValue();
47058 }
47059 
47060 // Try to combine sext_in_reg of a cmov of constants by extending the constants.
47061 static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
47062   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
47063 
47064   EVT DstVT = N->getValueType(0);
47065 
47066   SDValue N0 = N->getOperand(0);
47067   SDValue N1 = N->getOperand(1);
47068   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
47069 
47070   if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
47071     return SDValue();
47072 
47073   // Look through single use any_extends / truncs.
47074   SDValue IntermediateBitwidthOp;
47075   if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
47076       N0.hasOneUse()) {
47077     IntermediateBitwidthOp = N0;
47078     N0 = N0.getOperand(0);
47079   }
47080 
47081   // See if we have a single use cmov.
47082   if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
47083     return SDValue();
47084 
47085   SDValue CMovOp0 = N0.getOperand(0);
47086   SDValue CMovOp1 = N0.getOperand(1);
47087 
47088   // Make sure both operands are constants.
47089   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
47090       !isa<ConstantSDNode>(CMovOp1.getNode()))
47091     return SDValue();
47092 
47093   SDLoc DL(N);
47094 
47095   // If we looked through an any_extend/trunc above, add one to the constants.
47096   if (IntermediateBitwidthOp) {
47097     unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
47098     CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
47099     CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
47100   }
47101 
47102   CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
47103   CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
47104 
47105   EVT CMovVT = DstVT;
47106   // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
47107   if (DstVT == MVT::i16) {
47108     CMovVT = MVT::i32;
47109     CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
47110     CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
47111   }
47112 
47113   SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
47114                              N0.getOperand(2), N0.getOperand(3));
47115 
47116   if (CMovVT != DstVT)
47117     CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
47118 
47119   return CMov;
47120 }
47121 
47122 static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
47123                                       const X86Subtarget &Subtarget) {
47124   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
47125 
47126   if (SDValue V = combineSextInRegCmov(N, DAG))
47127     return V;
47128 
47129   EVT VT = N->getValueType(0);
47130   SDValue N0 = N->getOperand(0);
47131   SDValue N1 = N->getOperand(1);
47132   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
47133   SDLoc dl(N);
47134 
47135   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
47136   // both SSE and AVX2 since there is no sign-extended shift right
47137   // operation on a vector with 64-bit elements.
47138   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
47139   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
47140   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
47141                            N0.getOpcode() == ISD::SIGN_EXTEND)) {
47142     SDValue N00 = N0.getOperand(0);
47143 
47144     // EXTLOAD has a better solution on AVX2,
47145     // it may be replaced with X86ISD::VSEXT node.
47146     if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
47147       if (!ISD::isNormalLoad(N00.getNode()))
47148         return SDValue();
47149 
47150     // Attempt to promote any comparison mask ops before moving the
47151     // SIGN_EXTEND_INREG in the way.
47152     if (SDValue Promote = PromoteMaskArithmetic(N0.getNode(), DAG, Subtarget))
47153       return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Promote, N1);
47154 
47155     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
47156       SDValue Tmp =
47157           DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, N00, N1);
47158       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
47159     }
47160   }
47161   return SDValue();
47162 }
47163 
47164 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
47165 /// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
47166 /// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
47167 /// opportunities to combine math ops, use an LEA, or use a complex addressing
47168 /// mode. This can eliminate extend, add, and shift instructions.
47169 static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
47170                                    const X86Subtarget &Subtarget) {
47171   if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
47172       Ext->getOpcode() != ISD::ZERO_EXTEND)
47173     return SDValue();
47174 
47175   // TODO: This should be valid for other integer types.
47176   EVT VT = Ext->getValueType(0);
47177   if (VT != MVT::i64)
47178     return SDValue();
47179 
47180   SDValue Add = Ext->getOperand(0);
47181   if (Add.getOpcode() != ISD::ADD)
47182     return SDValue();
47183 
47184   bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
47185   bool NSW = Add->getFlags().hasNoSignedWrap();
47186   bool NUW = Add->getFlags().hasNoUnsignedWrap();
47187 
47188   // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
47189   // into the 'zext'
47190   if ((Sext && !NSW) || (!Sext && !NUW))
47191     return SDValue();
47192 
47193   // Having a constant operand to the 'add' ensures that we are not increasing
47194   // the instruction count because the constant is extended for free below.
47195   // A constant operand can also become the displacement field of an LEA.
47196   auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
47197   if (!AddOp1)
47198     return SDValue();
47199 
47200   // Don't make the 'add' bigger if there's no hope of combining it with some
47201   // other 'add' or 'shl' instruction.
47202   // TODO: It may be profitable to generate simpler LEA instructions in place
47203   // of single 'add' instructions, but the cost model for selecting an LEA
47204   // currently has a high threshold.
47205   bool HasLEAPotential = false;
47206   for (auto *User : Ext->uses()) {
47207     if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
47208       HasLEAPotential = true;
47209       break;
47210     }
47211   }
47212   if (!HasLEAPotential)
47213     return SDValue();
47214 
47215   // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
47216   int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
47217   SDValue AddOp0 = Add.getOperand(0);
47218   SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
47219   SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
47220 
47221   // The wider add is guaranteed to not wrap because both operands are
47222   // sign-extended.
47223   SDNodeFlags Flags;
47224   Flags.setNoSignedWrap(NSW);
47225   Flags.setNoUnsignedWrap(NUW);
47226   return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
47227 }
47228 
47229 // If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
47230 // operands and the result of CMOV is not used anywhere else - promote CMOV
47231 // itself instead of promoting its result. This could be beneficial, because:
47232 //     1) X86TargetLowering::EmitLoweredSelect later can do merging of two
47233 //        (or more) pseudo-CMOVs only when they go one-after-another and
47234 //        getting rid of result extension code after CMOV will help that.
47235 //     2) Promotion of constant CMOV arguments is free, hence the
47236 //        {ANY,SIGN,ZERO}_EXTEND will just be deleted.
47237 //     3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
47238 //        promotion is also good in terms of code-size.
47239 //        (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
47240 //         promotion).
47241 static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
47242   SDValue CMovN = Extend->getOperand(0);
47243   if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
47244     return SDValue();
47245 
47246   EVT TargetVT = Extend->getValueType(0);
47247   unsigned ExtendOpcode = Extend->getOpcode();
47248   SDLoc DL(Extend);
47249 
47250   EVT VT = CMovN.getValueType();
47251   SDValue CMovOp0 = CMovN.getOperand(0);
47252   SDValue CMovOp1 = CMovN.getOperand(1);
47253 
47254   if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
47255       !isa<ConstantSDNode>(CMovOp1.getNode()))
47256     return SDValue();
47257 
47258   // Only extend to i32 or i64.
47259   if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
47260     return SDValue();
47261 
47262   // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
47263   // are free.
47264   if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
47265     return SDValue();
47266 
47267   // If this a zero extend to i64, we should only extend to i32 and use a free
47268   // zero extend to finish.
47269   EVT ExtendVT = TargetVT;
47270   if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
47271     ExtendVT = MVT::i32;
47272 
47273   CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
47274   CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
47275 
47276   SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
47277                             CMovN.getOperand(2), CMovN.getOperand(3));
47278 
47279   // Finish extending if needed.
47280   if (ExtendVT != TargetVT)
47281     Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
47282 
47283   return Res;
47284 }
47285 
47286 // Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
47287 // This is more or less the reverse of combineBitcastvxi1.
47288 static SDValue
47289 combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
47290                                TargetLowering::DAGCombinerInfo &DCI,
47291                                const X86Subtarget &Subtarget) {
47292   unsigned Opcode = N->getOpcode();
47293   if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
47294       Opcode != ISD::ANY_EXTEND)
47295     return SDValue();
47296   if (!DCI.isBeforeLegalizeOps())
47297     return SDValue();
47298   if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
47299     return SDValue();
47300 
47301   SDValue N0 = N->getOperand(0);
47302   EVT VT = N->getValueType(0);
47303   EVT SVT = VT.getScalarType();
47304   EVT InSVT = N0.getValueType().getScalarType();
47305   unsigned EltSizeInBits = SVT.getSizeInBits();
47306 
47307   // Input type must be extending a bool vector (bit-casted from a scalar
47308   // integer) to legal integer types.
47309   if (!VT.isVector())
47310     return SDValue();
47311   if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
47312     return SDValue();
47313   if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
47314     return SDValue();
47315 
47316   SDValue N00 = N0.getOperand(0);
47317   EVT SclVT = N0.getOperand(0).getValueType();
47318   if (!SclVT.isScalarInteger())
47319     return SDValue();
47320 
47321   SDLoc DL(N);
47322   SDValue Vec;
47323   SmallVector<int, 32> ShuffleMask;
47324   unsigned NumElts = VT.getVectorNumElements();
47325   assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size");
47326 
47327   // Broadcast the scalar integer to the vector elements.
47328   if (NumElts > EltSizeInBits) {
47329     // If the scalar integer is greater than the vector element size, then we
47330     // must split it down into sub-sections for broadcasting. For example:
47331     //   i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
47332     //   i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
47333     assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale");
47334     unsigned Scale = NumElts / EltSizeInBits;
47335     EVT BroadcastVT =
47336         EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
47337     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
47338     Vec = DAG.getBitcast(VT, Vec);
47339 
47340     for (unsigned i = 0; i != Scale; ++i)
47341       ShuffleMask.append(EltSizeInBits, i);
47342     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
47343   } else if (Subtarget.hasAVX2() && NumElts < EltSizeInBits &&
47344              (SclVT == MVT::i8 || SclVT == MVT::i16 || SclVT == MVT::i32)) {
47345     // If we have register broadcast instructions, use the scalar size as the
47346     // element type for the shuffle. Then cast to the wider element type. The
47347     // widened bits won't be used, and this might allow the use of a broadcast
47348     // load.
47349     assert((EltSizeInBits % NumElts) == 0 && "Unexpected integer scale");
47350     unsigned Scale = EltSizeInBits / NumElts;
47351     EVT BroadcastVT =
47352         EVT::getVectorVT(*DAG.getContext(), SclVT, NumElts * Scale);
47353     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
47354     ShuffleMask.append(NumElts * Scale, 0);
47355     Vec = DAG.getVectorShuffle(BroadcastVT, DL, Vec, Vec, ShuffleMask);
47356     Vec = DAG.getBitcast(VT, Vec);
47357   } else {
47358     // For smaller scalar integers, we can simply any-extend it to the vector
47359     // element size (we don't care about the upper bits) and broadcast it to all
47360     // elements.
47361     SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
47362     Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
47363     ShuffleMask.append(NumElts, 0);
47364     Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
47365   }
47366 
47367   // Now, mask the relevant bit in each element.
47368   SmallVector<SDValue, 32> Bits;
47369   for (unsigned i = 0; i != NumElts; ++i) {
47370     int BitIdx = (i % EltSizeInBits);
47371     APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
47372     Bits.push_back(DAG.getConstant(Bit, DL, SVT));
47373   }
47374   SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
47375   Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
47376 
47377   // Compare against the bitmask and extend the result.
47378   EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
47379   Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
47380   Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
47381 
47382   // For SEXT, this is now done, otherwise shift the result down for
47383   // zero-extension.
47384   if (Opcode == ISD::SIGN_EXTEND)
47385     return Vec;
47386   return DAG.getNode(ISD::SRL, DL, VT, Vec,
47387                      DAG.getConstant(EltSizeInBits - 1, DL, VT));
47388 }
47389 
47390 // Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
47391 // result type.
47392 static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
47393                                const X86Subtarget &Subtarget) {
47394   SDValue N0 = N->getOperand(0);
47395   EVT VT = N->getValueType(0);
47396   SDLoc dl(N);
47397 
47398   // Only do this combine with AVX512 for vector extends.
47399   if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
47400     return SDValue();
47401 
47402   // Only combine legal element types.
47403   EVT SVT = VT.getVectorElementType();
47404   if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
47405       SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
47406     return SDValue();
47407 
47408   // We can only do this if the vector size in 256 bits or less.
47409   unsigned Size = VT.getSizeInBits();
47410   if (Size > 256 && Subtarget.useAVX512Regs())
47411     return SDValue();
47412 
47413   // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
47414   // that's the only integer compares with we have.
47415   ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
47416   if (ISD::isUnsignedIntSetCC(CC))
47417     return SDValue();
47418 
47419   // Only do this combine if the extension will be fully consumed by the setcc.
47420   EVT N00VT = N0.getOperand(0).getValueType();
47421   EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
47422   if (Size != MatchingVecType.getSizeInBits())
47423     return SDValue();
47424 
47425   SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
47426 
47427   if (N->getOpcode() == ISD::ZERO_EXTEND)
47428     Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType());
47429 
47430   return Res;
47431 }
47432 
47433 static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
47434                            TargetLowering::DAGCombinerInfo &DCI,
47435                            const X86Subtarget &Subtarget) {
47436   SDValue N0 = N->getOperand(0);
47437   EVT VT = N->getValueType(0);
47438   SDLoc DL(N);
47439 
47440   // (i32 (sext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
47441   if (!DCI.isBeforeLegalizeOps() &&
47442       N0.getOpcode() == X86ISD::SETCC_CARRY) {
47443     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, DL, VT, N0->getOperand(0),
47444                                  N0->getOperand(1));
47445     bool ReplaceOtherUses = !N0.hasOneUse();
47446     DCI.CombineTo(N, Setcc);
47447     // Replace other uses with a truncate of the widened setcc_carry.
47448     if (ReplaceOtherUses) {
47449       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
47450                                   N0.getValueType(), Setcc);
47451       DCI.CombineTo(N0.getNode(), Trunc);
47452     }
47453 
47454     return SDValue(N, 0);
47455   }
47456 
47457   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
47458     return NewCMov;
47459 
47460   if (!DCI.isBeforeLegalizeOps())
47461     return SDValue();
47462 
47463   if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
47464     return V;
47465 
47466   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
47467     return V;
47468 
47469   if (VT.isVector()) {
47470     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
47471       return R;
47472 
47473     if (N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG)
47474       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0));
47475   }
47476 
47477   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
47478     return NewAdd;
47479 
47480   return SDValue();
47481 }
47482 
47483 static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
47484                           TargetLowering::DAGCombinerInfo &DCI,
47485                           const X86Subtarget &Subtarget) {
47486   SDLoc dl(N);
47487   EVT VT = N->getValueType(0);
47488   bool IsStrict = N->isStrictFPOpcode() || N->isTargetStrictFPOpcode();
47489 
47490   // Let legalize expand this if it isn't a legal type yet.
47491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47492   if (!TLI.isTypeLegal(VT))
47493     return SDValue();
47494 
47495   SDValue A = N->getOperand(IsStrict ? 1 : 0);
47496   SDValue B = N->getOperand(IsStrict ? 2 : 1);
47497   SDValue C = N->getOperand(IsStrict ? 3 : 2);
47498 
47499   // If the operation allows fast-math and the target does not support FMA,
47500   // split this into mul+add to avoid libcall(s).
47501   SDNodeFlags Flags = N->getFlags();
47502   if (!IsStrict && Flags.hasAllowReassociation() &&
47503       TLI.isOperationExpand(ISD::FMA, VT)) {
47504     SDValue Fmul = DAG.getNode(ISD::FMUL, dl, VT, A, B, Flags);
47505     return DAG.getNode(ISD::FADD, dl, VT, Fmul, C, Flags);
47506   }
47507 
47508   EVT ScalarVT = VT.getScalarType();
47509   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
47510     return SDValue();
47511 
47512   auto invertIfNegative = [&DAG, &TLI, &DCI](SDValue &V) {
47513     bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
47514     bool LegalOperations = !DCI.isBeforeLegalizeOps();
47515     if (SDValue NegV = TLI.getCheaperNegatedExpression(V, DAG, LegalOperations,
47516                                                        CodeSize)) {
47517       V = NegV;
47518       return true;
47519     }
47520     // Look through extract_vector_elts. If it comes from an FNEG, create a
47521     // new extract from the FNEG input.
47522     if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
47523         isNullConstant(V.getOperand(1))) {
47524       SDValue Vec = V.getOperand(0);
47525       if (SDValue NegV = TLI.getCheaperNegatedExpression(
47526               Vec, DAG, LegalOperations, CodeSize)) {
47527         V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
47528                         NegV, V.getOperand(1));
47529         return true;
47530       }
47531     }
47532 
47533     return false;
47534   };
47535 
47536   // Do not convert the passthru input of scalar intrinsics.
47537   // FIXME: We could allow negations of the lower element only.
47538   bool NegA = invertIfNegative(A);
47539   bool NegB = invertIfNegative(B);
47540   bool NegC = invertIfNegative(C);
47541 
47542   if (!NegA && !NegB && !NegC)
47543     return SDValue();
47544 
47545   unsigned NewOpcode =
47546       negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC, false);
47547 
47548   if (IsStrict) {
47549     assert(N->getNumOperands() == 4 && "Shouldn't be greater than 4");
47550     return DAG.getNode(NewOpcode, dl, {VT, MVT::Other},
47551                        {N->getOperand(0), A, B, C});
47552   } else {
47553     if (N->getNumOperands() == 4)
47554       return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
47555     return DAG.getNode(NewOpcode, dl, VT, A, B, C);
47556   }
47557 }
47558 
47559 // Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
47560 // Combine FMSUBADD(A, B, FNEG(C)) -> FMADDSUB(A, B, C)
47561 static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
47562                                TargetLowering::DAGCombinerInfo &DCI) {
47563   SDLoc dl(N);
47564   EVT VT = N->getValueType(0);
47565   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47566   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
47567   bool LegalOperations = !DCI.isBeforeLegalizeOps();
47568 
47569   SDValue N2 = N->getOperand(2);
47570 
47571   SDValue NegN2 =
47572       TLI.getCheaperNegatedExpression(N2, DAG, LegalOperations, CodeSize);
47573   if (!NegN2)
47574     return SDValue();
47575   unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), false, true, false);
47576 
47577   if (N->getNumOperands() == 4)
47578     return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
47579                        NegN2, N->getOperand(3));
47580   return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
47581                      NegN2);
47582 }
47583 
47584 static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
47585                            TargetLowering::DAGCombinerInfo &DCI,
47586                            const X86Subtarget &Subtarget) {
47587   SDLoc dl(N);
47588   SDValue N0 = N->getOperand(0);
47589   EVT VT = N->getValueType(0);
47590 
47591   // (i32 (aext (i8 (x86isd::setcc_carry)))) -> (i32 (x86isd::setcc_carry))
47592   // FIXME: Is this needed? We don't seem to have any tests for it.
47593   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ANY_EXTEND &&
47594       N0.getOpcode() == X86ISD::SETCC_CARRY) {
47595     SDValue Setcc = DAG.getNode(X86ISD::SETCC_CARRY, dl, VT, N0->getOperand(0),
47596                                  N0->getOperand(1));
47597     bool ReplaceOtherUses = !N0.hasOneUse();
47598     DCI.CombineTo(N, Setcc);
47599     // Replace other uses with a truncate of the widened setcc_carry.
47600     if (ReplaceOtherUses) {
47601       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
47602                                   N0.getValueType(), Setcc);
47603       DCI.CombineTo(N0.getNode(), Trunc);
47604     }
47605 
47606     return SDValue(N, 0);
47607   }
47608 
47609   if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
47610     return NewCMov;
47611 
47612   if (DCI.isBeforeLegalizeOps())
47613     if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
47614       return V;
47615 
47616   if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
47617     return V;
47618 
47619   if (VT.isVector())
47620     if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
47621       return R;
47622 
47623   if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
47624     return NewAdd;
47625 
47626   if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
47627     return R;
47628 
47629   // TODO: Combine with any target/faux shuffle.
47630   if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
47631       VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
47632     SDValue N00 = N0.getOperand(0);
47633     SDValue N01 = N0.getOperand(1);
47634     unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
47635     APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
47636     if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
47637         (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
47638       return concatSubVectors(N00, N01, DAG, dl);
47639     }
47640   }
47641 
47642   return SDValue();
47643 }
47644 
47645 /// Recursive helper for combineVectorSizedSetCCEquality() to see if we have a
47646 /// recognizable memcmp expansion.
47647 static bool isOrXorXorTree(SDValue X, bool Root = true) {
47648   if (X.getOpcode() == ISD::OR)
47649     return isOrXorXorTree(X.getOperand(0), false) &&
47650            isOrXorXorTree(X.getOperand(1), false);
47651   if (Root)
47652     return false;
47653   return X.getOpcode() == ISD::XOR;
47654 }
47655 
47656 /// Recursive helper for combineVectorSizedSetCCEquality() to emit the memcmp
47657 /// expansion.
47658 template<typename F>
47659 static SDValue emitOrXorXorTree(SDValue X, SDLoc &DL, SelectionDAG &DAG,
47660                                 EVT VecVT, EVT CmpVT, bool HasPT, F SToV) {
47661   SDValue Op0 = X.getOperand(0);
47662   SDValue Op1 = X.getOperand(1);
47663   if (X.getOpcode() == ISD::OR) {
47664     SDValue A = emitOrXorXorTree(Op0, DL, DAG, VecVT, CmpVT, HasPT, SToV);
47665     SDValue B = emitOrXorXorTree(Op1, DL, DAG, VecVT, CmpVT, HasPT, SToV);
47666     if (VecVT != CmpVT)
47667       return DAG.getNode(ISD::OR, DL, CmpVT, A, B);
47668     if (HasPT)
47669       return DAG.getNode(ISD::OR, DL, VecVT, A, B);
47670     return DAG.getNode(ISD::AND, DL, CmpVT, A, B);
47671   } else if (X.getOpcode() == ISD::XOR) {
47672     SDValue A = SToV(Op0);
47673     SDValue B = SToV(Op1);
47674     if (VecVT != CmpVT)
47675       return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETNE);
47676     if (HasPT)
47677       return DAG.getNode(ISD::XOR, DL, VecVT, A, B);
47678     return DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
47679   }
47680   llvm_unreachable("Impossible");
47681 }
47682 
47683 /// Try to map a 128-bit or larger integer comparison to vector instructions
47684 /// before type legalization splits it up into chunks.
47685 static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
47686                                                const X86Subtarget &Subtarget) {
47687   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
47688   assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate");
47689 
47690   // We're looking for an oversized integer equality comparison.
47691   SDValue X = SetCC->getOperand(0);
47692   SDValue Y = SetCC->getOperand(1);
47693   EVT OpVT = X.getValueType();
47694   unsigned OpSize = OpVT.getSizeInBits();
47695   if (!OpVT.isScalarInteger() || OpSize < 128)
47696     return SDValue();
47697 
47698   // Ignore a comparison with zero because that gets special treatment in
47699   // EmitTest(). But make an exception for the special case of a pair of
47700   // logically-combined vector-sized operands compared to zero. This pattern may
47701   // be generated by the memcmp expansion pass with oversized integer compares
47702   // (see PR33325).
47703   bool IsOrXorXorTreeCCZero = isNullConstant(Y) && isOrXorXorTree(X);
47704   if (isNullConstant(Y) && !IsOrXorXorTreeCCZero)
47705     return SDValue();
47706 
47707   // Don't perform this combine if constructing the vector will be expensive.
47708   auto IsVectorBitCastCheap = [](SDValue X) {
47709     X = peekThroughBitcasts(X);
47710     return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
47711            X.getOpcode() == ISD::LOAD;
47712   };
47713   if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
47714       !IsOrXorXorTreeCCZero)
47715     return SDValue();
47716 
47717   EVT VT = SetCC->getValueType(0);
47718   SDLoc DL(SetCC);
47719 
47720   // Use XOR (plus OR) and PTEST after SSE4.1 for 128/256-bit operands.
47721   // Use PCMPNEQ (plus OR) and KORTEST for 512-bit operands.
47722   // Otherwise use PCMPEQ (plus AND) and mask testing.
47723   if ((OpSize == 128 && Subtarget.hasSSE2()) ||
47724       (OpSize == 256 && Subtarget.hasAVX()) ||
47725       (OpSize == 512 && Subtarget.useAVX512Regs())) {
47726     bool HasPT = Subtarget.hasSSE41();
47727 
47728     // PTEST and MOVMSK are slow on Knights Landing and Knights Mill and widened
47729     // vector registers are essentially free. (Technically, widening registers
47730     // prevents load folding, but the tradeoff is worth it.)
47731     bool PreferKOT = Subtarget.preferMaskRegisters();
47732     bool NeedZExt = PreferKOT && !Subtarget.hasVLX() && OpSize != 512;
47733 
47734     EVT VecVT = MVT::v16i8;
47735     EVT CmpVT = PreferKOT ? MVT::v16i1 : VecVT;
47736     if (OpSize == 256) {
47737       VecVT = MVT::v32i8;
47738       CmpVT = PreferKOT ? MVT::v32i1 : VecVT;
47739     }
47740     EVT CastVT = VecVT;
47741     bool NeedsAVX512FCast = false;
47742     if (OpSize == 512 || NeedZExt) {
47743       if (Subtarget.hasBWI()) {
47744         VecVT = MVT::v64i8;
47745         CmpVT = MVT::v64i1;
47746         if (OpSize == 512)
47747           CastVT = VecVT;
47748       } else {
47749         VecVT = MVT::v16i32;
47750         CmpVT = MVT::v16i1;
47751         CastVT = OpSize == 512 ? VecVT :
47752                  OpSize == 256 ? MVT::v8i32 : MVT::v4i32;
47753         NeedsAVX512FCast = true;
47754       }
47755     }
47756 
47757     auto ScalarToVector = [&](SDValue X) -> SDValue {
47758       bool TmpZext = false;
47759       EVT TmpCastVT = CastVT;
47760       if (X.getOpcode() == ISD::ZERO_EXTEND) {
47761         SDValue OrigX = X.getOperand(0);
47762         unsigned OrigSize = OrigX.getScalarValueSizeInBits();
47763         if (OrigSize < OpSize) {
47764           if (OrigSize == 128) {
47765             TmpCastVT = NeedsAVX512FCast ? MVT::v4i32 : MVT::v16i8;
47766             X = OrigX;
47767             TmpZext = true;
47768           } else if (OrigSize == 256) {
47769             TmpCastVT = NeedsAVX512FCast ? MVT::v8i32 : MVT::v32i8;
47770             X = OrigX;
47771             TmpZext = true;
47772           }
47773         }
47774       }
47775       X = DAG.getBitcast(TmpCastVT, X);
47776       if (!NeedZExt && !TmpZext)
47777         return X;
47778       return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT,
47779                          DAG.getConstant(0, DL, VecVT), X,
47780                          DAG.getVectorIdxConstant(0, DL));
47781     };
47782 
47783     SDValue Cmp;
47784     if (IsOrXorXorTreeCCZero) {
47785       // This is a bitwise-combined equality comparison of 2 pairs of vectors:
47786       // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
47787       // Use 2 vector equality compares and 'and' the results before doing a
47788       // MOVMSK.
47789       Cmp = emitOrXorXorTree(X, DL, DAG, VecVT, CmpVT, HasPT, ScalarToVector);
47790     } else {
47791       SDValue VecX = ScalarToVector(X);
47792       SDValue VecY = ScalarToVector(Y);
47793       if (VecVT != CmpVT) {
47794         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETNE);
47795       } else if (HasPT) {
47796         Cmp = DAG.getNode(ISD::XOR, DL, VecVT, VecX, VecY);
47797       } else {
47798         Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
47799       }
47800     }
47801     // AVX512 should emit a setcc that will lower to kortest.
47802     if (VecVT != CmpVT) {
47803       EVT KRegVT = CmpVT == MVT::v64i1 ? MVT::i64 :
47804                    CmpVT == MVT::v32i1 ? MVT::i32 : MVT::i16;
47805       return DAG.getSetCC(DL, VT, DAG.getBitcast(KRegVT, Cmp),
47806                           DAG.getConstant(0, DL, KRegVT), CC);
47807     }
47808     if (HasPT) {
47809       SDValue BCCmp = DAG.getBitcast(OpSize == 256 ? MVT::v4i64 : MVT::v2i64,
47810                                      Cmp);
47811       SDValue PT = DAG.getNode(X86ISD::PTEST, DL, MVT::i32, BCCmp, BCCmp);
47812       X86::CondCode X86CC = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
47813       SDValue X86SetCC = getSETCC(X86CC, PT, DL, DAG);
47814       return DAG.getNode(ISD::TRUNCATE, DL, VT, X86SetCC.getValue(0));
47815     }
47816     // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
47817     // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
47818     // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
47819     assert(Cmp.getValueType() == MVT::v16i8 &&
47820            "Non 128-bit vector on pre-SSE41 target");
47821     SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
47822     SDValue FFFFs = DAG.getConstant(0xFFFF, DL, MVT::i32);
47823     return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
47824   }
47825 
47826   return SDValue();
47827 }
47828 
47829 static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
47830                             const X86Subtarget &Subtarget) {
47831   const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
47832   const SDValue LHS = N->getOperand(0);
47833   const SDValue RHS = N->getOperand(1);
47834   EVT VT = N->getValueType(0);
47835   EVT OpVT = LHS.getValueType();
47836   SDLoc DL(N);
47837 
47838   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
47839     if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
47840       return V;
47841 
47842     if (VT == MVT::i1 && isNullConstant(RHS)) {
47843       SDValue X86CC;
47844       if (SDValue V =
47845               MatchVectorAllZeroTest(LHS, CC, DL, Subtarget, DAG, X86CC))
47846         return DAG.getNode(ISD::TRUNCATE, DL, VT,
47847                            DAG.getNode(X86ISD::SETCC, DL, MVT::i8, X86CC, V));
47848     }
47849   }
47850 
47851   if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
47852       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
47853     // Using temporaries to avoid messing up operand ordering for later
47854     // transformations if this doesn't work.
47855     SDValue Op0 = LHS;
47856     SDValue Op1 = RHS;
47857     ISD::CondCode TmpCC = CC;
47858     // Put build_vector on the right.
47859     if (Op0.getOpcode() == ISD::BUILD_VECTOR) {
47860       std::swap(Op0, Op1);
47861       TmpCC = ISD::getSetCCSwappedOperands(TmpCC);
47862     }
47863 
47864     bool IsSEXT0 =
47865         (Op0.getOpcode() == ISD::SIGN_EXTEND) &&
47866         (Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
47867     bool IsVZero1 = ISD::isBuildVectorAllZeros(Op1.getNode());
47868 
47869     if (IsSEXT0 && IsVZero1) {
47870       assert(VT == Op0.getOperand(0).getValueType() &&
47871              "Unexpected operand type");
47872       if (TmpCC == ISD::SETGT)
47873         return DAG.getConstant(0, DL, VT);
47874       if (TmpCC == ISD::SETLE)
47875         return DAG.getConstant(1, DL, VT);
47876       if (TmpCC == ISD::SETEQ || TmpCC == ISD::SETGE)
47877         return DAG.getNOT(DL, Op0.getOperand(0), VT);
47878 
47879       assert((TmpCC == ISD::SETNE || TmpCC == ISD::SETLT) &&
47880              "Unexpected condition code!");
47881       return Op0.getOperand(0);
47882     }
47883   }
47884 
47885   // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
47886   // pre-promote its result type since vXi1 vectors don't get promoted
47887   // during type legalization.
47888   // NOTE: The element count check is to ignore operand types that need to
47889   // go through type promotion to a 128-bit vector.
47890   if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
47891       VT.getVectorElementType() == MVT::i1 &&
47892       (OpVT.getVectorElementType() == MVT::i8 ||
47893        OpVT.getVectorElementType() == MVT::i16)) {
47894     SDValue Setcc = DAG.getSetCC(DL, OpVT, LHS, RHS, CC);
47895     return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
47896   }
47897 
47898   // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
47899   // to avoid scalarization via legalization because v4i32 is not a legal type.
47900   if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
47901       LHS.getValueType() == MVT::v4f32)
47902     return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
47903 
47904   return SDValue();
47905 }
47906 
47907 static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
47908                              TargetLowering::DAGCombinerInfo &DCI,
47909                              const X86Subtarget &Subtarget) {
47910   SDValue Src = N->getOperand(0);
47911   MVT SrcVT = Src.getSimpleValueType();
47912   MVT VT = N->getSimpleValueType(0);
47913   unsigned NumBits = VT.getScalarSizeInBits();
47914   unsigned NumElts = SrcVT.getVectorNumElements();
47915 
47916   // Perform constant folding.
47917   if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
47918     assert(VT == MVT::i32 && "Unexpected result type");
47919     APInt Imm(32, 0);
47920     for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
47921       if (!Src.getOperand(Idx).isUndef() &&
47922           Src.getConstantOperandAPInt(Idx).isNegative())
47923         Imm.setBit(Idx);
47924     }
47925     return DAG.getConstant(Imm, SDLoc(N), VT);
47926   }
47927 
47928   // Look through int->fp bitcasts that don't change the element width.
47929   unsigned EltWidth = SrcVT.getScalarSizeInBits();
47930   if (Subtarget.hasSSE2() && Src.getOpcode() == ISD::BITCAST &&
47931       Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
47932     return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
47933 
47934   // Fold movmsk(not(x)) -> not(movmsk(x)) to improve folding of movmsk results
47935   // with scalar comparisons.
47936   if (SDValue NotSrc = IsNOT(Src, DAG)) {
47937     SDLoc DL(N);
47938     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
47939     NotSrc = DAG.getBitcast(SrcVT, NotSrc);
47940     return DAG.getNode(ISD::XOR, DL, VT,
47941                        DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
47942                        DAG.getConstant(NotMask, DL, VT));
47943   }
47944 
47945   // Fold movmsk(icmp_sgt(x,-1)) -> not(movmsk(x)) to improve folding of movmsk
47946   // results with scalar comparisons.
47947   if (Src.getOpcode() == X86ISD::PCMPGT &&
47948       ISD::isBuildVectorAllOnes(Src.getOperand(1).getNode())) {
47949     SDLoc DL(N);
47950     APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
47951     return DAG.getNode(ISD::XOR, DL, VT,
47952                        DAG.getNode(X86ISD::MOVMSK, DL, VT, Src.getOperand(0)),
47953                        DAG.getConstant(NotMask, DL, VT));
47954   }
47955 
47956   // Simplify the inputs.
47957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47958   APInt DemandedMask(APInt::getAllOnesValue(NumBits));
47959   if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
47960     return SDValue(N, 0);
47961 
47962   return SDValue();
47963 }
47964 
47965 static SDValue combineX86GatherScatter(SDNode *N, SelectionDAG &DAG,
47966                                        TargetLowering::DAGCombinerInfo &DCI) {
47967   // With vector masks we only demand the upper bit of the mask.
47968   SDValue Mask = cast<X86MaskedGatherScatterSDNode>(N)->getMask();
47969   if (Mask.getScalarValueSizeInBits() != 1) {
47970     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
47971     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
47972     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
47973       if (N->getOpcode() != ISD::DELETED_NODE)
47974         DCI.AddToWorklist(N);
47975       return SDValue(N, 0);
47976     }
47977   }
47978 
47979   return SDValue();
47980 }
47981 
47982 static SDValue rebuildGatherScatter(MaskedGatherScatterSDNode *GorS,
47983                                     SDValue Index, SDValue Base, SDValue Scale,
47984                                     SelectionDAG &DAG) {
47985   SDLoc DL(GorS);
47986 
47987   if (auto *Gather = dyn_cast<MaskedGatherSDNode>(GorS)) {
47988     SDValue Ops[] = { Gather->getChain(), Gather->getPassThru(),
47989                       Gather->getMask(), Base, Index, Scale } ;
47990     return DAG.getMaskedGather(Gather->getVTList(),
47991                                Gather->getMemoryVT(), DL, Ops,
47992                                Gather->getMemOperand(),
47993                                Gather->getIndexType(),
47994                                Gather->getExtensionType());
47995   }
47996   auto *Scatter = cast<MaskedScatterSDNode>(GorS);
47997   SDValue Ops[] = { Scatter->getChain(), Scatter->getValue(),
47998                     Scatter->getMask(), Base, Index, Scale };
47999   return DAG.getMaskedScatter(Scatter->getVTList(),
48000                               Scatter->getMemoryVT(), DL,
48001                               Ops, Scatter->getMemOperand(),
48002                               Scatter->getIndexType(),
48003                               Scatter->isTruncatingStore());
48004 }
48005 
48006 static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
48007                                     TargetLowering::DAGCombinerInfo &DCI) {
48008   SDLoc DL(N);
48009   auto *GorS = cast<MaskedGatherScatterSDNode>(N);
48010   SDValue Index = GorS->getIndex();
48011   SDValue Base = GorS->getBasePtr();
48012   SDValue Scale = GorS->getScale();
48013 
48014   if (DCI.isBeforeLegalize()) {
48015     unsigned IndexWidth = Index.getScalarValueSizeInBits();
48016 
48017     // Shrink constant indices if they are larger than 32-bits.
48018     // Only do this before legalize types since v2i64 could become v2i32.
48019     // FIXME: We could check that the type is legal if we're after legalize
48020     // types, but then we would need to construct test cases where that happens.
48021     // FIXME: We could support more than just constant vectors, but we need to
48022     // careful with costing. A truncate that can be optimized out would be fine.
48023     // Otherwise we might only want to create a truncate if it avoids a split.
48024     if (auto *BV = dyn_cast<BuildVectorSDNode>(Index)) {
48025       if (BV->isConstant() && IndexWidth > 32 &&
48026           DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
48027         unsigned NumElts = Index.getValueType().getVectorNumElements();
48028         EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
48029         Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
48030         return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
48031       }
48032     }
48033 
48034     // Shrink any sign/zero extends from 32 or smaller to larger than 32 if
48035     // there are sufficient sign bits. Only do this before legalize types to
48036     // avoid creating illegal types in truncate.
48037     if ((Index.getOpcode() == ISD::SIGN_EXTEND ||
48038          Index.getOpcode() == ISD::ZERO_EXTEND) &&
48039         IndexWidth > 32 &&
48040         Index.getOperand(0).getScalarValueSizeInBits() <= 32 &&
48041         DAG.ComputeNumSignBits(Index) > (IndexWidth - 32)) {
48042       unsigned NumElts = Index.getValueType().getVectorNumElements();
48043       EVT NewVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
48044       Index = DAG.getNode(ISD::TRUNCATE, DL, NewVT, Index);
48045       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
48046     }
48047   }
48048 
48049   if (DCI.isBeforeLegalizeOps()) {
48050     unsigned IndexWidth = Index.getScalarValueSizeInBits();
48051 
48052     // Make sure the index is either i32 or i64
48053     if (IndexWidth != 32 && IndexWidth != 64) {
48054       MVT EltVT = IndexWidth > 32 ? MVT::i64 : MVT::i32;
48055       EVT IndexVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
48056                                    Index.getValueType().getVectorNumElements());
48057       Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
48058       return rebuildGatherScatter(GorS, Index, Base, Scale, DAG);
48059     }
48060   }
48061 
48062   // With vector masks we only demand the upper bit of the mask.
48063   SDValue Mask = GorS->getMask();
48064   if (Mask.getScalarValueSizeInBits() != 1) {
48065     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
48066     APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
48067     if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI)) {
48068       if (N->getOpcode() != ISD::DELETED_NODE)
48069         DCI.AddToWorklist(N);
48070       return SDValue(N, 0);
48071     }
48072   }
48073 
48074   return SDValue();
48075 }
48076 
48077 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
48078 static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
48079                                const X86Subtarget &Subtarget) {
48080   SDLoc DL(N);
48081   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
48082   SDValue EFLAGS = N->getOperand(1);
48083 
48084   // Try to simplify the EFLAGS and condition code operands.
48085   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
48086     return getSETCC(CC, Flags, DL, DAG);
48087 
48088   return SDValue();
48089 }
48090 
48091 /// Optimize branch condition evaluation.
48092 static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
48093                              const X86Subtarget &Subtarget) {
48094   SDLoc DL(N);
48095   SDValue EFLAGS = N->getOperand(3);
48096   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
48097 
48098   // Try to simplify the EFLAGS and condition code operands.
48099   // Make sure to not keep references to operands, as combineSetCCEFLAGS can
48100   // RAUW them under us.
48101   if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
48102     SDValue Cond = DAG.getTargetConstant(CC, DL, MVT::i8);
48103     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
48104                        N->getOperand(1), Cond, Flags);
48105   }
48106 
48107   return SDValue();
48108 }
48109 
48110 // TODO: Could we move this to DAGCombine?
48111 static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
48112                                                   SelectionDAG &DAG) {
48113   // Take advantage of vector comparisons (etc.) producing 0 or -1 in each lane
48114   // to optimize away operation when it's from a constant.
48115   //
48116   // The general transformation is:
48117   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
48118   //       AND(VECTOR_CMP(x,y), constant2)
48119   //    constant2 = UNARYOP(constant)
48120 
48121   // Early exit if this isn't a vector operation, the operand of the
48122   // unary operation isn't a bitwise AND, or if the sizes of the operations
48123   // aren't the same.
48124   EVT VT = N->getValueType(0);
48125   bool IsStrict = N->isStrictFPOpcode();
48126   unsigned NumEltBits = VT.getScalarSizeInBits();
48127   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
48128   if (!VT.isVector() || Op0.getOpcode() != ISD::AND ||
48129       DAG.ComputeNumSignBits(Op0.getOperand(0)) != NumEltBits ||
48130       VT.getSizeInBits() != Op0.getValueSizeInBits())
48131     return SDValue();
48132 
48133   // Now check that the other operand of the AND is a constant. We could
48134   // make the transformation for non-constant splats as well, but it's unclear
48135   // that would be a benefit as it would not eliminate any operations, just
48136   // perform one more step in scalar code before moving to the vector unit.
48137   if (auto *BV = dyn_cast<BuildVectorSDNode>(Op0.getOperand(1))) {
48138     // Bail out if the vector isn't a constant.
48139     if (!BV->isConstant())
48140       return SDValue();
48141 
48142     // Everything checks out. Build up the new and improved node.
48143     SDLoc DL(N);
48144     EVT IntVT = BV->getValueType(0);
48145     // Create a new constant of the appropriate type for the transformed
48146     // DAG.
48147     SDValue SourceConst;
48148     if (IsStrict)
48149       SourceConst = DAG.getNode(N->getOpcode(), DL, {VT, MVT::Other},
48150                                 {N->getOperand(0), SDValue(BV, 0)});
48151     else
48152       SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
48153     // The AND node needs bitcasts to/from an integer vector type around it.
48154     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
48155     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, Op0->getOperand(0),
48156                                  MaskConst);
48157     SDValue Res = DAG.getBitcast(VT, NewAnd);
48158     if (IsStrict)
48159       return DAG.getMergeValues({Res, SourceConst.getValue(1)}, DL);
48160     return Res;
48161   }
48162 
48163   return SDValue();
48164 }
48165 
48166 /// If we are converting a value to floating-point, try to replace scalar
48167 /// truncate of an extracted vector element with a bitcast. This tries to keep
48168 /// the sequence on XMM registers rather than moving between vector and GPRs.
48169 static SDValue combineToFPTruncExtElt(SDNode *N, SelectionDAG &DAG) {
48170   // TODO: This is currently only used by combineSIntToFP, but it is generalized
48171   //       to allow being called by any similar cast opcode.
48172   // TODO: Consider merging this into lowering: vectorizeExtractedCast().
48173   SDValue Trunc = N->getOperand(0);
48174   if (!Trunc.hasOneUse() || Trunc.getOpcode() != ISD::TRUNCATE)
48175     return SDValue();
48176 
48177   SDValue ExtElt = Trunc.getOperand(0);
48178   if (!ExtElt.hasOneUse() || ExtElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48179       !isNullConstant(ExtElt.getOperand(1)))
48180     return SDValue();
48181 
48182   EVT TruncVT = Trunc.getValueType();
48183   EVT SrcVT = ExtElt.getValueType();
48184   unsigned DestWidth = TruncVT.getSizeInBits();
48185   unsigned SrcWidth = SrcVT.getSizeInBits();
48186   if (SrcWidth % DestWidth != 0)
48187     return SDValue();
48188 
48189   // inttofp (trunc (extelt X, 0)) --> inttofp (extelt (bitcast X), 0)
48190   EVT SrcVecVT = ExtElt.getOperand(0).getValueType();
48191   unsigned VecWidth = SrcVecVT.getSizeInBits();
48192   unsigned NumElts = VecWidth / DestWidth;
48193   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), TruncVT, NumElts);
48194   SDValue BitcastVec = DAG.getBitcast(BitcastVT, ExtElt.getOperand(0));
48195   SDLoc DL(N);
48196   SDValue NewExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TruncVT,
48197                                   BitcastVec, ExtElt.getOperand(1));
48198   return DAG.getNode(N->getOpcode(), DL, N->getValueType(0), NewExtElt);
48199 }
48200 
48201 static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
48202                                const X86Subtarget &Subtarget) {
48203   bool IsStrict = N->isStrictFPOpcode();
48204   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
48205   EVT VT = N->getValueType(0);
48206   EVT InVT = Op0.getValueType();
48207 
48208   // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
48209   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
48210   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
48211   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
48212     SDLoc dl(N);
48213     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
48214                                  InVT.getVectorNumElements());
48215     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
48216 
48217     // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
48218     if (IsStrict)
48219       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
48220                          {N->getOperand(0), P});
48221     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
48222   }
48223 
48224   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
48225   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
48226   // the optimization here.
48227   if (DAG.SignBitIsZero(Op0)) {
48228     if (IsStrict)
48229       return DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(N), {VT, MVT::Other},
48230                          {N->getOperand(0), Op0});
48231     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
48232   }
48233 
48234   return SDValue();
48235 }
48236 
48237 static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
48238                                TargetLowering::DAGCombinerInfo &DCI,
48239                                const X86Subtarget &Subtarget) {
48240   // First try to optimize away the conversion entirely when it's
48241   // conditionally from a constant. Vectors only.
48242   bool IsStrict = N->isStrictFPOpcode();
48243   if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
48244     return Res;
48245 
48246   // Now move on to more general possibilities.
48247   SDValue Op0 = N->getOperand(IsStrict ? 1 : 0);
48248   EVT VT = N->getValueType(0);
48249   EVT InVT = Op0.getValueType();
48250 
48251   // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
48252   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
48253   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
48254   if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
48255     SDLoc dl(N);
48256     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
48257                                  InVT.getVectorNumElements());
48258     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
48259     if (IsStrict)
48260       return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
48261                          {N->getOperand(0), P});
48262     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
48263   }
48264 
48265   // Without AVX512DQ we only support i64 to float scalar conversion. For both
48266   // vectors and scalars, see if we know that the upper bits are all the sign
48267   // bit, in which case we can truncate the input to i32 and convert from that.
48268   if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
48269     unsigned BitWidth = InVT.getScalarSizeInBits();
48270     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
48271     if (NumSignBits >= (BitWidth - 31)) {
48272       EVT TruncVT = MVT::i32;
48273       if (InVT.isVector())
48274         TruncVT = EVT::getVectorVT(*DAG.getContext(), TruncVT,
48275                                    InVT.getVectorNumElements());
48276       SDLoc dl(N);
48277       if (DCI.isBeforeLegalize() || TruncVT != MVT::v2i32) {
48278         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
48279         if (IsStrict)
48280           return DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, {VT, MVT::Other},
48281                              {N->getOperand(0), Trunc});
48282         return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
48283       }
48284       // If we're after legalize and the type is v2i32 we need to shuffle and
48285       // use CVTSI2P.
48286       assert(InVT == MVT::v2i64 && "Unexpected VT!");
48287       SDValue Cast = DAG.getBitcast(MVT::v4i32, Op0);
48288       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Cast, Cast,
48289                                           { 0, 2, -1, -1 });
48290       if (IsStrict)
48291         return DAG.getNode(X86ISD::STRICT_CVTSI2P, dl, {VT, MVT::Other},
48292                            {N->getOperand(0), Shuf});
48293       return DAG.getNode(X86ISD::CVTSI2P, dl, VT, Shuf);
48294     }
48295   }
48296 
48297   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
48298   // a 32-bit target where SSE doesn't support i64->FP operations.
48299   if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
48300       Op0.getOpcode() == ISD::LOAD) {
48301     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
48302 
48303     // This transformation is not supported if the result type is f16 or f128.
48304     if (VT == MVT::f16 || VT == MVT::f128)
48305       return SDValue();
48306 
48307     // If we have AVX512DQ we can use packed conversion instructions unless
48308     // the VT is f80.
48309     if (Subtarget.hasDQI() && VT != MVT::f80)
48310       return SDValue();
48311 
48312     if (Ld->isSimple() && !VT.isVector() && ISD::isNormalLoad(Op0.getNode()) &&
48313         Op0.hasOneUse() && !Subtarget.is64Bit() && InVT == MVT::i64) {
48314       std::pair<SDValue, SDValue> Tmp =
48315           Subtarget.getTargetLowering()->BuildFILD(
48316               VT, InVT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(),
48317               Ld->getPointerInfo(), Ld->getOriginalAlign(), DAG);
48318       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Tmp.second);
48319       return Tmp.first;
48320     }
48321   }
48322 
48323   if (IsStrict)
48324     return SDValue();
48325 
48326   if (SDValue V = combineToFPTruncExtElt(N, DAG))
48327     return V;
48328 
48329   return SDValue();
48330 }
48331 
48332 static bool needCarryOrOverflowFlag(SDValue Flags) {
48333   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
48334 
48335   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
48336          UI != UE; ++UI) {
48337     SDNode *User = *UI;
48338 
48339     X86::CondCode CC;
48340     switch (User->getOpcode()) {
48341     default:
48342       // Be conservative.
48343       return true;
48344     case X86ISD::SETCC:
48345     case X86ISD::SETCC_CARRY:
48346       CC = (X86::CondCode)User->getConstantOperandVal(0);
48347       break;
48348     case X86ISD::BRCOND:
48349       CC = (X86::CondCode)User->getConstantOperandVal(2);
48350       break;
48351     case X86ISD::CMOV:
48352       CC = (X86::CondCode)User->getConstantOperandVal(2);
48353       break;
48354     }
48355 
48356     switch (CC) {
48357     default: break;
48358     case X86::COND_A: case X86::COND_AE:
48359     case X86::COND_B: case X86::COND_BE:
48360     case X86::COND_O: case X86::COND_NO:
48361     case X86::COND_G: case X86::COND_GE:
48362     case X86::COND_L: case X86::COND_LE:
48363       return true;
48364     }
48365   }
48366 
48367   return false;
48368 }
48369 
48370 static bool onlyZeroFlagUsed(SDValue Flags) {
48371   assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!");
48372 
48373   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
48374          UI != UE; ++UI) {
48375     SDNode *User = *UI;
48376 
48377     unsigned CCOpNo;
48378     switch (User->getOpcode()) {
48379     default:
48380       // Be conservative.
48381       return false;
48382     case X86ISD::SETCC:       CCOpNo = 0; break;
48383     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
48384     case X86ISD::BRCOND:      CCOpNo = 2; break;
48385     case X86ISD::CMOV:        CCOpNo = 2; break;
48386     }
48387 
48388     X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
48389     if (CC != X86::COND_E && CC != X86::COND_NE)
48390       return false;
48391   }
48392 
48393   return true;
48394 }
48395 
48396 static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
48397   // Only handle test patterns.
48398   if (!isNullConstant(N->getOperand(1)))
48399     return SDValue();
48400 
48401   // If we have a CMP of a truncated binop, see if we can make a smaller binop
48402   // and use its flags directly.
48403   // TODO: Maybe we should try promoting compares that only use the zero flag
48404   // first if we can prove the upper bits with computeKnownBits?
48405   SDLoc dl(N);
48406   SDValue Op = N->getOperand(0);
48407   EVT VT = Op.getValueType();
48408 
48409   // If we have a constant logical shift that's only used in a comparison
48410   // against zero turn it into an equivalent AND. This allows turning it into
48411   // a TEST instruction later.
48412   if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
48413       Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
48414       onlyZeroFlagUsed(SDValue(N, 0))) {
48415     unsigned BitWidth = VT.getSizeInBits();
48416     const APInt &ShAmt = Op.getConstantOperandAPInt(1);
48417     if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
48418       unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
48419       APInt Mask = Op.getOpcode() == ISD::SRL
48420                        ? APInt::getHighBitsSet(BitWidth, MaskBits)
48421                        : APInt::getLowBitsSet(BitWidth, MaskBits);
48422       if (Mask.isSignedIntN(32)) {
48423         Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
48424                          DAG.getConstant(Mask, dl, VT));
48425         return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
48426                            DAG.getConstant(0, dl, VT));
48427       }
48428     }
48429   }
48430 
48431   // Look for a truncate with a single use.
48432   if (Op.getOpcode() != ISD::TRUNCATE || !Op.hasOneUse())
48433     return SDValue();
48434 
48435   Op = Op.getOperand(0);
48436 
48437   // Arithmetic op can only have one use.
48438   if (!Op.hasOneUse())
48439     return SDValue();
48440 
48441   unsigned NewOpc;
48442   switch (Op.getOpcode()) {
48443   default: return SDValue();
48444   case ISD::AND:
48445     // Skip and with constant. We have special handling for and with immediate
48446     // during isel to generate test instructions.
48447     if (isa<ConstantSDNode>(Op.getOperand(1)))
48448       return SDValue();
48449     NewOpc = X86ISD::AND;
48450     break;
48451   case ISD::OR:  NewOpc = X86ISD::OR;  break;
48452   case ISD::XOR: NewOpc = X86ISD::XOR; break;
48453   case ISD::ADD:
48454     // If the carry or overflow flag is used, we can't truncate.
48455     if (needCarryOrOverflowFlag(SDValue(N, 0)))
48456       return SDValue();
48457     NewOpc = X86ISD::ADD;
48458     break;
48459   case ISD::SUB:
48460     // If the carry or overflow flag is used, we can't truncate.
48461     if (needCarryOrOverflowFlag(SDValue(N, 0)))
48462       return SDValue();
48463     NewOpc = X86ISD::SUB;
48464     break;
48465   }
48466 
48467   // We found an op we can narrow. Truncate its inputs.
48468   SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
48469   SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
48470 
48471   // Use a X86 specific opcode to avoid DAG combine messing with it.
48472   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
48473   Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
48474 
48475   // For AND, keep a CMP so that we can match the test pattern.
48476   if (NewOpc == X86ISD::AND)
48477     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
48478                        DAG.getConstant(0, dl, VT));
48479 
48480   // Return the flags.
48481   return Op.getValue(1);
48482 }
48483 
48484 static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
48485                                 TargetLowering::DAGCombinerInfo &DCI) {
48486   assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&
48487          "Expected X86ISD::ADD or X86ISD::SUB");
48488 
48489   SDLoc DL(N);
48490   SDValue LHS = N->getOperand(0);
48491   SDValue RHS = N->getOperand(1);
48492   MVT VT = LHS.getSimpleValueType();
48493   unsigned GenericOpc = X86ISD::ADD == N->getOpcode() ? ISD::ADD : ISD::SUB;
48494 
48495   // If we don't use the flag result, simplify back to a generic ADD/SUB.
48496   if (!N->hasAnyUseOfValue(1)) {
48497     SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
48498     return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
48499   }
48500 
48501   // Fold any similar generic ADD/SUB opcodes to reuse this node.
48502   auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
48503     SDValue Ops[] = {N0, N1};
48504     SDVTList VTs = DAG.getVTList(N->getValueType(0));
48505     if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops)) {
48506       SDValue Op(N, 0);
48507       if (Negate)
48508         Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
48509       DCI.CombineTo(GenericAddSub, Op);
48510     }
48511   };
48512   MatchGeneric(LHS, RHS, false);
48513   MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
48514 
48515   return SDValue();
48516 }
48517 
48518 static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
48519   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
48520     MVT VT = N->getSimpleValueType(0);
48521     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
48522     return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
48523                        N->getOperand(0), N->getOperand(1),
48524                        Flags);
48525   }
48526 
48527   // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
48528   // iff the flag result is dead.
48529   SDValue Op0 = N->getOperand(0);
48530   SDValue Op1 = N->getOperand(1);
48531   if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op1) &&
48532       !N->hasAnyUseOfValue(1))
48533     return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), Op0.getOperand(0),
48534                        Op0.getOperand(1), N->getOperand(2));
48535 
48536   return SDValue();
48537 }
48538 
48539 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
48540 static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
48541                           TargetLowering::DAGCombinerInfo &DCI) {
48542   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
48543   // the result is either zero or one (depending on the input carry bit).
48544   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
48545   if (X86::isZeroNode(N->getOperand(0)) &&
48546       X86::isZeroNode(N->getOperand(1)) &&
48547       // We don't have a good way to replace an EFLAGS use, so only do this when
48548       // dead right now.
48549       SDValue(N, 1).use_empty()) {
48550     SDLoc DL(N);
48551     EVT VT = N->getValueType(0);
48552     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
48553     SDValue Res1 =
48554         DAG.getNode(ISD::AND, DL, VT,
48555                     DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
48556                                 DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
48557                                 N->getOperand(2)),
48558                     DAG.getConstant(1, DL, VT));
48559     return DCI.CombineTo(N, Res1, CarryOut);
48560   }
48561 
48562   if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
48563     MVT VT = N->getSimpleValueType(0);
48564     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
48565     return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
48566                        N->getOperand(0), N->getOperand(1),
48567                        Flags);
48568   }
48569 
48570   return SDValue();
48571 }
48572 
48573 /// If this is an add or subtract where one operand is produced by a cmp+setcc,
48574 /// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
48575 /// with CMP+{ADC, SBB}.
48576 static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
48577   bool IsSub = N->getOpcode() == ISD::SUB;
48578   SDValue X = N->getOperand(0);
48579   SDValue Y = N->getOperand(1);
48580 
48581   // If this is an add, canonicalize a zext operand to the RHS.
48582   // TODO: Incomplete? What if both sides are zexts?
48583   if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
48584       Y.getOpcode() != ISD::ZERO_EXTEND)
48585     std::swap(X, Y);
48586 
48587   // Look through a one-use zext.
48588   bool PeekedThroughZext = false;
48589   if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
48590     Y = Y.getOperand(0);
48591     PeekedThroughZext = true;
48592   }
48593 
48594   // If this is an add, canonicalize a setcc operand to the RHS.
48595   // TODO: Incomplete? What if both sides are setcc?
48596   // TODO: Should we allow peeking through a zext of the other operand?
48597   if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
48598       Y.getOpcode() != X86ISD::SETCC)
48599     std::swap(X, Y);
48600 
48601   if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
48602     return SDValue();
48603 
48604   SDLoc DL(N);
48605   EVT VT = N->getValueType(0);
48606   X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
48607 
48608   // If X is -1 or 0, then we have an opportunity to avoid constants required in
48609   // the general case below.
48610   auto *ConstantX = dyn_cast<ConstantSDNode>(X);
48611   if (ConstantX) {
48612     if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnesValue()) ||
48613         (IsSub && CC == X86::COND_B && ConstantX->isNullValue())) {
48614       // This is a complicated way to get -1 or 0 from the carry flag:
48615       // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
48616       //  0 - SETB  -->  0 -  (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
48617       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
48618                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
48619                          Y.getOperand(1));
48620     }
48621 
48622     if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnesValue()) ||
48623         (IsSub && CC == X86::COND_A && ConstantX->isNullValue())) {
48624       SDValue EFLAGS = Y->getOperand(1);
48625       if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
48626           EFLAGS.getValueType().isInteger() &&
48627           !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
48628         // Swap the operands of a SUB, and we have the same pattern as above.
48629         // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
48630         //  0 - SETA  (SUB A, B) -->  0 - SETB  (SUB B, A) --> SUB + SBB
48631         SDValue NewSub = DAG.getNode(
48632             X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
48633             EFLAGS.getOperand(1), EFLAGS.getOperand(0));
48634         SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
48635         return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
48636                            DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
48637                            NewEFLAGS);
48638       }
48639     }
48640   }
48641 
48642   if (CC == X86::COND_B) {
48643     // X + SETB Z --> adc X, 0
48644     // X - SETB Z --> sbb X, 0
48645     return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
48646                        DAG.getVTList(VT, MVT::i32), X,
48647                        DAG.getConstant(0, DL, VT), Y.getOperand(1));
48648   }
48649 
48650   if (CC == X86::COND_A) {
48651     SDValue EFLAGS = Y.getOperand(1);
48652     // Try to convert COND_A into COND_B in an attempt to facilitate
48653     // materializing "setb reg".
48654     //
48655     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
48656     // cannot take an immediate as its first operand.
48657     //
48658     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
48659         EFLAGS.getValueType().isInteger() &&
48660         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
48661       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
48662                                    EFLAGS.getNode()->getVTList(),
48663                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
48664       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
48665       return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
48666                          DAG.getVTList(VT, MVT::i32), X,
48667                          DAG.getConstant(0, DL, VT), NewEFLAGS);
48668     }
48669   }
48670 
48671   if (CC == X86::COND_AE) {
48672     // X + SETAE --> sbb X, -1
48673     // X - SETAE --> adc X, -1
48674     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
48675                        DAG.getVTList(VT, MVT::i32), X,
48676                        DAG.getConstant(-1, DL, VT), Y.getOperand(1));
48677   }
48678 
48679   if (CC == X86::COND_BE) {
48680     // X + SETBE --> sbb X, -1
48681     // X - SETBE --> adc X, -1
48682     SDValue EFLAGS = Y.getOperand(1);
48683     // Try to convert COND_BE into COND_AE in an attempt to facilitate
48684     // materializing "setae reg".
48685     //
48686     // Do not flip "e <= c", where "c" is a constant, because Cmp instruction
48687     // cannot take an immediate as its first operand.
48688     //
48689     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
48690         EFLAGS.getValueType().isInteger() &&
48691         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
48692       SDValue NewSub = DAG.getNode(
48693           X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
48694           EFLAGS.getOperand(1), EFLAGS.getOperand(0));
48695       SDValue NewEFLAGS = NewSub.getValue(EFLAGS.getResNo());
48696       return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL,
48697                          DAG.getVTList(VT, MVT::i32), X,
48698                          DAG.getConstant(-1, DL, VT), NewEFLAGS);
48699     }
48700   }
48701 
48702   if (CC != X86::COND_E && CC != X86::COND_NE)
48703     return SDValue();
48704 
48705   SDValue Cmp = Y.getOperand(1);
48706   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
48707       !X86::isZeroNode(Cmp.getOperand(1)) ||
48708       !Cmp.getOperand(0).getValueType().isInteger())
48709     return SDValue();
48710 
48711   SDValue Z = Cmp.getOperand(0);
48712   EVT ZVT = Z.getValueType();
48713 
48714   // If X is -1 or 0, then we have an opportunity to avoid constants required in
48715   // the general case below.
48716   if (ConstantX) {
48717     // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
48718     // fake operands:
48719     //  0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
48720     // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
48721     if ((IsSub && CC == X86::COND_NE && ConstantX->isNullValue()) ||
48722         (!IsSub && CC == X86::COND_E && ConstantX->isAllOnesValue())) {
48723       SDValue Zero = DAG.getConstant(0, DL, ZVT);
48724       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
48725       SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
48726       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
48727                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
48728                          SDValue(Neg.getNode(), 1));
48729     }
48730 
48731     // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
48732     // with fake operands:
48733     //  0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
48734     // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
48735     if ((IsSub && CC == X86::COND_E && ConstantX->isNullValue()) ||
48736         (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnesValue())) {
48737       SDValue One = DAG.getConstant(1, DL, ZVT);
48738       SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
48739       SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
48740       return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
48741                          DAG.getTargetConstant(X86::COND_B, DL, MVT::i8),
48742                          Cmp1.getValue(1));
48743     }
48744   }
48745 
48746   // (cmp Z, 1) sets the carry flag if Z is 0.
48747   SDValue One = DAG.getConstant(1, DL, ZVT);
48748   SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
48749   SDValue Cmp1 = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Z, One);
48750 
48751   // Add the flags type for ADC/SBB nodes.
48752   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
48753 
48754   // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
48755   // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
48756   if (CC == X86::COND_NE)
48757     return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
48758                        DAG.getConstant(-1ULL, DL, VT), Cmp1.getValue(1));
48759 
48760   // X - (Z == 0) --> sub X, (zext(sete  Z, 0)) --> sbb X, 0, (cmp Z, 1)
48761   // X + (Z == 0) --> add X, (zext(sete  Z, 0)) --> adc X, 0, (cmp Z, 1)
48762   return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
48763                      DAG.getConstant(0, DL, VT), Cmp1.getValue(1));
48764 }
48765 
48766 static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
48767                             const SDLoc &DL, EVT VT,
48768                             const X86Subtarget &Subtarget) {
48769   // Example of pattern we try to detect:
48770   // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
48771   //(add (build_vector (extract_elt t, 0),
48772   //                   (extract_elt t, 2),
48773   //                   (extract_elt t, 4),
48774   //                   (extract_elt t, 6)),
48775   //     (build_vector (extract_elt t, 1),
48776   //                   (extract_elt t, 3),
48777   //                   (extract_elt t, 5),
48778   //                   (extract_elt t, 7)))
48779 
48780   if (!Subtarget.hasSSE2())
48781     return SDValue();
48782 
48783   if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
48784       Op1.getOpcode() != ISD::BUILD_VECTOR)
48785     return SDValue();
48786 
48787   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
48788       VT.getVectorNumElements() < 4 ||
48789       !isPowerOf2_32(VT.getVectorNumElements()))
48790     return SDValue();
48791 
48792   // Check if one of Op0,Op1 is of the form:
48793   // (build_vector (extract_elt Mul, 0),
48794   //               (extract_elt Mul, 2),
48795   //               (extract_elt Mul, 4),
48796   //                   ...
48797   // the other is of the form:
48798   // (build_vector (extract_elt Mul, 1),
48799   //               (extract_elt Mul, 3),
48800   //               (extract_elt Mul, 5),
48801   //                   ...
48802   // and identify Mul.
48803   SDValue Mul;
48804   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
48805     SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
48806             Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
48807     // TODO: Be more tolerant to undefs.
48808     if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48809         Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48810         Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48811         Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
48812       return SDValue();
48813     auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
48814     auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
48815     auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
48816     auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
48817     if (!Const0L || !Const1L || !Const0H || !Const1H)
48818       return SDValue();
48819     unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
48820              Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
48821     // Commutativity of mul allows factors of a product to reorder.
48822     if (Idx0L > Idx1L)
48823       std::swap(Idx0L, Idx1L);
48824     if (Idx0H > Idx1H)
48825       std::swap(Idx0H, Idx1H);
48826     // Commutativity of add allows pairs of factors to reorder.
48827     if (Idx0L > Idx0H) {
48828       std::swap(Idx0L, Idx0H);
48829       std::swap(Idx1L, Idx1H);
48830     }
48831     if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
48832         Idx1H != 2 * i + 3)
48833       return SDValue();
48834     if (!Mul) {
48835       // First time an extract_elt's source vector is visited. Must be a MUL
48836       // with 2X number of vector elements than the BUILD_VECTOR.
48837       // Both extracts must be from same MUL.
48838       Mul = Op0L->getOperand(0);
48839       if (Mul->getOpcode() != ISD::MUL ||
48840           Mul.getValueType().getVectorNumElements() != 2 * e)
48841         return SDValue();
48842     }
48843     // Check that the extract is from the same MUL previously seen.
48844     if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
48845         Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
48846       return SDValue();
48847   }
48848 
48849   // Check if the Mul source can be safely shrunk.
48850   ShrinkMode Mode;
48851   if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) ||
48852       Mode == ShrinkMode::MULU16)
48853     return SDValue();
48854 
48855   EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
48856                                  VT.getVectorNumElements() * 2);
48857   SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(0));
48858   SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Mul.getOperand(1));
48859 
48860   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48861                          ArrayRef<SDValue> Ops) {
48862     EVT InVT = Ops[0].getValueType();
48863     assert(InVT == Ops[1].getValueType() && "Operands' types mismatch");
48864     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
48865                                  InVT.getVectorNumElements() / 2);
48866     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
48867   };
48868   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { N0, N1 }, PMADDBuilder);
48869 }
48870 
48871 // Attempt to turn this pattern into PMADDWD.
48872 // (add (mul (sext (build_vector)), (sext (build_vector))),
48873 //      (mul (sext (build_vector)), (sext (build_vector)))
48874 static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
48875                               const SDLoc &DL, EVT VT,
48876                               const X86Subtarget &Subtarget) {
48877   if (!Subtarget.hasSSE2())
48878     return SDValue();
48879 
48880   if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
48881     return SDValue();
48882 
48883   if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
48884       VT.getVectorNumElements() < 4 ||
48885       !isPowerOf2_32(VT.getVectorNumElements()))
48886     return SDValue();
48887 
48888   SDValue N00 = N0.getOperand(0);
48889   SDValue N01 = N0.getOperand(1);
48890   SDValue N10 = N1.getOperand(0);
48891   SDValue N11 = N1.getOperand(1);
48892 
48893   // All inputs need to be sign extends.
48894   // TODO: Support ZERO_EXTEND from known positive?
48895   if (N00.getOpcode() != ISD::SIGN_EXTEND ||
48896       N01.getOpcode() != ISD::SIGN_EXTEND ||
48897       N10.getOpcode() != ISD::SIGN_EXTEND ||
48898       N11.getOpcode() != ISD::SIGN_EXTEND)
48899     return SDValue();
48900 
48901   // Peek through the extends.
48902   N00 = N00.getOperand(0);
48903   N01 = N01.getOperand(0);
48904   N10 = N10.getOperand(0);
48905   N11 = N11.getOperand(0);
48906 
48907   // Must be extending from vXi16.
48908   EVT InVT = N00.getValueType();
48909   if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
48910       N10.getValueType() != InVT || N11.getValueType() != InVT)
48911     return SDValue();
48912 
48913   // All inputs should be build_vectors.
48914   if (N00.getOpcode() != ISD::BUILD_VECTOR ||
48915       N01.getOpcode() != ISD::BUILD_VECTOR ||
48916       N10.getOpcode() != ISD::BUILD_VECTOR ||
48917       N11.getOpcode() != ISD::BUILD_VECTOR)
48918     return SDValue();
48919 
48920   // For each element, we need to ensure we have an odd element from one vector
48921   // multiplied by the odd element of another vector and the even element from
48922   // one of the same vectors being multiplied by the even element from the
48923   // other vector. So we need to make sure for each element i, this operator
48924   // is being performed:
48925   //  A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
48926   SDValue In0, In1;
48927   for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
48928     SDValue N00Elt = N00.getOperand(i);
48929     SDValue N01Elt = N01.getOperand(i);
48930     SDValue N10Elt = N10.getOperand(i);
48931     SDValue N11Elt = N11.getOperand(i);
48932     // TODO: Be more tolerant to undefs.
48933     if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48934         N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48935         N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
48936         N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
48937       return SDValue();
48938     auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
48939     auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
48940     auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
48941     auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
48942     if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
48943       return SDValue();
48944     unsigned IdxN00 = ConstN00Elt->getZExtValue();
48945     unsigned IdxN01 = ConstN01Elt->getZExtValue();
48946     unsigned IdxN10 = ConstN10Elt->getZExtValue();
48947     unsigned IdxN11 = ConstN11Elt->getZExtValue();
48948     // Add is commutative so indices can be reordered.
48949     if (IdxN00 > IdxN10) {
48950       std::swap(IdxN00, IdxN10);
48951       std::swap(IdxN01, IdxN11);
48952     }
48953     // N0 indices be the even element. N1 indices must be the next odd element.
48954     if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
48955         IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
48956       return SDValue();
48957     SDValue N00In = N00Elt.getOperand(0);
48958     SDValue N01In = N01Elt.getOperand(0);
48959     SDValue N10In = N10Elt.getOperand(0);
48960     SDValue N11In = N11Elt.getOperand(0);
48961     // First time we find an input capture it.
48962     if (!In0) {
48963       In0 = N00In;
48964       In1 = N01In;
48965     }
48966     // Mul is commutative so the input vectors can be in any order.
48967     // Canonicalize to make the compares easier.
48968     if (In0 != N00In)
48969       std::swap(N00In, N01In);
48970     if (In0 != N10In)
48971       std::swap(N10In, N11In);
48972     if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
48973       return SDValue();
48974   }
48975 
48976   auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
48977                          ArrayRef<SDValue> Ops) {
48978     // Shrink by adding truncate nodes and let DAGCombine fold with the
48979     // sources.
48980     EVT OpVT = Ops[0].getValueType();
48981     assert(OpVT.getScalarType() == MVT::i16 &&
48982            "Unexpected scalar element type");
48983     assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch");
48984     EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
48985                                  OpVT.getVectorNumElements() / 2);
48986     return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
48987   };
48988   return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
48989                           PMADDBuilder);
48990 }
48991 
48992 static SDValue combineAddOrSubToHADDorHSUB(SDNode *N, SelectionDAG &DAG,
48993                                            const X86Subtarget &Subtarget) {
48994   EVT VT = N->getValueType(0);
48995   SDValue Op0 = N->getOperand(0);
48996   SDValue Op1 = N->getOperand(1);
48997   bool IsAdd = N->getOpcode() == ISD::ADD;
48998   auto HorizOpcode = IsAdd ? X86ISD::HADD : X86ISD::HSUB;
48999   assert((IsAdd || N->getOpcode() == ISD::SUB) && "Wrong opcode");
49000 
49001   SmallVector<int, 8> PostShuffleMask;
49002   if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
49003        VT == MVT::v8i32) &&
49004       Subtarget.hasSSSE3() &&
49005       isHorizontalBinOp(HorizOpcode, Op0, Op1, DAG, Subtarget, IsAdd,
49006                         PostShuffleMask)) {
49007     auto HOpBuilder = [HorizOpcode](SelectionDAG &DAG, const SDLoc &DL,
49008                                     ArrayRef<SDValue> Ops) {
49009       return DAG.getNode(HorizOpcode, DL, Ops[0].getValueType(), Ops);
49010     };
49011     SDValue HorizBinOp =
49012         SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1}, HOpBuilder);
49013     if (!PostShuffleMask.empty())
49014       HorizBinOp = DAG.getVectorShuffle(VT, SDLoc(HorizBinOp), HorizBinOp,
49015                                         DAG.getUNDEF(VT), PostShuffleMask);
49016     return HorizBinOp;
49017   }
49018 
49019   return SDValue();
49020 }
49021 
49022 static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
49023                           TargetLowering::DAGCombinerInfo &DCI,
49024                           const X86Subtarget &Subtarget) {
49025   EVT VT = N->getValueType(0);
49026   SDValue Op0 = N->getOperand(0);
49027   SDValue Op1 = N->getOperand(1);
49028 
49029   if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
49030     return MAdd;
49031   if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
49032     return MAdd;
49033 
49034   // Try to synthesize horizontal adds from adds of shuffles.
49035   if (SDValue V = combineAddOrSubToHADDorHSUB(N, DAG, Subtarget))
49036     return V;
49037 
49038   // If vectors of i1 are legal, turn (add (zext (vXi1 X)), Y) into
49039   // (sub Y, (sext (vXi1 X))).
49040   // FIXME: We have the (sub Y, (zext (vXi1 X))) -> (add (sext (vXi1 X)), Y) in
49041   // generic DAG combine without a legal type check, but adding this there
49042   // caused regressions.
49043   if (VT.isVector()) {
49044     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49045     if (Op0.getOpcode() == ISD::ZERO_EXTEND &&
49046         Op0.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
49047         TLI.isTypeLegal(Op0.getOperand(0).getValueType())) {
49048       SDLoc DL(N);
49049       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op0.getOperand(0));
49050       return DAG.getNode(ISD::SUB, DL, VT, Op1, SExt);
49051     }
49052 
49053     if (Op1.getOpcode() == ISD::ZERO_EXTEND &&
49054         Op1.getOperand(0).getValueType().getVectorElementType() == MVT::i1 &&
49055         TLI.isTypeLegal(Op1.getOperand(0).getValueType())) {
49056       SDLoc DL(N);
49057       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op1.getOperand(0));
49058       return DAG.getNode(ISD::SUB, DL, VT, Op0, SExt);
49059     }
49060   }
49061 
49062   return combineAddOrSubToADCOrSBB(N, DAG);
49063 }
49064 
49065 static SDValue combineSubToSubus(SDNode *N, SelectionDAG &DAG,
49066                                  const X86Subtarget &Subtarget) {
49067   SDValue Op0 = N->getOperand(0);
49068   SDValue Op1 = N->getOperand(1);
49069   EVT VT = N->getValueType(0);
49070 
49071   if (!VT.isVector())
49072     return SDValue();
49073 
49074   // PSUBUS is supported, starting from SSE2.
49075   EVT EltVT = VT.getVectorElementType();
49076   if (!(Subtarget.hasSSE2() &&
49077         (EltVT == MVT::i8 || EltVT == MVT::i16 || VT == MVT::v8i32 ||
49078          VT == MVT::v8i64 || VT == MVT::v16i32)))
49079     return SDValue();
49080 
49081   SDValue SubusLHS, SubusRHS;
49082   // Try to find umax(a,b) - b or a - umin(a,b) patterns
49083   // they may be converted to subus(a,b).
49084   // TODO: Need to add IR canonicalization for this code.
49085   if (Op0.getOpcode() == ISD::UMAX) {
49086     SubusRHS = Op1;
49087     SDValue MaxLHS = Op0.getOperand(0);
49088     SDValue MaxRHS = Op0.getOperand(1);
49089     if (MaxLHS == Op1)
49090       SubusLHS = MaxRHS;
49091     else if (MaxRHS == Op1)
49092       SubusLHS = MaxLHS;
49093     else
49094       return SDValue();
49095   } else if (Op1.getOpcode() == ISD::UMIN) {
49096     SubusLHS = Op0;
49097     SDValue MinLHS = Op1.getOperand(0);
49098     SDValue MinRHS = Op1.getOperand(1);
49099     if (MinLHS == Op0)
49100       SubusRHS = MinRHS;
49101     else if (MinRHS == Op0)
49102       SubusRHS = MinLHS;
49103     else
49104       return SDValue();
49105   } else if (Op1.getOpcode() == ISD::TRUNCATE &&
49106              Op1.getOperand(0).getOpcode() == ISD::UMIN &&
49107              (EltVT == MVT::i8 || EltVT == MVT::i16)) {
49108     // Special case where the UMIN has been truncated. Try to push the truncate
49109     // further up. This is similar to the i32/i64 special processing.
49110     SubusLHS = Op0;
49111     SDValue MinLHS = Op1.getOperand(0).getOperand(0);
49112     SDValue MinRHS = Op1.getOperand(0).getOperand(1);
49113     EVT TruncVT = Op1.getOperand(0).getValueType();
49114     if (!(Subtarget.hasSSE2() &&
49115           (TruncVT == MVT::v8i32 || TruncVT == MVT::v8i64 ||
49116            TruncVT == MVT::v16i32)))
49117       return SDValue();
49118     SDValue OpToSaturate;
49119     if (MinLHS.getOpcode() == ISD::ZERO_EXTEND &&
49120         MinLHS.getOperand(0) == Op0)
49121       OpToSaturate = MinRHS;
49122     else if (MinRHS.getOpcode() == ISD::ZERO_EXTEND &&
49123              MinRHS.getOperand(0) == Op0)
49124       OpToSaturate = MinLHS;
49125     else
49126       return SDValue();
49127 
49128     // Saturate the non-extended input and then truncate it.
49129     SDLoc DL(N);
49130     SDValue SaturationConst =
49131         DAG.getConstant(APInt::getLowBitsSet(TruncVT.getScalarSizeInBits(),
49132                                              VT.getScalarSizeInBits()),
49133                         DL, TruncVT);
49134     SDValue UMin = DAG.getNode(ISD::UMIN, DL, TruncVT, OpToSaturate,
49135                                SaturationConst);
49136     SubusRHS = DAG.getNode(ISD::TRUNCATE, DL, VT, UMin);
49137   } else
49138     return SDValue();
49139 
49140   // PSUBUS doesn't support v8i32/v8i64/v16i32, but it can be enabled with
49141   // special preprocessing in some cases.
49142   if (EltVT == MVT::i8 || EltVT == MVT::i16)
49143     return DAG.getNode(ISD::USUBSAT, SDLoc(N), VT, SubusLHS, SubusRHS);
49144 
49145   assert((VT == MVT::v8i32 || VT == MVT::v16i32 || VT == MVT::v8i64) &&
49146          "Unexpected VT!");
49147 
49148   // Special preprocessing case can be only applied
49149   // if the value was zero extended from 16 bit,
49150   // so we require first 16 bits to be zeros for 32 bit
49151   // values, or first 48 bits for 64 bit values.
49152   KnownBits Known = DAG.computeKnownBits(SubusLHS);
49153   unsigned NumZeros = Known.countMinLeadingZeros();
49154   if (NumZeros < (VT.getScalarSizeInBits() - 16))
49155     return SDValue();
49156 
49157   EVT ExtType = SubusLHS.getValueType();
49158   EVT ShrinkedType;
49159   if (VT == MVT::v8i32 || VT == MVT::v8i64)
49160     ShrinkedType = MVT::v8i16;
49161   else
49162     ShrinkedType = NumZeros >= 24 ? MVT::v16i8 : MVT::v16i16;
49163 
49164   // If SubusLHS is zeroextended - truncate SubusRHS to it's
49165   // size SubusRHS = umin(0xFFF.., SubusRHS).
49166   SDValue SaturationConst =
49167       DAG.getConstant(APInt::getLowBitsSet(ExtType.getScalarSizeInBits(),
49168                                            ShrinkedType.getScalarSizeInBits()),
49169                       SDLoc(SubusLHS), ExtType);
49170   SDValue UMin = DAG.getNode(ISD::UMIN, SDLoc(SubusLHS), ExtType, SubusRHS,
49171                              SaturationConst);
49172   SDValue NewSubusLHS =
49173       DAG.getZExtOrTrunc(SubusLHS, SDLoc(SubusLHS), ShrinkedType);
49174   SDValue NewSubusRHS = DAG.getZExtOrTrunc(UMin, SDLoc(SubusRHS), ShrinkedType);
49175   SDValue Psubus = DAG.getNode(ISD::USUBSAT, SDLoc(N), ShrinkedType,
49176                                NewSubusLHS, NewSubusRHS);
49177 
49178   // Zero extend the result, it may be used somewhere as 32 bit,
49179   // if not zext and following trunc will shrink.
49180   return DAG.getZExtOrTrunc(Psubus, SDLoc(N), ExtType);
49181 }
49182 
49183 static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
49184                           TargetLowering::DAGCombinerInfo &DCI,
49185                           const X86Subtarget &Subtarget) {
49186   SDValue Op0 = N->getOperand(0);
49187   SDValue Op1 = N->getOperand(1);
49188 
49189   // X86 can't encode an immediate LHS of a sub. See if we can push the
49190   // negation into a preceding instruction.
49191   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
49192     // If the RHS of the sub is a XOR with one use and a constant, invert the
49193     // immediate. Then add one to the LHS of the sub so we can turn
49194     // X-Y -> X+~Y+1, saving one register.
49195     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
49196         isa<ConstantSDNode>(Op1.getOperand(1))) {
49197       const APInt &XorC = Op1.getConstantOperandAPInt(1);
49198       EVT VT = Op0.getValueType();
49199       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
49200                                    Op1.getOperand(0),
49201                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
49202       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
49203                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
49204     }
49205   }
49206 
49207   // Try to synthesize horizontal subs from subs of shuffles.
49208   if (SDValue V = combineAddOrSubToHADDorHSUB(N, DAG, Subtarget))
49209     return V;
49210 
49211   // Try to create PSUBUS if SUB's argument is max/min
49212   if (SDValue V = combineSubToSubus(N, DAG, Subtarget))
49213     return V;
49214 
49215   return combineAddOrSubToADCOrSBB(N, DAG);
49216 }
49217 
49218 static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
49219                                     const X86Subtarget &Subtarget) {
49220   MVT VT = N->getSimpleValueType(0);
49221   SDLoc DL(N);
49222 
49223   if (N->getOperand(0) == N->getOperand(1)) {
49224     if (N->getOpcode() == X86ISD::PCMPEQ)
49225       return DAG.getConstant(-1, DL, VT);
49226     if (N->getOpcode() == X86ISD::PCMPGT)
49227       return DAG.getConstant(0, DL, VT);
49228   }
49229 
49230   return SDValue();
49231 }
49232 
49233 /// Helper that combines an array of subvector ops as if they were the operands
49234 /// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
49235 /// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
49236 static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
49237                                       ArrayRef<SDValue> Ops, SelectionDAG &DAG,
49238                                       TargetLowering::DAGCombinerInfo &DCI,
49239                                       const X86Subtarget &Subtarget) {
49240   assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors");
49241   unsigned EltSizeInBits = VT.getScalarSizeInBits();
49242 
49243   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
49244     return DAG.getUNDEF(VT);
49245 
49246   if (llvm::all_of(Ops, [](SDValue Op) {
49247         return ISD::isBuildVectorAllZeros(Op.getNode());
49248       }))
49249     return getZeroVector(VT, Subtarget, DAG, DL);
49250 
49251   SDValue Op0 = Ops[0];
49252   bool IsSplat = llvm::all_of(Ops, [&Op0](SDValue Op) { return Op == Op0; });
49253 
49254   // Repeated subvectors.
49255   if (IsSplat &&
49256       (VT.is256BitVector() || (VT.is512BitVector() && Subtarget.hasAVX512()))) {
49257     // If this broadcast is inserted into both halves, use a larger broadcast.
49258     if (Op0.getOpcode() == X86ISD::VBROADCAST)
49259       return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
49260 
49261     // If this scalar/subvector broadcast_load is inserted into both halves, use
49262     // a larger broadcast_load. Update other uses to use an extracted subvector.
49263     if (Op0.getOpcode() == X86ISD::VBROADCAST_LOAD ||
49264         Op0.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) {
49265       auto *MemIntr = cast<MemIntrinsicSDNode>(Op0);
49266       SDVTList Tys = DAG.getVTList(VT, MVT::Other);
49267       SDValue Ops[] = {MemIntr->getChain(), MemIntr->getBasePtr()};
49268       SDValue BcastLd = DAG.getMemIntrinsicNode(Op0.getOpcode(), DL, Tys, Ops,
49269                                                 MemIntr->getMemoryVT(),
49270                                                 MemIntr->getMemOperand());
49271       DAG.ReplaceAllUsesOfValueWith(
49272           Op0, extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits()));
49273       DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
49274       return BcastLd;
49275     }
49276 
49277     // If this is a simple subvector load repeated across multiple lanes, then
49278     // broadcast the load. Update other uses to use an extracted subvector.
49279     if (auto *Ld = dyn_cast<LoadSDNode>(Op0)) {
49280       if (Ld->isSimple() && !Ld->isNonTemporal() &&
49281           Ld->getExtensionType() == ISD::NON_EXTLOAD) {
49282         SDVTList Tys = DAG.getVTList(VT, MVT::Other);
49283         SDValue Ops[] = {Ld->getChain(), Ld->getBasePtr()};
49284         SDValue BcastLd =
49285             DAG.getMemIntrinsicNode(X86ISD::SUBV_BROADCAST_LOAD, DL, Tys, Ops,
49286                                     Ld->getMemoryVT(), Ld->getMemOperand());
49287         DAG.ReplaceAllUsesOfValueWith(
49288             Op0,
49289             extractSubVector(BcastLd, 0, DAG, DL, Op0.getValueSizeInBits()));
49290         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), BcastLd.getValue(1));
49291         return BcastLd;
49292       }
49293     }
49294 
49295     // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
49296     if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
49297         (Subtarget.hasAVX2() || MayFoldLoad(Op0.getOperand(0))))
49298       return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
49299                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
49300                                      Op0.getOperand(0),
49301                                      DAG.getIntPtrConstant(0, DL)));
49302 
49303     // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
49304     if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
49305         (Subtarget.hasAVX2() ||
49306          (EltSizeInBits >= 32 && MayFoldLoad(Op0.getOperand(0)))) &&
49307         Op0.getOperand(0).getValueType() == VT.getScalarType())
49308       return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
49309 
49310     // concat_vectors(extract_subvector(broadcast(x)),
49311     //                extract_subvector(broadcast(x))) -> broadcast(x)
49312     if (Op0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
49313         Op0.getOperand(0).getValueType() == VT) {
49314       if (Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST ||
49315           Op0.getOperand(0).getOpcode() == X86ISD::VBROADCAST_LOAD)
49316         return Op0.getOperand(0);
49317     }
49318   }
49319 
49320   // Repeated opcode.
49321   // TODO - combineX86ShufflesRecursively should handle shuffle concatenation
49322   // but it currently struggles with different vector widths.
49323   if (llvm::all_of(Ops, [Op0](SDValue Op) {
49324         return Op.getOpcode() == Op0.getOpcode();
49325       })) {
49326     unsigned NumOps = Ops.size();
49327     switch (Op0.getOpcode()) {
49328     case X86ISD::SHUFP: {
49329       // Add SHUFPD support if/when necessary.
49330       if (!IsSplat && VT.getScalarType() == MVT::f32 &&
49331           llvm::all_of(Ops, [Op0](SDValue Op) {
49332             return Op.getOperand(2) == Op0.getOperand(2);
49333           })) {
49334         SmallVector<SDValue, 2> LHS, RHS;
49335         for (unsigned i = 0; i != NumOps; ++i) {
49336           LHS.push_back(Ops[i].getOperand(0));
49337           RHS.push_back(Ops[i].getOperand(1));
49338         }
49339         return DAG.getNode(Op0.getOpcode(), DL, VT,
49340                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS),
49341                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, RHS),
49342                            Op0.getOperand(2));
49343       }
49344       break;
49345     }
49346     case X86ISD::PSHUFHW:
49347     case X86ISD::PSHUFLW:
49348     case X86ISD::PSHUFD:
49349       if (!IsSplat && NumOps == 2 && VT.is256BitVector() &&
49350           Subtarget.hasInt256() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
49351         SmallVector<SDValue, 2> Src;
49352         for (unsigned i = 0; i != NumOps; ++i)
49353           Src.push_back(Ops[i].getOperand(0));
49354         return DAG.getNode(Op0.getOpcode(), DL, VT,
49355                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
49356                            Op0.getOperand(1));
49357       }
49358       LLVM_FALLTHROUGH;
49359     case X86ISD::VPERMILPI:
49360       // TODO - add support for vXf64/vXi64 shuffles.
49361       if (!IsSplat && NumOps == 2 && (VT == MVT::v8f32 || VT == MVT::v8i32) &&
49362           Subtarget.hasAVX() && Op0.getOperand(1) == Ops[1].getOperand(1)) {
49363         SmallVector<SDValue, 2> Src;
49364         for (unsigned i = 0; i != NumOps; ++i)
49365           Src.push_back(DAG.getBitcast(MVT::v4f32, Ops[i].getOperand(0)));
49366         SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8f32, Src);
49367         Res = DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, Res,
49368                           Op0.getOperand(1));
49369         return DAG.getBitcast(VT, Res);
49370       }
49371       break;
49372     case X86ISD::VPERMV3:
49373       if (!IsSplat && NumOps == 2 && VT.is512BitVector()) {
49374         MVT OpVT = Op0.getSimpleValueType();
49375         int NumSrcElts = OpVT.getVectorNumElements();
49376         SmallVector<int, 64> ConcatMask;
49377         for (unsigned i = 0; i != NumOps; ++i) {
49378           bool IsUnary;
49379           SmallVector<int, 64> SubMask;
49380           SmallVector<SDValue, 2> SubOps;
49381           if (!getTargetShuffleMask(Ops[i].getNode(), OpVT, false, SubOps,
49382                                     SubMask, IsUnary))
49383             break;
49384           for (int M : SubMask) {
49385             if (0 <= M) {
49386               M += M < NumSrcElts ? 0 : NumSrcElts;
49387               M += i * NumSrcElts;
49388             }
49389             ConcatMask.push_back(M);
49390           }
49391         }
49392         if (ConcatMask.size() == (NumOps * NumSrcElts)) {
49393           SDValue Src0 = concatSubVectors(Ops[0].getOperand(0),
49394                                           Ops[1].getOperand(0), DAG, DL);
49395           SDValue Src1 = concatSubVectors(Ops[0].getOperand(2),
49396                                           Ops[1].getOperand(2), DAG, DL);
49397           MVT IntMaskSVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
49398           MVT IntMaskVT = MVT::getVectorVT(IntMaskSVT, NumOps * NumSrcElts);
49399           SDValue Mask = getConstVector(ConcatMask, IntMaskVT, DAG, DL, true);
49400           return DAG.getNode(X86ISD::VPERMV3, DL, VT, Src0, Mask, Src1);
49401         }
49402       }
49403       break;
49404     case X86ISD::VSHLI:
49405     case X86ISD::VSRAI:
49406     case X86ISD::VSRLI:
49407       if (((VT.is256BitVector() && Subtarget.hasInt256()) ||
49408            (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
49409             (EltSizeInBits >= 32 || Subtarget.useBWIRegs()))) &&
49410           llvm::all_of(Ops, [Op0](SDValue Op) {
49411             return Op0.getOperand(1) == Op.getOperand(1);
49412           })) {
49413         SmallVector<SDValue, 2> Src;
49414         for (unsigned i = 0; i != NumOps; ++i)
49415           Src.push_back(Ops[i].getOperand(0));
49416         return DAG.getNode(Op0.getOpcode(), DL, VT,
49417                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
49418                            Op0.getOperand(1));
49419       }
49420       break;
49421     case X86ISD::VPERMI:
49422     case X86ISD::VROTLI:
49423     case X86ISD::VROTRI:
49424       if (VT.is512BitVector() && Subtarget.useAVX512Regs() &&
49425           llvm::all_of(Ops, [Op0](SDValue Op) {
49426             return Op0.getOperand(1) == Op.getOperand(1);
49427           })) {
49428         SmallVector<SDValue, 2> Src;
49429         for (unsigned i = 0; i != NumOps; ++i)
49430           Src.push_back(Ops[i].getOperand(0));
49431         return DAG.getNode(Op0.getOpcode(), DL, VT,
49432                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Src),
49433                            Op0.getOperand(1));
49434       }
49435       break;
49436     case ISD::AND:
49437     case ISD::OR:
49438     case ISD::XOR:
49439     case X86ISD::ANDNP:
49440       // TODO: Add 256-bit support.
49441       if (!IsSplat && VT.is512BitVector()) {
49442         SmallVector<SDValue, 2> LHS, RHS;
49443         for (unsigned i = 0; i != NumOps; ++i) {
49444           LHS.push_back(Ops[i].getOperand(0));
49445           RHS.push_back(Ops[i].getOperand(1));
49446         }
49447         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
49448         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
49449                                  NumOps * SrcVT.getVectorNumElements());
49450         return DAG.getNode(Op0.getOpcode(), DL, VT,
49451                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, LHS),
49452                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, RHS));
49453       }
49454       break;
49455     case X86ISD::HADD:
49456     case X86ISD::HSUB:
49457     case X86ISD::FHADD:
49458     case X86ISD::FHSUB:
49459     case X86ISD::PACKSS:
49460     case X86ISD::PACKUS:
49461       if (!IsSplat && VT.is256BitVector() &&
49462           (VT.isFloatingPoint() || Subtarget.hasInt256())) {
49463         SmallVector<SDValue, 2> LHS, RHS;
49464         for (unsigned i = 0; i != NumOps; ++i) {
49465           LHS.push_back(Ops[i].getOperand(0));
49466           RHS.push_back(Ops[i].getOperand(1));
49467         }
49468         MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
49469         SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
49470                                  NumOps * SrcVT.getVectorNumElements());
49471         return DAG.getNode(Op0.getOpcode(), DL, VT,
49472                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, LHS),
49473                            DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, RHS));
49474       }
49475       break;
49476     case X86ISD::PALIGNR:
49477       if (!IsSplat &&
49478           ((VT.is256BitVector() && Subtarget.hasInt256()) ||
49479            (VT.is512BitVector() && Subtarget.useBWIRegs())) &&
49480           llvm::all_of(Ops, [Op0](SDValue Op) {
49481             return Op0.getOperand(2) == Op.getOperand(2);
49482           })) {
49483         SmallVector<SDValue, 2> LHS, RHS;
49484         for (unsigned i = 0; i != NumOps; ++i) {
49485           LHS.push_back(Ops[i].getOperand(0));
49486           RHS.push_back(Ops[i].getOperand(1));
49487         }
49488         return DAG.getNode(Op0.getOpcode(), DL, VT,
49489                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS),
49490                            DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, RHS),
49491                            Op0.getOperand(2));
49492       }
49493       break;
49494     }
49495   }
49496 
49497   // Fold subvector loads into one.
49498   // If needed, look through bitcasts to get to the load.
49499   if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
49500     bool Fast;
49501     const X86TargetLowering *TLI = Subtarget.getTargetLowering();
49502     if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
49503                                 *FirstLd->getMemOperand(), &Fast) &&
49504         Fast) {
49505       if (SDValue Ld =
49506               EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
49507         return Ld;
49508     }
49509   }
49510 
49511   return SDValue();
49512 }
49513 
49514 static SDValue combineConcatVectors(SDNode *N, SelectionDAG &DAG,
49515                                     TargetLowering::DAGCombinerInfo &DCI,
49516                                     const X86Subtarget &Subtarget) {
49517   EVT VT = N->getValueType(0);
49518   EVT SrcVT = N->getOperand(0).getValueType();
49519   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49520 
49521   // Don't do anything for i1 vectors.
49522   if (VT.getVectorElementType() == MVT::i1)
49523     return SDValue();
49524 
49525   if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
49526     SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
49527     if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
49528                                            DCI, Subtarget))
49529       return R;
49530   }
49531 
49532   return SDValue();
49533 }
49534 
49535 static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
49536                                       TargetLowering::DAGCombinerInfo &DCI,
49537                                       const X86Subtarget &Subtarget) {
49538   if (DCI.isBeforeLegalizeOps())
49539     return SDValue();
49540 
49541   MVT OpVT = N->getSimpleValueType(0);
49542 
49543   bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
49544 
49545   SDLoc dl(N);
49546   SDValue Vec = N->getOperand(0);
49547   SDValue SubVec = N->getOperand(1);
49548 
49549   uint64_t IdxVal = N->getConstantOperandVal(2);
49550   MVT SubVecVT = SubVec.getSimpleValueType();
49551 
49552   if (Vec.isUndef() && SubVec.isUndef())
49553     return DAG.getUNDEF(OpVT);
49554 
49555   // Inserting undefs/zeros into zeros/undefs is a zero vector.
49556   if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
49557       (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
49558     return getZeroVector(OpVT, Subtarget, DAG, dl);
49559 
49560   if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
49561     // If we're inserting into a zero vector and then into a larger zero vector,
49562     // just insert into the larger zero vector directly.
49563     if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
49564         ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
49565       uint64_t Idx2Val = SubVec.getConstantOperandVal(2);
49566       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
49567                          getZeroVector(OpVT, Subtarget, DAG, dl),
49568                          SubVec.getOperand(1),
49569                          DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
49570     }
49571 
49572     // If we're inserting into a zero vector and our input was extracted from an
49573     // insert into a zero vector of the same type and the extraction was at
49574     // least as large as the original insertion. Just insert the original
49575     // subvector into a zero vector.
49576     if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
49577         isNullConstant(SubVec.getOperand(1)) &&
49578         SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
49579       SDValue Ins = SubVec.getOperand(0);
49580       if (isNullConstant(Ins.getOperand(2)) &&
49581           ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
49582           Ins.getOperand(1).getValueSizeInBits().getFixedSize() <=
49583               SubVecVT.getFixedSizeInBits())
49584         return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
49585                            getZeroVector(OpVT, Subtarget, DAG, dl),
49586                            Ins.getOperand(1), N->getOperand(2));
49587     }
49588   }
49589 
49590   // Stop here if this is an i1 vector.
49591   if (IsI1Vector)
49592     return SDValue();
49593 
49594   // If this is an insert of an extract, combine to a shuffle. Don't do this
49595   // if the insert or extract can be represented with a subregister operation.
49596   if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
49597       SubVec.getOperand(0).getSimpleValueType() == OpVT &&
49598       (IdxVal != 0 ||
49599        !(Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())))) {
49600     int ExtIdxVal = SubVec.getConstantOperandVal(1);
49601     if (ExtIdxVal != 0) {
49602       int VecNumElts = OpVT.getVectorNumElements();
49603       int SubVecNumElts = SubVecVT.getVectorNumElements();
49604       SmallVector<int, 64> Mask(VecNumElts);
49605       // First create an identity shuffle mask.
49606       for (int i = 0; i != VecNumElts; ++i)
49607         Mask[i] = i;
49608       // Now insert the extracted portion.
49609       for (int i = 0; i != SubVecNumElts; ++i)
49610         Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
49611 
49612       return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
49613     }
49614   }
49615 
49616   // Match concat_vector style patterns.
49617   SmallVector<SDValue, 2> SubVectorOps;
49618   if (collectConcatOps(N, SubVectorOps)) {
49619     if (SDValue Fold =
49620             combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
49621       return Fold;
49622 
49623     // If we're inserting all zeros into the upper half, change this to
49624     // a concat with zero. We will match this to a move
49625     // with implicit upper bit zeroing during isel.
49626     // We do this here because we don't want combineConcatVectorOps to
49627     // create INSERT_SUBVECTOR from CONCAT_VECTORS.
49628     if (SubVectorOps.size() == 2 &&
49629         ISD::isBuildVectorAllZeros(SubVectorOps[1].getNode()))
49630       return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
49631                          getZeroVector(OpVT, Subtarget, DAG, dl),
49632                          SubVectorOps[0], DAG.getIntPtrConstant(0, dl));
49633   }
49634 
49635   // If this is a broadcast insert into an upper undef, use a larger broadcast.
49636   if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
49637     return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
49638 
49639   // If this is a broadcast load inserted into an upper undef, use a larger
49640   // broadcast load.
49641   if (Vec.isUndef() && IdxVal != 0 && SubVec.hasOneUse() &&
49642       SubVec.getOpcode() == X86ISD::VBROADCAST_LOAD) {
49643     auto *MemIntr = cast<MemIntrinsicSDNode>(SubVec);
49644     SDVTList Tys = DAG.getVTList(OpVT, MVT::Other);
49645     SDValue Ops[] = { MemIntr->getChain(), MemIntr->getBasePtr() };
49646     SDValue BcastLd =
49647         DAG.getMemIntrinsicNode(X86ISD::VBROADCAST_LOAD, dl, Tys, Ops,
49648                                 MemIntr->getMemoryVT(),
49649                                 MemIntr->getMemOperand());
49650     DAG.ReplaceAllUsesOfValueWith(SDValue(MemIntr, 1), BcastLd.getValue(1));
49651     return BcastLd;
49652   }
49653 
49654   return SDValue();
49655 }
49656 
49657 /// If we are extracting a subvector of a vector select and the select condition
49658 /// is composed of concatenated vectors, try to narrow the select width. This
49659 /// is a common pattern for AVX1 integer code because 256-bit selects may be
49660 /// legal, but there is almost no integer math/logic available for 256-bit.
49661 /// This function should only be called with legal types (otherwise, the calls
49662 /// to get simple value types will assert).
49663 static SDValue narrowExtractedVectorSelect(SDNode *Ext, SelectionDAG &DAG) {
49664   SDValue Sel = peekThroughBitcasts(Ext->getOperand(0));
49665   SmallVector<SDValue, 4> CatOps;
49666   if (Sel.getOpcode() != ISD::VSELECT ||
49667       !collectConcatOps(Sel.getOperand(0).getNode(), CatOps))
49668     return SDValue();
49669 
49670   // Note: We assume simple value types because this should only be called with
49671   //       legal operations/types.
49672   // TODO: This can be extended to handle extraction to 256-bits.
49673   MVT VT = Ext->getSimpleValueType(0);
49674   if (!VT.is128BitVector())
49675     return SDValue();
49676 
49677   MVT SelCondVT = Sel.getOperand(0).getSimpleValueType();
49678   if (!SelCondVT.is256BitVector() && !SelCondVT.is512BitVector())
49679     return SDValue();
49680 
49681   MVT WideVT = Ext->getOperand(0).getSimpleValueType();
49682   MVT SelVT = Sel.getSimpleValueType();
49683   assert((SelVT.is256BitVector() || SelVT.is512BitVector()) &&
49684          "Unexpected vector type with legal operations");
49685 
49686   unsigned SelElts = SelVT.getVectorNumElements();
49687   unsigned CastedElts = WideVT.getVectorNumElements();
49688   unsigned ExtIdx = Ext->getConstantOperandVal(1);
49689   if (SelElts % CastedElts == 0) {
49690     // The select has the same or more (narrower) elements than the extract
49691     // operand. The extraction index gets scaled by that factor.
49692     ExtIdx *= (SelElts / CastedElts);
49693   } else if (CastedElts % SelElts == 0) {
49694     // The select has less (wider) elements than the extract operand. Make sure
49695     // that the extraction index can be divided evenly.
49696     unsigned IndexDivisor = CastedElts / SelElts;
49697     if (ExtIdx % IndexDivisor != 0)
49698       return SDValue();
49699     ExtIdx /= IndexDivisor;
49700   } else {
49701     llvm_unreachable("Element count of simple vector types are not divisible?");
49702   }
49703 
49704   unsigned NarrowingFactor = WideVT.getSizeInBits() / VT.getSizeInBits();
49705   unsigned NarrowElts = SelElts / NarrowingFactor;
49706   MVT NarrowSelVT = MVT::getVectorVT(SelVT.getVectorElementType(), NarrowElts);
49707   SDLoc DL(Ext);
49708   SDValue ExtCond = extract128BitVector(Sel.getOperand(0), ExtIdx, DAG, DL);
49709   SDValue ExtT = extract128BitVector(Sel.getOperand(1), ExtIdx, DAG, DL);
49710   SDValue ExtF = extract128BitVector(Sel.getOperand(2), ExtIdx, DAG, DL);
49711   SDValue NarrowSel = DAG.getSelect(DL, NarrowSelVT, ExtCond, ExtT, ExtF);
49712   return DAG.getBitcast(VT, NarrowSel);
49713 }
49714 
49715 static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
49716                                        TargetLowering::DAGCombinerInfo &DCI,
49717                                        const X86Subtarget &Subtarget) {
49718   // For AVX1 only, if we are extracting from a 256-bit and+not (which will
49719   // eventually get combined/lowered into ANDNP) with a concatenated operand,
49720   // split the 'and' into 128-bit ops to avoid the concatenate and extract.
49721   // We let generic combining take over from there to simplify the
49722   // insert/extract and 'not'.
49723   // This pattern emerges during AVX1 legalization. We handle it before lowering
49724   // to avoid complications like splitting constant vector loads.
49725 
49726   // Capture the original wide type in the likely case that we need to bitcast
49727   // back to this type.
49728   if (!N->getValueType(0).isSimple())
49729     return SDValue();
49730 
49731   MVT VT = N->getSimpleValueType(0);
49732   SDValue InVec = N->getOperand(0);
49733   unsigned IdxVal = N->getConstantOperandVal(1);
49734   SDValue InVecBC = peekThroughBitcasts(InVec);
49735   EVT InVecVT = InVec.getValueType();
49736   unsigned SizeInBits = VT.getSizeInBits();
49737   unsigned InSizeInBits = InVecVT.getSizeInBits();
49738   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49739 
49740   if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
49741       TLI.isTypeLegal(InVecVT) &&
49742       InSizeInBits == 256 && InVecBC.getOpcode() == ISD::AND) {
49743     auto isConcatenatedNot = [](SDValue V) {
49744       V = peekThroughBitcasts(V);
49745       if (!isBitwiseNot(V))
49746         return false;
49747       SDValue NotOp = V->getOperand(0);
49748       return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
49749     };
49750     if (isConcatenatedNot(InVecBC.getOperand(0)) ||
49751         isConcatenatedNot(InVecBC.getOperand(1))) {
49752       // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
49753       SDValue Concat = splitVectorIntBinary(InVecBC, DAG);
49754       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
49755                          DAG.getBitcast(InVecVT, Concat), N->getOperand(1));
49756     }
49757   }
49758 
49759   if (DCI.isBeforeLegalizeOps())
49760     return SDValue();
49761 
49762   if (SDValue V = narrowExtractedVectorSelect(N, DAG))
49763     return V;
49764 
49765   if (ISD::isBuildVectorAllZeros(InVec.getNode()))
49766     return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
49767 
49768   if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
49769     if (VT.getScalarType() == MVT::i1)
49770       return DAG.getConstant(1, SDLoc(N), VT);
49771     return getOnesVector(VT, DAG, SDLoc(N));
49772   }
49773 
49774   if (InVec.getOpcode() == ISD::BUILD_VECTOR)
49775     return DAG.getBuildVector(
49776         VT, SDLoc(N),
49777         InVec.getNode()->ops().slice(IdxVal, VT.getVectorNumElements()));
49778 
49779   // If we are extracting from an insert into a zero vector, replace with a
49780   // smaller insert into zero if we don't access less than the original
49781   // subvector. Don't do this for i1 vectors.
49782   if (VT.getVectorElementType() != MVT::i1 &&
49783       InVec.getOpcode() == ISD::INSERT_SUBVECTOR && IdxVal == 0 &&
49784       InVec.hasOneUse() && isNullConstant(InVec.getOperand(2)) &&
49785       ISD::isBuildVectorAllZeros(InVec.getOperand(0).getNode()) &&
49786       InVec.getOperand(1).getValueSizeInBits() <= SizeInBits) {
49787     SDLoc DL(N);
49788     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
49789                        getZeroVector(VT, Subtarget, DAG, DL),
49790                        InVec.getOperand(1), InVec.getOperand(2));
49791   }
49792 
49793   // If we're extracting an upper subvector from a broadcast we should just
49794   // extract the lowest subvector instead which should allow
49795   // SimplifyDemandedVectorElts do more simplifications.
49796   if (IdxVal != 0 && (InVec.getOpcode() == X86ISD::VBROADCAST ||
49797                       InVec.getOpcode() == X86ISD::VBROADCAST_LOAD))
49798     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
49799 
49800   // If we're extracting a broadcasted subvector, just use the lowest subvector.
49801   if (IdxVal != 0 && InVec.getOpcode() == X86ISD::SUBV_BROADCAST_LOAD &&
49802       cast<MemIntrinsicSDNode>(InVec)->getMemoryVT() == VT)
49803     return extractSubVector(InVec, 0, DAG, SDLoc(N), SizeInBits);
49804 
49805   // Attempt to extract from the source of a shuffle vector.
49806   if ((InSizeInBits % SizeInBits) == 0 &&
49807       (IdxVal % VT.getVectorNumElements()) == 0) {
49808     SmallVector<int, 32> ShuffleMask;
49809     SmallVector<int, 32> ScaledMask;
49810     SmallVector<SDValue, 2> ShuffleInputs;
49811     unsigned NumSubVecs = InSizeInBits / SizeInBits;
49812     // Decode the shuffle mask and scale it so its shuffling subvectors.
49813     if (getTargetShuffleInputs(InVecBC, ShuffleInputs, ShuffleMask, DAG) &&
49814         scaleShuffleElements(ShuffleMask, NumSubVecs, ScaledMask)) {
49815       unsigned SubVecIdx = IdxVal / VT.getVectorNumElements();
49816       if (ScaledMask[SubVecIdx] == SM_SentinelUndef)
49817         return DAG.getUNDEF(VT);
49818       if (ScaledMask[SubVecIdx] == SM_SentinelZero)
49819         return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
49820       SDValue Src = ShuffleInputs[ScaledMask[SubVecIdx] / NumSubVecs];
49821       if (Src.getValueSizeInBits() == InSizeInBits) {
49822         unsigned SrcSubVecIdx = ScaledMask[SubVecIdx] % NumSubVecs;
49823         unsigned SrcEltIdx = SrcSubVecIdx * VT.getVectorNumElements();
49824         return extractSubVector(DAG.getBitcast(InVecVT, Src), SrcEltIdx, DAG,
49825                                 SDLoc(N), SizeInBits);
49826       }
49827     }
49828   }
49829 
49830   // If we're extracting the lowest subvector and we're the only user,
49831   // we may be able to perform this with a smaller vector width.
49832   unsigned InOpcode = InVec.getOpcode();
49833   if (IdxVal == 0 && InVec.hasOneUse()) {
49834     if (VT == MVT::v2f64 && InVecVT == MVT::v4f64) {
49835       // v2f64 CVTDQ2PD(v4i32).
49836       if (InOpcode == ISD::SINT_TO_FP &&
49837           InVec.getOperand(0).getValueType() == MVT::v4i32) {
49838         return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
49839       }
49840       // v2f64 CVTUDQ2PD(v4i32).
49841       if (InOpcode == ISD::UINT_TO_FP && Subtarget.hasVLX() &&
49842           InVec.getOperand(0).getValueType() == MVT::v4i32) {
49843         return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
49844       }
49845       // v2f64 CVTPS2PD(v4f32).
49846       if (InOpcode == ISD::FP_EXTEND &&
49847           InVec.getOperand(0).getValueType() == MVT::v4f32) {
49848         return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
49849       }
49850     }
49851     if ((InOpcode == ISD::ANY_EXTEND ||
49852          InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
49853          InOpcode == ISD::ZERO_EXTEND ||
49854          InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
49855          InOpcode == ISD::SIGN_EXTEND ||
49856          InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
49857         (SizeInBits == 128 || SizeInBits == 256) &&
49858         InVec.getOperand(0).getValueSizeInBits() >= SizeInBits) {
49859       SDLoc DL(N);
49860       SDValue Ext = InVec.getOperand(0);
49861       if (Ext.getValueSizeInBits() > SizeInBits)
49862         Ext = extractSubVector(Ext, 0, DAG, DL, SizeInBits);
49863       unsigned ExtOp = getOpcode_EXTEND_VECTOR_INREG(InOpcode);
49864       return DAG.getNode(ExtOp, DL, VT, Ext);
49865     }
49866     if (InOpcode == ISD::VSELECT &&
49867         InVec.getOperand(0).getValueType().is256BitVector() &&
49868         InVec.getOperand(1).getValueType().is256BitVector() &&
49869         InVec.getOperand(2).getValueType().is256BitVector()) {
49870       SDLoc DL(N);
49871       SDValue Ext0 = extractSubVector(InVec.getOperand(0), 0, DAG, DL, 128);
49872       SDValue Ext1 = extractSubVector(InVec.getOperand(1), 0, DAG, DL, 128);
49873       SDValue Ext2 = extractSubVector(InVec.getOperand(2), 0, DAG, DL, 128);
49874       return DAG.getNode(InOpcode, DL, VT, Ext0, Ext1, Ext2);
49875     }
49876     if (InOpcode == ISD::TRUNCATE && Subtarget.hasVLX() &&
49877         (VT.is128BitVector() || VT.is256BitVector())) {
49878       SDLoc DL(N);
49879       SDValue InVecSrc = InVec.getOperand(0);
49880       unsigned Scale = InVecSrc.getValueSizeInBits() / InSizeInBits;
49881       SDValue Ext = extractSubVector(InVecSrc, 0, DAG, DL, Scale * SizeInBits);
49882       return DAG.getNode(InOpcode, DL, VT, Ext);
49883     }
49884   }
49885 
49886   // Always split vXi64 logical shifts where we're extracting the upper 32-bits
49887   // as this is very likely to fold into a shuffle/truncation.
49888   if ((InOpcode == X86ISD::VSHLI || InOpcode == X86ISD::VSRLI) &&
49889       InVecVT.getScalarSizeInBits() == 64 &&
49890       InVec.getConstantOperandAPInt(1) == 32) {
49891     SDLoc DL(N);
49892     SDValue Ext =
49893         extractSubVector(InVec.getOperand(0), IdxVal, DAG, DL, SizeInBits);
49894     return DAG.getNode(InOpcode, DL, VT, Ext, InVec.getOperand(1));
49895   }
49896 
49897   return SDValue();
49898 }
49899 
49900 static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
49901   EVT VT = N->getValueType(0);
49902   SDValue Src = N->getOperand(0);
49903   SDLoc DL(N);
49904 
49905   // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
49906   // This occurs frequently in our masked scalar intrinsic code and our
49907   // floating point select lowering with AVX512.
49908   // TODO: SimplifyDemandedBits instead?
49909   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
49910     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
49911       if (C->getAPIntValue().isOneValue())
49912         return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
49913                            Src.getOperand(0));
49914 
49915   // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
49916   if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
49917       Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
49918       Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
49919     if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
49920       if (C->isNullValue())
49921         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
49922                            Src.getOperand(1));
49923 
49924   // Reduce v2i64 to v4i32 if we don't need the upper bits.
49925   // TODO: Move to DAGCombine/SimplifyDemandedBits?
49926   if (VT == MVT::v2i64 || VT == MVT::v2f64) {
49927     auto IsAnyExt64 = [](SDValue Op) {
49928       if (Op.getValueType() != MVT::i64 || !Op.hasOneUse())
49929         return SDValue();
49930       if (Op.getOpcode() == ISD::ANY_EXTEND &&
49931           Op.getOperand(0).getScalarValueSizeInBits() <= 32)
49932         return Op.getOperand(0);
49933       if (auto *Ld = dyn_cast<LoadSDNode>(Op))
49934         if (Ld->getExtensionType() == ISD::EXTLOAD &&
49935             Ld->getMemoryVT().getScalarSizeInBits() <= 32)
49936           return Op;
49937       return SDValue();
49938     };
49939     if (SDValue ExtSrc = IsAnyExt64(peekThroughOneUseBitcasts(Src)))
49940       return DAG.getBitcast(
49941           VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
49942                           DAG.getAnyExtOrTrunc(ExtSrc, DL, MVT::i32)));
49943   }
49944 
49945   // Combine (v2i64 (scalar_to_vector (i64 (bitconvert (mmx))))) to MOVQ2DQ.
49946   if (VT == MVT::v2i64 && Src.getOpcode() == ISD::BITCAST &&
49947       Src.getOperand(0).getValueType() == MVT::x86mmx)
49948     return DAG.getNode(X86ISD::MOVQ2DQ, DL, VT, Src.getOperand(0));
49949 
49950   return SDValue();
49951 }
49952 
49953 // Simplify PMULDQ and PMULUDQ operations.
49954 static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
49955                              TargetLowering::DAGCombinerInfo &DCI,
49956                              const X86Subtarget &Subtarget) {
49957   SDValue LHS = N->getOperand(0);
49958   SDValue RHS = N->getOperand(1);
49959 
49960   // Canonicalize constant to RHS.
49961   if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
49962       !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
49963     return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
49964 
49965   // Multiply by zero.
49966   // Don't return RHS as it may contain UNDEFs.
49967   if (ISD::isBuildVectorAllZeros(RHS.getNode()))
49968     return DAG.getConstant(0, SDLoc(N), N->getValueType(0));
49969 
49970   // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
49971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
49972   if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnesValue(64), DCI))
49973     return SDValue(N, 0);
49974 
49975   // If the input is an extend_invec and the SimplifyDemandedBits call didn't
49976   // convert it to any_extend_invec, due to the LegalOperations check, do the
49977   // conversion directly to a vector shuffle manually. This exposes combine
49978   // opportunities missed by combineEXTEND_VECTOR_INREG not calling
49979   // combineX86ShufflesRecursively on SSE4.1 targets.
49980   // FIXME: This is basically a hack around several other issues related to
49981   // ANY_EXTEND_VECTOR_INREG.
49982   if (N->getValueType(0) == MVT::v2i64 && LHS.hasOneUse() &&
49983       (LHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
49984        LHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
49985       LHS.getOperand(0).getValueType() == MVT::v4i32) {
49986     SDLoc dl(N);
49987     LHS = DAG.getVectorShuffle(MVT::v4i32, dl, LHS.getOperand(0),
49988                                LHS.getOperand(0), { 0, -1, 1, -1 });
49989     LHS = DAG.getBitcast(MVT::v2i64, LHS);
49990     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
49991   }
49992   if (N->getValueType(0) == MVT::v2i64 && RHS.hasOneUse() &&
49993       (RHS.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG ||
49994        RHS.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG) &&
49995       RHS.getOperand(0).getValueType() == MVT::v4i32) {
49996     SDLoc dl(N);
49997     RHS = DAG.getVectorShuffle(MVT::v4i32, dl, RHS.getOperand(0),
49998                                RHS.getOperand(0), { 0, -1, 1, -1 });
49999     RHS = DAG.getBitcast(MVT::v2i64, RHS);
50000     return DAG.getNode(N->getOpcode(), dl, MVT::v2i64, LHS, RHS);
50001   }
50002 
50003   return SDValue();
50004 }
50005 
50006 static SDValue combineEXTEND_VECTOR_INREG(SDNode *N, SelectionDAG &DAG,
50007                                           TargetLowering::DAGCombinerInfo &DCI,
50008                                           const X86Subtarget &Subtarget) {
50009   EVT VT = N->getValueType(0);
50010   SDValue In = N->getOperand(0);
50011   unsigned Opcode = N->getOpcode();
50012   unsigned InOpcode = In.getOpcode();
50013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50014 
50015   // Try to merge vector loads and extend_inreg to an extload.
50016   if (!DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(In.getNode()) &&
50017       In.hasOneUse()) {
50018     auto *Ld = cast<LoadSDNode>(In);
50019     if (Ld->isSimple()) {
50020       MVT SVT = In.getSimpleValueType().getVectorElementType();
50021       ISD::LoadExtType Ext = Opcode == ISD::SIGN_EXTEND_VECTOR_INREG
50022                                  ? ISD::SEXTLOAD
50023                                  : ISD::ZEXTLOAD;
50024       EVT MemVT =
50025           EVT::getVectorVT(*DAG.getContext(), SVT, VT.getVectorNumElements());
50026       if (TLI.isLoadExtLegal(Ext, VT, MemVT)) {
50027         SDValue Load =
50028             DAG.getExtLoad(Ext, SDLoc(N), VT, Ld->getChain(), Ld->getBasePtr(),
50029                            Ld->getPointerInfo(), MemVT, Ld->getOriginalAlign(),
50030                            Ld->getMemOperand()->getFlags());
50031         DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
50032         return Load;
50033       }
50034     }
50035   }
50036 
50037   // Fold EXTEND_VECTOR_INREG(EXTEND_VECTOR_INREG(X)) -> EXTEND_VECTOR_INREG(X).
50038   if (Opcode == InOpcode)
50039     return DAG.getNode(Opcode, SDLoc(N), VT, In.getOperand(0));
50040 
50041   // Fold EXTEND_VECTOR_INREG(EXTRACT_SUBVECTOR(EXTEND(X),0))
50042   // -> EXTEND_VECTOR_INREG(X).
50043   // TODO: Handle non-zero subvector indices.
50044   if (InOpcode == ISD::EXTRACT_SUBVECTOR && In.getConstantOperandVal(1) == 0 &&
50045       In.getOperand(0).getOpcode() == getOpcode_EXTEND(Opcode) &&
50046       In.getOperand(0).getOperand(0).getValueSizeInBits() ==
50047           In.getValueSizeInBits())
50048     return DAG.getNode(Opcode, SDLoc(N), VT, In.getOperand(0).getOperand(0));
50049 
50050   // Attempt to combine as a shuffle.
50051   // TODO: General ZERO_EXTEND_VECTOR_INREG support.
50052   if (Opcode == ISD::ANY_EXTEND_VECTOR_INREG ||
50053       (Opcode == ISD::ZERO_EXTEND_VECTOR_INREG && Subtarget.hasSSE41())) {
50054     SDValue Op(N, 0);
50055     if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
50056       if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
50057         return Res;
50058   }
50059 
50060   return SDValue();
50061 }
50062 
50063 static SDValue combineKSHIFT(SDNode *N, SelectionDAG &DAG,
50064                              TargetLowering::DAGCombinerInfo &DCI) {
50065   EVT VT = N->getValueType(0);
50066 
50067   if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
50068     return DAG.getConstant(0, SDLoc(N), VT);
50069 
50070   APInt KnownUndef, KnownZero;
50071   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50072   APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
50073   if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
50074                                      KnownZero, DCI))
50075     return SDValue(N, 0);
50076 
50077   return SDValue();
50078 }
50079 
50080 // Optimize (fp16_to_fp (fp_to_fp16 X)) to VCVTPS2PH followed by VCVTPH2PS.
50081 // Done as a combine because the lowering for fp16_to_fp and fp_to_fp16 produce
50082 // extra instructions between the conversion due to going to scalar and back.
50083 static SDValue combineFP16_TO_FP(SDNode *N, SelectionDAG &DAG,
50084                                  const X86Subtarget &Subtarget) {
50085   if (Subtarget.useSoftFloat() || !Subtarget.hasF16C())
50086     return SDValue();
50087 
50088   if (N->getOperand(0).getOpcode() != ISD::FP_TO_FP16)
50089     return SDValue();
50090 
50091   if (N->getValueType(0) != MVT::f32 ||
50092       N->getOperand(0).getOperand(0).getValueType() != MVT::f32)
50093     return SDValue();
50094 
50095   SDLoc dl(N);
50096   SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32,
50097                             N->getOperand(0).getOperand(0));
50098   Res = DAG.getNode(X86ISD::CVTPS2PH, dl, MVT::v8i16, Res,
50099                     DAG.getTargetConstant(4, dl, MVT::i32));
50100   Res = DAG.getNode(X86ISD::CVTPH2PS, dl, MVT::v4f32, Res);
50101   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
50102                      DAG.getIntPtrConstant(0, dl));
50103 }
50104 
50105 static SDValue combineFP_EXTEND(SDNode *N, SelectionDAG &DAG,
50106                                 const X86Subtarget &Subtarget) {
50107   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
50108     return SDValue();
50109 
50110   bool IsStrict = N->isStrictFPOpcode();
50111   EVT VT = N->getValueType(0);
50112   SDValue Src = N->getOperand(IsStrict ? 1 : 0);
50113   EVT SrcVT = Src.getValueType();
50114 
50115   if (!SrcVT.isVector() || SrcVT.getVectorElementType() != MVT::f16)
50116     return SDValue();
50117 
50118   if (VT.getVectorElementType() != MVT::f32 &&
50119       VT.getVectorElementType() != MVT::f64)
50120     return SDValue();
50121 
50122   unsigned NumElts = VT.getVectorNumElements();
50123   if (NumElts == 1 || !isPowerOf2_32(NumElts))
50124     return SDValue();
50125 
50126   SDLoc dl(N);
50127 
50128   // Convert the input to vXi16.
50129   EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
50130   Src = DAG.getBitcast(IntVT, Src);
50131 
50132   // Widen to at least 8 input elements.
50133   if (NumElts < 8) {
50134     unsigned NumConcats = 8 / NumElts;
50135     SDValue Fill = NumElts == 4 ? DAG.getUNDEF(IntVT)
50136                                 : DAG.getConstant(0, dl, IntVT);
50137     SmallVector<SDValue, 4> Ops(NumConcats, Fill);
50138     Ops[0] = Src;
50139     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, Ops);
50140   }
50141 
50142   // Destination is vXf32 with at least 4 elements.
50143   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32,
50144                                std::max(4U, NumElts));
50145   SDValue Cvt, Chain;
50146   if (IsStrict) {
50147     Cvt = DAG.getNode(X86ISD::STRICT_CVTPH2PS, dl, {CvtVT, MVT::Other},
50148                       {N->getOperand(0), Src});
50149     Chain = Cvt.getValue(1);
50150   } else {
50151     Cvt = DAG.getNode(X86ISD::CVTPH2PS, dl, CvtVT, Src);
50152   }
50153 
50154   if (NumElts < 4) {
50155     assert(NumElts == 2 && "Unexpected size");
50156     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2f32, Cvt,
50157                       DAG.getIntPtrConstant(0, dl));
50158   }
50159 
50160   if (IsStrict) {
50161     // Extend to the original VT if necessary.
50162     if (Cvt.getValueType() != VT) {
50163       Cvt = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {VT, MVT::Other},
50164                         {Chain, Cvt});
50165       Chain = Cvt.getValue(1);
50166     }
50167     return DAG.getMergeValues({Cvt, Chain}, dl);
50168   }
50169 
50170   // Extend to the original VT if necessary.
50171   return DAG.getNode(ISD::FP_EXTEND, dl, VT, Cvt);
50172 }
50173 
50174 // Try to find a larger VBROADCAST_LOAD/SUBV_BROADCAST_LOAD that we can extract
50175 // from. Limit this to cases where the loads have the same input chain and the
50176 // output chains are unused. This avoids any memory ordering issues.
50177 static SDValue combineBROADCAST_LOAD(SDNode *N, SelectionDAG &DAG,
50178                                      TargetLowering::DAGCombinerInfo &DCI) {
50179   assert((N->getOpcode() == X86ISD::VBROADCAST_LOAD ||
50180           N->getOpcode() == X86ISD::SUBV_BROADCAST_LOAD) &&
50181          "Unknown broadcast load type");
50182 
50183   // Only do this if the chain result is unused.
50184   if (N->hasAnyUseOfValue(1))
50185     return SDValue();
50186 
50187   auto *MemIntrin = cast<MemIntrinsicSDNode>(N);
50188 
50189   SDValue Ptr = MemIntrin->getBasePtr();
50190   SDValue Chain = MemIntrin->getChain();
50191   EVT VT = N->getSimpleValueType(0);
50192   EVT MemVT = MemIntrin->getMemoryVT();
50193 
50194   // Look at other users of our base pointer and try to find a wider broadcast.
50195   // The input chain and the size of the memory VT must match.
50196   for (SDNode *User : Ptr->uses())
50197     if (User != N && User->getOpcode() == N->getOpcode() &&
50198         cast<MemIntrinsicSDNode>(User)->getBasePtr() == Ptr &&
50199         cast<MemIntrinsicSDNode>(User)->getChain() == Chain &&
50200         cast<MemIntrinsicSDNode>(User)->getMemoryVT().getSizeInBits() ==
50201             MemVT.getSizeInBits() &&
50202         !User->hasAnyUseOfValue(1) &&
50203         User->getValueSizeInBits(0).getFixedSize() > VT.getFixedSizeInBits()) {
50204       SDValue Extract = extractSubVector(SDValue(User, 0), 0, DAG, SDLoc(N),
50205                                          VT.getSizeInBits());
50206       Extract = DAG.getBitcast(VT, Extract);
50207       return DCI.CombineTo(N, Extract, SDValue(User, 1));
50208     }
50209 
50210   return SDValue();
50211 }
50212 
50213 static SDValue combineFP_ROUND(SDNode *N, SelectionDAG &DAG,
50214                                const X86Subtarget &Subtarget) {
50215   if (!Subtarget.hasF16C() || Subtarget.useSoftFloat())
50216     return SDValue();
50217 
50218   EVT VT = N->getValueType(0);
50219   SDValue Src = N->getOperand(0);
50220   EVT SrcVT = Src.getValueType();
50221 
50222   if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
50223       SrcVT.getVectorElementType() != MVT::f32)
50224     return SDValue();
50225 
50226   unsigned NumElts = VT.getVectorNumElements();
50227   if (NumElts == 1 || !isPowerOf2_32(NumElts))
50228     return SDValue();
50229 
50230   SDLoc dl(N);
50231 
50232   // Widen to at least 4 input elements.
50233   if (NumElts < 4)
50234     Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
50235                       DAG.getConstantFP(0.0, dl, SrcVT));
50236 
50237   // Destination is v8i16 with at least 8 elements.
50238   EVT CvtVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
50239                                std::max(8U, NumElts));
50240   SDValue Cvt = DAG.getNode(X86ISD::CVTPS2PH, dl, CvtVT, Src,
50241                             DAG.getTargetConstant(4, dl, MVT::i32));
50242 
50243   // Extract down to real number of elements.
50244   if (NumElts < 8) {
50245     EVT IntVT = VT.changeVectorElementTypeToInteger();
50246     Cvt = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, IntVT, Cvt,
50247                       DAG.getIntPtrConstant(0, dl));
50248   }
50249 
50250   return DAG.getBitcast(VT, Cvt);
50251 }
50252 
50253 static SDValue combineMOVDQ2Q(SDNode *N, SelectionDAG &DAG) {
50254   SDValue Src = N->getOperand(0);
50255 
50256   // Turn MOVDQ2Q+simple_load into an mmx load.
50257   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
50258     LoadSDNode *LN = cast<LoadSDNode>(Src.getNode());
50259 
50260     if (LN->isSimple()) {
50261       SDValue NewLd = DAG.getLoad(MVT::x86mmx, SDLoc(N), LN->getChain(),
50262                                   LN->getBasePtr(),
50263                                   LN->getPointerInfo(),
50264                                   LN->getOriginalAlign(),
50265                                   LN->getMemOperand()->getFlags());
50266       DAG.ReplaceAllUsesOfValueWith(SDValue(LN, 1), NewLd.getValue(1));
50267       return NewLd;
50268     }
50269   }
50270 
50271   return SDValue();
50272 }
50273 
50274 static SDValue combinePDEP(SDNode *N, SelectionDAG &DAG,
50275                            TargetLowering::DAGCombinerInfo &DCI) {
50276   unsigned NumBits = N->getSimpleValueType(0).getSizeInBits();
50277   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
50278   if (TLI.SimplifyDemandedBits(SDValue(N, 0),
50279                                APInt::getAllOnesValue(NumBits), DCI))
50280     return SDValue(N, 0);
50281 
50282   return SDValue();
50283 }
50284 
50285 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
50286                                              DAGCombinerInfo &DCI) const {
50287   SelectionDAG &DAG = DCI.DAG;
50288   switch (N->getOpcode()) {
50289   default: break;
50290   case ISD::SCALAR_TO_VECTOR:
50291     return combineScalarToVector(N, DAG);
50292   case ISD::EXTRACT_VECTOR_ELT:
50293   case X86ISD::PEXTRW:
50294   case X86ISD::PEXTRB:
50295     return combineExtractVectorElt(N, DAG, DCI, Subtarget);
50296   case ISD::CONCAT_VECTORS:
50297     return combineConcatVectors(N, DAG, DCI, Subtarget);
50298   case ISD::INSERT_SUBVECTOR:
50299     return combineInsertSubvector(N, DAG, DCI, Subtarget);
50300   case ISD::EXTRACT_SUBVECTOR:
50301     return combineExtractSubvector(N, DAG, DCI, Subtarget);
50302   case ISD::VSELECT:
50303   case ISD::SELECT:
50304   case X86ISD::BLENDV:      return combineSelect(N, DAG, DCI, Subtarget);
50305   case ISD::BITCAST:        return combineBitcast(N, DAG, DCI, Subtarget);
50306   case X86ISD::CMOV:        return combineCMov(N, DAG, DCI, Subtarget);
50307   case X86ISD::CMP:         return combineCMP(N, DAG);
50308   case ISD::ADD:            return combineAdd(N, DAG, DCI, Subtarget);
50309   case ISD::SUB:            return combineSub(N, DAG, DCI, Subtarget);
50310   case X86ISD::ADD:
50311   case X86ISD::SUB:         return combineX86AddSub(N, DAG, DCI);
50312   case X86ISD::SBB:         return combineSBB(N, DAG);
50313   case X86ISD::ADC:         return combineADC(N, DAG, DCI);
50314   case ISD::MUL:            return combineMul(N, DAG, DCI, Subtarget);
50315   case ISD::SHL:            return combineShiftLeft(N, DAG);
50316   case ISD::SRA:            return combineShiftRightArithmetic(N, DAG, Subtarget);
50317   case ISD::SRL:            return combineShiftRightLogical(N, DAG, DCI, Subtarget);
50318   case ISD::AND:            return combineAnd(N, DAG, DCI, Subtarget);
50319   case ISD::OR:             return combineOr(N, DAG, DCI, Subtarget);
50320   case ISD::XOR:            return combineXor(N, DAG, DCI, Subtarget);
50321   case X86ISD::BEXTR:
50322   case X86ISD::BEXTRI:      return combineBEXTR(N, DAG, DCI, Subtarget);
50323   case ISD::LOAD:           return combineLoad(N, DAG, DCI, Subtarget);
50324   case ISD::MLOAD:          return combineMaskedLoad(N, DAG, DCI, Subtarget);
50325   case ISD::STORE:          return combineStore(N, DAG, DCI, Subtarget);
50326   case ISD::MSTORE:         return combineMaskedStore(N, DAG, DCI, Subtarget);
50327   case X86ISD::VEXTRACT_STORE:
50328     return combineVEXTRACT_STORE(N, DAG, DCI, Subtarget);
50329   case ISD::SINT_TO_FP:
50330   case ISD::STRICT_SINT_TO_FP:
50331     return combineSIntToFP(N, DAG, DCI, Subtarget);
50332   case ISD::UINT_TO_FP:
50333   case ISD::STRICT_UINT_TO_FP:
50334     return combineUIntToFP(N, DAG, Subtarget);
50335   case ISD::FADD:
50336   case ISD::FSUB:           return combineFaddFsub(N, DAG, Subtarget);
50337   case ISD::FNEG:           return combineFneg(N, DAG, DCI, Subtarget);
50338   case ISD::TRUNCATE:       return combineTruncate(N, DAG, Subtarget);
50339   case X86ISD::VTRUNC:      return combineVTRUNC(N, DAG, DCI);
50340   case X86ISD::ANDNP:       return combineAndnp(N, DAG, DCI, Subtarget);
50341   case X86ISD::FAND:        return combineFAnd(N, DAG, Subtarget);
50342   case X86ISD::FANDN:       return combineFAndn(N, DAG, Subtarget);
50343   case X86ISD::FXOR:
50344   case X86ISD::FOR:         return combineFOr(N, DAG, DCI, Subtarget);
50345   case X86ISD::FMIN:
50346   case X86ISD::FMAX:        return combineFMinFMax(N, DAG);
50347   case ISD::FMINNUM:
50348   case ISD::FMAXNUM:        return combineFMinNumFMaxNum(N, DAG, Subtarget);
50349   case X86ISD::CVTSI2P:
50350   case X86ISD::CVTUI2P:     return combineX86INT_TO_FP(N, DAG, DCI);
50351   case X86ISD::CVTP2SI:
50352   case X86ISD::CVTP2UI:
50353   case X86ISD::STRICT_CVTTP2SI:
50354   case X86ISD::CVTTP2SI:
50355   case X86ISD::STRICT_CVTTP2UI:
50356   case X86ISD::CVTTP2UI:
50357                             return combineCVTP2I_CVTTP2I(N, DAG, DCI);
50358   case X86ISD::STRICT_CVTPH2PS:
50359   case X86ISD::CVTPH2PS:    return combineCVTPH2PS(N, DAG, DCI);
50360   case X86ISD::BT:          return combineBT(N, DAG, DCI);
50361   case ISD::ANY_EXTEND:
50362   case ISD::ZERO_EXTEND:    return combineZext(N, DAG, DCI, Subtarget);
50363   case ISD::SIGN_EXTEND:    return combineSext(N, DAG, DCI, Subtarget);
50364   case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
50365   case ISD::ANY_EXTEND_VECTOR_INREG:
50366   case ISD::SIGN_EXTEND_VECTOR_INREG:
50367   case ISD::ZERO_EXTEND_VECTOR_INREG:
50368     return combineEXTEND_VECTOR_INREG(N, DAG, DCI, Subtarget);
50369   case ISD::SETCC:          return combineSetCC(N, DAG, Subtarget);
50370   case X86ISD::SETCC:       return combineX86SetCC(N, DAG, Subtarget);
50371   case X86ISD::BRCOND:      return combineBrCond(N, DAG, Subtarget);
50372   case X86ISD::PACKSS:
50373   case X86ISD::PACKUS:      return combineVectorPack(N, DAG, DCI, Subtarget);
50374   case X86ISD::HADD:
50375   case X86ISD::HSUB:
50376   case X86ISD::FHADD:
50377   case X86ISD::FHSUB:       return combineVectorHADDSUB(N, DAG, DCI, Subtarget);
50378   case X86ISD::VSHL:
50379   case X86ISD::VSRA:
50380   case X86ISD::VSRL:
50381     return combineVectorShiftVar(N, DAG, DCI, Subtarget);
50382   case X86ISD::VSHLI:
50383   case X86ISD::VSRAI:
50384   case X86ISD::VSRLI:
50385     return combineVectorShiftImm(N, DAG, DCI, Subtarget);
50386   case ISD::INSERT_VECTOR_ELT:
50387   case X86ISD::PINSRB:
50388   case X86ISD::PINSRW:      return combineVectorInsert(N, DAG, DCI, Subtarget);
50389   case X86ISD::SHUFP:       // Handle all target specific shuffles
50390   case X86ISD::INSERTPS:
50391   case X86ISD::EXTRQI:
50392   case X86ISD::INSERTQI:
50393   case X86ISD::VALIGN:
50394   case X86ISD::PALIGNR:
50395   case X86ISD::VSHLDQ:
50396   case X86ISD::VSRLDQ:
50397   case X86ISD::BLENDI:
50398   case X86ISD::UNPCKH:
50399   case X86ISD::UNPCKL:
50400   case X86ISD::MOVHLPS:
50401   case X86ISD::MOVLHPS:
50402   case X86ISD::PSHUFB:
50403   case X86ISD::PSHUFD:
50404   case X86ISD::PSHUFHW:
50405   case X86ISD::PSHUFLW:
50406   case X86ISD::MOVSHDUP:
50407   case X86ISD::MOVSLDUP:
50408   case X86ISD::MOVDDUP:
50409   case X86ISD::MOVSS:
50410   case X86ISD::MOVSD:
50411   case X86ISD::VBROADCAST:
50412   case X86ISD::VPPERM:
50413   case X86ISD::VPERMI:
50414   case X86ISD::VPERMV:
50415   case X86ISD::VPERMV3:
50416   case X86ISD::VPERMIL2:
50417   case X86ISD::VPERMILPI:
50418   case X86ISD::VPERMILPV:
50419   case X86ISD::VPERM2X128:
50420   case X86ISD::SHUF128:
50421   case X86ISD::VZEXT_MOVL:
50422   case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
50423   case X86ISD::FMADD_RND:
50424   case X86ISD::FMSUB:
50425   case X86ISD::STRICT_FMSUB:
50426   case X86ISD::FMSUB_RND:
50427   case X86ISD::FNMADD:
50428   case X86ISD::STRICT_FNMADD:
50429   case X86ISD::FNMADD_RND:
50430   case X86ISD::FNMSUB:
50431   case X86ISD::STRICT_FNMSUB:
50432   case X86ISD::FNMSUB_RND:
50433   case ISD::FMA:
50434   case ISD::STRICT_FMA:     return combineFMA(N, DAG, DCI, Subtarget);
50435   case X86ISD::FMADDSUB_RND:
50436   case X86ISD::FMSUBADD_RND:
50437   case X86ISD::FMADDSUB:
50438   case X86ISD::FMSUBADD:    return combineFMADDSUB(N, DAG, DCI);
50439   case X86ISD::MOVMSK:      return combineMOVMSK(N, DAG, DCI, Subtarget);
50440   case X86ISD::MGATHER:
50441   case X86ISD::MSCATTER:    return combineX86GatherScatter(N, DAG, DCI);
50442   case ISD::MGATHER:
50443   case ISD::MSCATTER:       return combineGatherScatter(N, DAG, DCI);
50444   case X86ISD::PCMPEQ:
50445   case X86ISD::PCMPGT:      return combineVectorCompare(N, DAG, Subtarget);
50446   case X86ISD::PMULDQ:
50447   case X86ISD::PMULUDQ:     return combinePMULDQ(N, DAG, DCI, Subtarget);
50448   case X86ISD::KSHIFTL:
50449   case X86ISD::KSHIFTR:     return combineKSHIFT(N, DAG, DCI);
50450   case ISD::FP16_TO_FP:     return combineFP16_TO_FP(N, DAG, Subtarget);
50451   case ISD::STRICT_FP_EXTEND:
50452   case ISD::FP_EXTEND:      return combineFP_EXTEND(N, DAG, Subtarget);
50453   case ISD::FP_ROUND:       return combineFP_ROUND(N, DAG, Subtarget);
50454   case X86ISD::VBROADCAST_LOAD:
50455   case X86ISD::SUBV_BROADCAST_LOAD: return combineBROADCAST_LOAD(N, DAG, DCI);
50456   case X86ISD::MOVDQ2Q:     return combineMOVDQ2Q(N, DAG);
50457   case X86ISD::PDEP:        return combinePDEP(N, DAG, DCI);
50458   }
50459 
50460   return SDValue();
50461 }
50462 
50463 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
50464   if (!isTypeLegal(VT))
50465     return false;
50466 
50467   // There are no vXi8 shifts.
50468   if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
50469     return false;
50470 
50471   // TODO: Almost no 8-bit ops are desirable because they have no actual
50472   //       size/speed advantages vs. 32-bit ops, but they do have a major
50473   //       potential disadvantage by causing partial register stalls.
50474   //
50475   // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
50476   // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
50477   // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
50478   // check for a constant operand to the multiply.
50479   if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
50480     return false;
50481 
50482   // i16 instruction encodings are longer and some i16 instructions are slow,
50483   // so those are not desirable.
50484   if (VT == MVT::i16) {
50485     switch (Opc) {
50486     default:
50487       break;
50488     case ISD::LOAD:
50489     case ISD::SIGN_EXTEND:
50490     case ISD::ZERO_EXTEND:
50491     case ISD::ANY_EXTEND:
50492     case ISD::SHL:
50493     case ISD::SRA:
50494     case ISD::SRL:
50495     case ISD::SUB:
50496     case ISD::ADD:
50497     case ISD::MUL:
50498     case ISD::AND:
50499     case ISD::OR:
50500     case ISD::XOR:
50501       return false;
50502     }
50503   }
50504 
50505   // Any legal type not explicitly accounted for above here is desirable.
50506   return true;
50507 }
50508 
50509 SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
50510                                                   SDValue Value, SDValue Addr,
50511                                                   SelectionDAG &DAG) const {
50512   const Module *M = DAG.getMachineFunction().getMMI().getModule();
50513   Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
50514   if (IsCFProtectionSupported) {
50515     // In case control-flow branch protection is enabled, we need to add
50516     // notrack prefix to the indirect branch.
50517     // In order to do that we create NT_BRIND SDNode.
50518     // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
50519     return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
50520   }
50521 
50522   return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
50523 }
50524 
50525 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
50526   EVT VT = Op.getValueType();
50527   bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
50528                              isa<ConstantSDNode>(Op.getOperand(1));
50529 
50530   // i16 is legal, but undesirable since i16 instruction encodings are longer
50531   // and some i16 instructions are slow.
50532   // 8-bit multiply-by-constant can usually be expanded to something cheaper
50533   // using LEA and/or other ALU ops.
50534   if (VT != MVT::i16 && !Is8BitMulByConstant)
50535     return false;
50536 
50537   auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
50538     if (!Op.hasOneUse())
50539       return false;
50540     SDNode *User = *Op->use_begin();
50541     if (!ISD::isNormalStore(User))
50542       return false;
50543     auto *Ld = cast<LoadSDNode>(Load);
50544     auto *St = cast<StoreSDNode>(User);
50545     return Ld->getBasePtr() == St->getBasePtr();
50546   };
50547 
50548   auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
50549     if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
50550       return false;
50551     if (!Op.hasOneUse())
50552       return false;
50553     SDNode *User = *Op->use_begin();
50554     if (User->getOpcode() != ISD::ATOMIC_STORE)
50555       return false;
50556     auto *Ld = cast<AtomicSDNode>(Load);
50557     auto *St = cast<AtomicSDNode>(User);
50558     return Ld->getBasePtr() == St->getBasePtr();
50559   };
50560 
50561   bool Commute = false;
50562   switch (Op.getOpcode()) {
50563   default: return false;
50564   case ISD::SIGN_EXTEND:
50565   case ISD::ZERO_EXTEND:
50566   case ISD::ANY_EXTEND:
50567     break;
50568   case ISD::SHL:
50569   case ISD::SRA:
50570   case ISD::SRL: {
50571     SDValue N0 = Op.getOperand(0);
50572     // Look out for (store (shl (load), x)).
50573     if (MayFoldLoad(N0) && IsFoldableRMW(N0, Op))
50574       return false;
50575     break;
50576   }
50577   case ISD::ADD:
50578   case ISD::MUL:
50579   case ISD::AND:
50580   case ISD::OR:
50581   case ISD::XOR:
50582     Commute = true;
50583     LLVM_FALLTHROUGH;
50584   case ISD::SUB: {
50585     SDValue N0 = Op.getOperand(0);
50586     SDValue N1 = Op.getOperand(1);
50587     // Avoid disabling potential load folding opportunities.
50588     if (MayFoldLoad(N1) &&
50589         (!Commute || !isa<ConstantSDNode>(N0) ||
50590          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
50591       return false;
50592     if (MayFoldLoad(N0) &&
50593         ((Commute && !isa<ConstantSDNode>(N1)) ||
50594          (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
50595       return false;
50596     if (IsFoldableAtomicRMW(N0, Op) ||
50597         (Commute && IsFoldableAtomicRMW(N1, Op)))
50598       return false;
50599   }
50600   }
50601 
50602   PVT = MVT::i32;
50603   return true;
50604 }
50605 
50606 //===----------------------------------------------------------------------===//
50607 //                           X86 Inline Assembly Support
50608 //===----------------------------------------------------------------------===//
50609 
50610 // Helper to match a string separated by whitespace.
50611 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
50612   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
50613 
50614   for (StringRef Piece : Pieces) {
50615     if (!S.startswith(Piece)) // Check if the piece matches.
50616       return false;
50617 
50618     S = S.substr(Piece.size());
50619     StringRef::size_type Pos = S.find_first_not_of(" \t");
50620     if (Pos == 0) // We matched a prefix.
50621       return false;
50622 
50623     S = S.substr(Pos);
50624   }
50625 
50626   return S.empty();
50627 }
50628 
50629 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
50630 
50631   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
50632     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
50633         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
50634         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
50635 
50636       if (AsmPieces.size() == 3)
50637         return true;
50638       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
50639         return true;
50640     }
50641   }
50642   return false;
50643 }
50644 
50645 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
50646   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
50647 
50648   const std::string &AsmStr = IA->getAsmString();
50649 
50650   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
50651   if (!Ty || Ty->getBitWidth() % 16 != 0)
50652     return false;
50653 
50654   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
50655   SmallVector<StringRef, 4> AsmPieces;
50656   SplitString(AsmStr, AsmPieces, ";\n");
50657 
50658   switch (AsmPieces.size()) {
50659   default: return false;
50660   case 1:
50661     // FIXME: this should verify that we are targeting a 486 or better.  If not,
50662     // we will turn this bswap into something that will be lowered to logical
50663     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
50664     // lower so don't worry about this.
50665     // bswap $0
50666     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
50667         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
50668         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
50669         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
50670         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
50671         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
50672       // No need to check constraints, nothing other than the equivalent of
50673       // "=r,0" would be valid here.
50674       return IntrinsicLowering::LowerToByteSwap(CI);
50675     }
50676 
50677     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
50678     if (CI->getType()->isIntegerTy(16) &&
50679         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
50680         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
50681          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
50682       AsmPieces.clear();
50683       StringRef ConstraintsStr = IA->getConstraintString();
50684       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
50685       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
50686       if (clobbersFlagRegisters(AsmPieces))
50687         return IntrinsicLowering::LowerToByteSwap(CI);
50688     }
50689     break;
50690   case 3:
50691     if (CI->getType()->isIntegerTy(32) &&
50692         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
50693         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
50694         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
50695         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
50696       AsmPieces.clear();
50697       StringRef ConstraintsStr = IA->getConstraintString();
50698       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
50699       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
50700       if (clobbersFlagRegisters(AsmPieces))
50701         return IntrinsicLowering::LowerToByteSwap(CI);
50702     }
50703 
50704     if (CI->getType()->isIntegerTy(64)) {
50705       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
50706       if (Constraints.size() >= 2 &&
50707           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
50708           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
50709         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
50710         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
50711             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
50712             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
50713           return IntrinsicLowering::LowerToByteSwap(CI);
50714       }
50715     }
50716     break;
50717   }
50718   return false;
50719 }
50720 
50721 static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
50722   X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
50723                            .Case("{@cca}", X86::COND_A)
50724                            .Case("{@ccae}", X86::COND_AE)
50725                            .Case("{@ccb}", X86::COND_B)
50726                            .Case("{@ccbe}", X86::COND_BE)
50727                            .Case("{@ccc}", X86::COND_B)
50728                            .Case("{@cce}", X86::COND_E)
50729                            .Case("{@ccz}", X86::COND_E)
50730                            .Case("{@ccg}", X86::COND_G)
50731                            .Case("{@ccge}", X86::COND_GE)
50732                            .Case("{@ccl}", X86::COND_L)
50733                            .Case("{@ccle}", X86::COND_LE)
50734                            .Case("{@ccna}", X86::COND_BE)
50735                            .Case("{@ccnae}", X86::COND_B)
50736                            .Case("{@ccnb}", X86::COND_AE)
50737                            .Case("{@ccnbe}", X86::COND_A)
50738                            .Case("{@ccnc}", X86::COND_AE)
50739                            .Case("{@ccne}", X86::COND_NE)
50740                            .Case("{@ccnz}", X86::COND_NE)
50741                            .Case("{@ccng}", X86::COND_LE)
50742                            .Case("{@ccnge}", X86::COND_L)
50743                            .Case("{@ccnl}", X86::COND_GE)
50744                            .Case("{@ccnle}", X86::COND_G)
50745                            .Case("{@ccno}", X86::COND_NO)
50746                            .Case("{@ccnp}", X86::COND_NP)
50747                            .Case("{@ccns}", X86::COND_NS)
50748                            .Case("{@cco}", X86::COND_O)
50749                            .Case("{@ccp}", X86::COND_P)
50750                            .Case("{@ccs}", X86::COND_S)
50751                            .Default(X86::COND_INVALID);
50752   return Cond;
50753 }
50754 
50755 /// Given a constraint letter, return the type of constraint for this target.
50756 X86TargetLowering::ConstraintType
50757 X86TargetLowering::getConstraintType(StringRef Constraint) const {
50758   if (Constraint.size() == 1) {
50759     switch (Constraint[0]) {
50760     case 'R':
50761     case 'q':
50762     case 'Q':
50763     case 'f':
50764     case 't':
50765     case 'u':
50766     case 'y':
50767     case 'x':
50768     case 'v':
50769     case 'l':
50770     case 'k': // AVX512 masking registers.
50771       return C_RegisterClass;
50772     case 'a':
50773     case 'b':
50774     case 'c':
50775     case 'd':
50776     case 'S':
50777     case 'D':
50778     case 'A':
50779       return C_Register;
50780     case 'I':
50781     case 'J':
50782     case 'K':
50783     case 'N':
50784     case 'G':
50785     case 'L':
50786     case 'M':
50787       return C_Immediate;
50788     case 'C':
50789     case 'e':
50790     case 'Z':
50791       return C_Other;
50792     default:
50793       break;
50794     }
50795   }
50796   else if (Constraint.size() == 2) {
50797     switch (Constraint[0]) {
50798     default:
50799       break;
50800     case 'Y':
50801       switch (Constraint[1]) {
50802       default:
50803         break;
50804       case 'z':
50805         return C_Register;
50806       case 'i':
50807       case 'm':
50808       case 'k':
50809       case 't':
50810       case '2':
50811         return C_RegisterClass;
50812       }
50813     }
50814   } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
50815     return C_Other;
50816   return TargetLowering::getConstraintType(Constraint);
50817 }
50818 
50819 /// Examine constraint type and operand type and determine a weight value.
50820 /// This object must already have been set up with the operand type
50821 /// and the current alternative constraint selected.
50822 TargetLowering::ConstraintWeight
50823   X86TargetLowering::getSingleConstraintMatchWeight(
50824     AsmOperandInfo &info, const char *constraint) const {
50825   ConstraintWeight weight = CW_Invalid;
50826   Value *CallOperandVal = info.CallOperandVal;
50827     // If we don't have a value, we can't do a match,
50828     // but allow it at the lowest weight.
50829   if (!CallOperandVal)
50830     return CW_Default;
50831   Type *type = CallOperandVal->getType();
50832   // Look at the constraint type.
50833   switch (*constraint) {
50834   default:
50835     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
50836     LLVM_FALLTHROUGH;
50837   case 'R':
50838   case 'q':
50839   case 'Q':
50840   case 'a':
50841   case 'b':
50842   case 'c':
50843   case 'd':
50844   case 'S':
50845   case 'D':
50846   case 'A':
50847     if (CallOperandVal->getType()->isIntegerTy())
50848       weight = CW_SpecificReg;
50849     break;
50850   case 'f':
50851   case 't':
50852   case 'u':
50853     if (type->isFloatingPointTy())
50854       weight = CW_SpecificReg;
50855     break;
50856   case 'y':
50857     if (type->isX86_MMXTy() && Subtarget.hasMMX())
50858       weight = CW_SpecificReg;
50859     break;
50860   case 'Y':
50861     if (StringRef(constraint).size() != 2)
50862       break;
50863     switch (constraint[1]) {
50864       default:
50865         return CW_Invalid;
50866       // XMM0
50867       case 'z':
50868         if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
50869             ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()) ||
50870             ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512()))
50871           return CW_SpecificReg;
50872         return CW_Invalid;
50873       // Conditional OpMask regs (AVX512)
50874       case 'k':
50875         if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
50876           return CW_Register;
50877         return CW_Invalid;
50878       // Any MMX reg
50879       case 'm':
50880         if (type->isX86_MMXTy() && Subtarget.hasMMX())
50881           return weight;
50882         return CW_Invalid;
50883       // Any SSE reg when ISA >= SSE2, same as 'x'
50884       case 'i':
50885       case 't':
50886       case '2':
50887         if (!Subtarget.hasSSE2())
50888           return CW_Invalid;
50889         break;
50890     }
50891     break;
50892   case 'v':
50893     if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
50894       weight = CW_Register;
50895     LLVM_FALLTHROUGH;
50896   case 'x':
50897     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
50898         ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
50899       weight = CW_Register;
50900     break;
50901   case 'k':
50902     // Enable conditional vector operations using %k<#> registers.
50903     if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
50904       weight = CW_Register;
50905     break;
50906   case 'I':
50907     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
50908       if (C->getZExtValue() <= 31)
50909         weight = CW_Constant;
50910     }
50911     break;
50912   case 'J':
50913     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50914       if (C->getZExtValue() <= 63)
50915         weight = CW_Constant;
50916     }
50917     break;
50918   case 'K':
50919     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50920       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
50921         weight = CW_Constant;
50922     }
50923     break;
50924   case 'L':
50925     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50926       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
50927         weight = CW_Constant;
50928     }
50929     break;
50930   case 'M':
50931     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50932       if (C->getZExtValue() <= 3)
50933         weight = CW_Constant;
50934     }
50935     break;
50936   case 'N':
50937     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50938       if (C->getZExtValue() <= 0xff)
50939         weight = CW_Constant;
50940     }
50941     break;
50942   case 'G':
50943   case 'C':
50944     if (isa<ConstantFP>(CallOperandVal)) {
50945       weight = CW_Constant;
50946     }
50947     break;
50948   case 'e':
50949     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50950       if ((C->getSExtValue() >= -0x80000000LL) &&
50951           (C->getSExtValue() <= 0x7fffffffLL))
50952         weight = CW_Constant;
50953     }
50954     break;
50955   case 'Z':
50956     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
50957       if (C->getZExtValue() <= 0xffffffff)
50958         weight = CW_Constant;
50959     }
50960     break;
50961   }
50962   return weight;
50963 }
50964 
50965 /// Try to replace an X constraint, which matches anything, with another that
50966 /// has more specific requirements based on the type of the corresponding
50967 /// operand.
50968 const char *X86TargetLowering::
50969 LowerXConstraint(EVT ConstraintVT) const {
50970   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
50971   // 'f' like normal targets.
50972   if (ConstraintVT.isFloatingPoint()) {
50973     if (Subtarget.hasSSE1())
50974       return "x";
50975   }
50976 
50977   return TargetLowering::LowerXConstraint(ConstraintVT);
50978 }
50979 
50980 // Lower @cc targets via setcc.
50981 SDValue X86TargetLowering::LowerAsmOutputForConstraint(
50982     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
50983     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
50984   X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
50985   if (Cond == X86::COND_INVALID)
50986     return SDValue();
50987   // Check that return type is valid.
50988   if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
50989       OpInfo.ConstraintVT.getSizeInBits() < 8)
50990     report_fatal_error("Flag output operand is of invalid type");
50991 
50992   // Get EFLAGS register. Only update chain when copyfrom is glued.
50993   if (Flag.getNode()) {
50994     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
50995     Chain = Flag.getValue(1);
50996   } else
50997     Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
50998   // Extract CC code.
50999   SDValue CC = getSETCC(Cond, Flag, DL, DAG);
51000   // Extend to 32-bits
51001   SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
51002 
51003   return Result;
51004 }
51005 
51006 /// Lower the specified operand into the Ops vector.
51007 /// If it is invalid, don't add anything to Ops.
51008 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
51009                                                      std::string &Constraint,
51010                                                      std::vector<SDValue>&Ops,
51011                                                      SelectionDAG &DAG) const {
51012   SDValue Result;
51013 
51014   // Only support length 1 constraints for now.
51015   if (Constraint.length() > 1) return;
51016 
51017   char ConstraintLetter = Constraint[0];
51018   switch (ConstraintLetter) {
51019   default: break;
51020   case 'I':
51021     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51022       if (C->getZExtValue() <= 31) {
51023         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51024                                        Op.getValueType());
51025         break;
51026       }
51027     }
51028     return;
51029   case 'J':
51030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51031       if (C->getZExtValue() <= 63) {
51032         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51033                                        Op.getValueType());
51034         break;
51035       }
51036     }
51037     return;
51038   case 'K':
51039     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51040       if (isInt<8>(C->getSExtValue())) {
51041         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51042                                        Op.getValueType());
51043         break;
51044       }
51045     }
51046     return;
51047   case 'L':
51048     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51049       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
51050           (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
51051         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
51052                                        Op.getValueType());
51053         break;
51054       }
51055     }
51056     return;
51057   case 'M':
51058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51059       if (C->getZExtValue() <= 3) {
51060         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51061                                        Op.getValueType());
51062         break;
51063       }
51064     }
51065     return;
51066   case 'N':
51067     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51068       if (C->getZExtValue() <= 255) {
51069         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51070                                        Op.getValueType());
51071         break;
51072       }
51073     }
51074     return;
51075   case 'O':
51076     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51077       if (C->getZExtValue() <= 127) {
51078         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51079                                        Op.getValueType());
51080         break;
51081       }
51082     }
51083     return;
51084   case 'e': {
51085     // 32-bit signed value
51086     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51087       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
51088                                            C->getSExtValue())) {
51089         // Widen to 64 bits here to get it sign extended.
51090         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
51091         break;
51092       }
51093     // FIXME gcc accepts some relocatable values here too, but only in certain
51094     // memory models; it's complicated.
51095     }
51096     return;
51097   }
51098   case 'Z': {
51099     // 32-bit unsigned value
51100     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
51101       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
51102                                            C->getZExtValue())) {
51103         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
51104                                        Op.getValueType());
51105         break;
51106       }
51107     }
51108     // FIXME gcc accepts some relocatable values here too, but only in certain
51109     // memory models; it's complicated.
51110     return;
51111   }
51112   case 'i': {
51113     // Literal immediates are always ok.
51114     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
51115       bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
51116       BooleanContent BCont = getBooleanContents(MVT::i64);
51117       ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
51118                                     : ISD::SIGN_EXTEND;
51119       int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
51120                                                   : CST->getSExtValue();
51121       Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
51122       break;
51123     }
51124 
51125     // In any sort of PIC mode addresses need to be computed at runtime by
51126     // adding in a register or some sort of table lookup.  These can't
51127     // be used as immediates.
51128     if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
51129       return;
51130 
51131     // If we are in non-pic codegen mode, we allow the address of a global (with
51132     // an optional displacement) to be used with 'i'.
51133     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
51134       // If we require an extra load to get this address, as in PIC mode, we
51135       // can't accept it.
51136       if (isGlobalStubReference(
51137               Subtarget.classifyGlobalReference(GA->getGlobal())))
51138         return;
51139     break;
51140   }
51141   }
51142 
51143   if (Result.getNode()) {
51144     Ops.push_back(Result);
51145     return;
51146   }
51147   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
51148 }
51149 
51150 /// Check if \p RC is a general purpose register class.
51151 /// I.e., GR* or one of their variant.
51152 static bool isGRClass(const TargetRegisterClass &RC) {
51153   return RC.hasSuperClassEq(&X86::GR8RegClass) ||
51154          RC.hasSuperClassEq(&X86::GR16RegClass) ||
51155          RC.hasSuperClassEq(&X86::GR32RegClass) ||
51156          RC.hasSuperClassEq(&X86::GR64RegClass) ||
51157          RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
51158 }
51159 
51160 /// Check if \p RC is a vector register class.
51161 /// I.e., FR* / VR* or one of their variant.
51162 static bool isFRClass(const TargetRegisterClass &RC) {
51163   return RC.hasSuperClassEq(&X86::FR32XRegClass) ||
51164          RC.hasSuperClassEq(&X86::FR64XRegClass) ||
51165          RC.hasSuperClassEq(&X86::VR128XRegClass) ||
51166          RC.hasSuperClassEq(&X86::VR256XRegClass) ||
51167          RC.hasSuperClassEq(&X86::VR512RegClass);
51168 }
51169 
51170 /// Check if \p RC is a mask register class.
51171 /// I.e., VK* or one of their variant.
51172 static bool isVKClass(const TargetRegisterClass &RC) {
51173   return RC.hasSuperClassEq(&X86::VK1RegClass) ||
51174          RC.hasSuperClassEq(&X86::VK2RegClass) ||
51175          RC.hasSuperClassEq(&X86::VK4RegClass) ||
51176          RC.hasSuperClassEq(&X86::VK8RegClass) ||
51177          RC.hasSuperClassEq(&X86::VK16RegClass) ||
51178          RC.hasSuperClassEq(&X86::VK32RegClass) ||
51179          RC.hasSuperClassEq(&X86::VK64RegClass);
51180 }
51181 
51182 std::pair<unsigned, const TargetRegisterClass *>
51183 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
51184                                                 StringRef Constraint,
51185                                                 MVT VT) const {
51186   // First, see if this is a constraint that directly corresponds to an LLVM
51187   // register class.
51188   if (Constraint.size() == 1) {
51189     // GCC Constraint Letters
51190     switch (Constraint[0]) {
51191     default: break;
51192     // 'A' means [ER]AX + [ER]DX.
51193     case 'A':
51194       if (Subtarget.is64Bit())
51195         return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
51196       assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&
51197              "Expecting 64, 32 or 16 bit subtarget");
51198       return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
51199 
51200       // TODO: Slight differences here in allocation order and leaving
51201       // RIP in the class. Do they matter any more here than they do
51202       // in the normal allocation?
51203     case 'k':
51204       if (Subtarget.hasAVX512()) {
51205         if (VT == MVT::i1)
51206           return std::make_pair(0U, &X86::VK1RegClass);
51207         if (VT == MVT::i8)
51208           return std::make_pair(0U, &X86::VK8RegClass);
51209         if (VT == MVT::i16)
51210           return std::make_pair(0U, &X86::VK16RegClass);
51211       }
51212       if (Subtarget.hasBWI()) {
51213         if (VT == MVT::i32)
51214           return std::make_pair(0U, &X86::VK32RegClass);
51215         if (VT == MVT::i64)
51216           return std::make_pair(0U, &X86::VK64RegClass);
51217       }
51218       break;
51219     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
51220       if (Subtarget.is64Bit()) {
51221         if (VT == MVT::i8 || VT == MVT::i1)
51222           return std::make_pair(0U, &X86::GR8RegClass);
51223         if (VT == MVT::i16)
51224           return std::make_pair(0U, &X86::GR16RegClass);
51225         if (VT == MVT::i32 || VT == MVT::f32)
51226           return std::make_pair(0U, &X86::GR32RegClass);
51227         if (VT != MVT::f80)
51228           return std::make_pair(0U, &X86::GR64RegClass);
51229         break;
51230       }
51231       LLVM_FALLTHROUGH;
51232       // 32-bit fallthrough
51233     case 'Q':   // Q_REGS
51234       if (VT == MVT::i8 || VT == MVT::i1)
51235         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
51236       if (VT == MVT::i16)
51237         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
51238       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
51239         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
51240       if (VT != MVT::f80)
51241         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
51242       break;
51243     case 'r':   // GENERAL_REGS
51244     case 'l':   // INDEX_REGS
51245       if (VT == MVT::i8 || VT == MVT::i1)
51246         return std::make_pair(0U, &X86::GR8RegClass);
51247       if (VT == MVT::i16)
51248         return std::make_pair(0U, &X86::GR16RegClass);
51249       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
51250         return std::make_pair(0U, &X86::GR32RegClass);
51251       if (VT != MVT::f80)
51252         return std::make_pair(0U, &X86::GR64RegClass);
51253       break;
51254     case 'R':   // LEGACY_REGS
51255       if (VT == MVT::i8 || VT == MVT::i1)
51256         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
51257       if (VT == MVT::i16)
51258         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
51259       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
51260         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
51261       if (VT != MVT::f80)
51262         return std::make_pair(0U, &X86::GR64_NOREXRegClass);
51263       break;
51264     case 'f':  // FP Stack registers.
51265       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
51266       // value to the correct fpstack register class.
51267       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
51268         return std::make_pair(0U, &X86::RFP32RegClass);
51269       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
51270         return std::make_pair(0U, &X86::RFP64RegClass);
51271       if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80)
51272         return std::make_pair(0U, &X86::RFP80RegClass);
51273       break;
51274     case 'y':   // MMX_REGS if MMX allowed.
51275       if (!Subtarget.hasMMX()) break;
51276       return std::make_pair(0U, &X86::VR64RegClass);
51277     case 'v':
51278     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
51279       if (!Subtarget.hasSSE1()) break;
51280       bool VConstraint = (Constraint[0] == 'v');
51281 
51282       switch (VT.SimpleTy) {
51283       default: break;
51284       // Scalar SSE types.
51285       case MVT::f32:
51286       case MVT::i32:
51287         if (VConstraint && Subtarget.hasVLX())
51288           return std::make_pair(0U, &X86::FR32XRegClass);
51289         return std::make_pair(0U, &X86::FR32RegClass);
51290       case MVT::f64:
51291       case MVT::i64:
51292         if (VConstraint && Subtarget.hasVLX())
51293           return std::make_pair(0U, &X86::FR64XRegClass);
51294         return std::make_pair(0U, &X86::FR64RegClass);
51295       case MVT::i128:
51296         if (Subtarget.is64Bit()) {
51297           if (VConstraint && Subtarget.hasVLX())
51298             return std::make_pair(0U, &X86::VR128XRegClass);
51299           return std::make_pair(0U, &X86::VR128RegClass);
51300         }
51301         break;
51302       // Vector types and fp128.
51303       case MVT::f128:
51304       case MVT::v16i8:
51305       case MVT::v8i16:
51306       case MVT::v4i32:
51307       case MVT::v2i64:
51308       case MVT::v4f32:
51309       case MVT::v2f64:
51310         if (VConstraint && Subtarget.hasVLX())
51311           return std::make_pair(0U, &X86::VR128XRegClass);
51312         return std::make_pair(0U, &X86::VR128RegClass);
51313       // AVX types.
51314       case MVT::v32i8:
51315       case MVT::v16i16:
51316       case MVT::v8i32:
51317       case MVT::v4i64:
51318       case MVT::v8f32:
51319       case MVT::v4f64:
51320         if (VConstraint && Subtarget.hasVLX())
51321           return std::make_pair(0U, &X86::VR256XRegClass);
51322         if (Subtarget.hasAVX())
51323           return std::make_pair(0U, &X86::VR256RegClass);
51324         break;
51325       case MVT::v64i8:
51326       case MVT::v32i16:
51327       case MVT::v8f64:
51328       case MVT::v16f32:
51329       case MVT::v16i32:
51330       case MVT::v8i64:
51331         if (!Subtarget.hasAVX512()) break;
51332         if (VConstraint)
51333           return std::make_pair(0U, &X86::VR512RegClass);
51334         return std::make_pair(0U, &X86::VR512_0_15RegClass);
51335       }
51336       break;
51337     }
51338   } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
51339     switch (Constraint[1]) {
51340     default:
51341       break;
51342     case 'i':
51343     case 't':
51344     case '2':
51345       return getRegForInlineAsmConstraint(TRI, "x", VT);
51346     case 'm':
51347       if (!Subtarget.hasMMX()) break;
51348       return std::make_pair(0U, &X86::VR64RegClass);
51349     case 'z':
51350       if (!Subtarget.hasSSE1()) break;
51351       switch (VT.SimpleTy) {
51352       default: break;
51353       // Scalar SSE types.
51354       case MVT::f32:
51355       case MVT::i32:
51356         return std::make_pair(X86::XMM0, &X86::FR32RegClass);
51357       case MVT::f64:
51358       case MVT::i64:
51359         return std::make_pair(X86::XMM0, &X86::FR64RegClass);
51360       case MVT::f128:
51361       case MVT::v16i8:
51362       case MVT::v8i16:
51363       case MVT::v4i32:
51364       case MVT::v2i64:
51365       case MVT::v4f32:
51366       case MVT::v2f64:
51367         return std::make_pair(X86::XMM0, &X86::VR128RegClass);
51368       // AVX types.
51369       case MVT::v32i8:
51370       case MVT::v16i16:
51371       case MVT::v8i32:
51372       case MVT::v4i64:
51373       case MVT::v8f32:
51374       case MVT::v4f64:
51375         if (Subtarget.hasAVX())
51376           return std::make_pair(X86::YMM0, &X86::VR256RegClass);
51377         break;
51378       case MVT::v64i8:
51379       case MVT::v32i16:
51380       case MVT::v8f64:
51381       case MVT::v16f32:
51382       case MVT::v16i32:
51383       case MVT::v8i64:
51384         if (Subtarget.hasAVX512())
51385           return std::make_pair(X86::ZMM0, &X86::VR512_0_15RegClass);
51386         break;
51387       }
51388       break;
51389     case 'k':
51390       // This register class doesn't allocate k0 for masked vector operation.
51391       if (Subtarget.hasAVX512()) {
51392         if (VT == MVT::i1)
51393           return std::make_pair(0U, &X86::VK1WMRegClass);
51394         if (VT == MVT::i8)
51395           return std::make_pair(0U, &X86::VK8WMRegClass);
51396         if (VT == MVT::i16)
51397           return std::make_pair(0U, &X86::VK16WMRegClass);
51398       }
51399       if (Subtarget.hasBWI()) {
51400         if (VT == MVT::i32)
51401           return std::make_pair(0U, &X86::VK32WMRegClass);
51402         if (VT == MVT::i64)
51403           return std::make_pair(0U, &X86::VK64WMRegClass);
51404       }
51405       break;
51406     }
51407   }
51408 
51409   if (parseConstraintCode(Constraint) != X86::COND_INVALID)
51410     return std::make_pair(0U, &X86::GR32RegClass);
51411 
51412   // Use the default implementation in TargetLowering to convert the register
51413   // constraint into a member of a register class.
51414   std::pair<Register, const TargetRegisterClass*> Res;
51415   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
51416 
51417   // Not found as a standard register?
51418   if (!Res.second) {
51419     // Only match x87 registers if the VT is one SelectionDAGBuilder can convert
51420     // to/from f80.
51421     if (VT == MVT::Other || VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f80) {
51422       // Map st(0) -> st(7) -> ST0
51423       if (Constraint.size() == 7 && Constraint[0] == '{' &&
51424           tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
51425           Constraint[3] == '(' &&
51426           (Constraint[4] >= '0' && Constraint[4] <= '7') &&
51427           Constraint[5] == ')' && Constraint[6] == '}') {
51428         // st(7) is not allocatable and thus not a member of RFP80. Return
51429         // singleton class in cases where we have a reference to it.
51430         if (Constraint[4] == '7')
51431           return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
51432         return std::make_pair(X86::FP0 + Constraint[4] - '0',
51433                               &X86::RFP80RegClass);
51434       }
51435 
51436       // GCC allows "st(0)" to be called just plain "st".
51437       if (StringRef("{st}").equals_lower(Constraint))
51438         return std::make_pair(X86::FP0, &X86::RFP80RegClass);
51439     }
51440 
51441     // flags -> EFLAGS
51442     if (StringRef("{flags}").equals_lower(Constraint))
51443       return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
51444 
51445     // dirflag -> DF
51446     // Only allow for clobber.
51447     if (StringRef("{dirflag}").equals_lower(Constraint) && VT == MVT::Other)
51448       return std::make_pair(X86::DF, &X86::DFCCRRegClass);
51449 
51450     // fpsr -> FPSW
51451     if (StringRef("{fpsr}").equals_lower(Constraint))
51452       return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
51453 
51454     return Res;
51455   }
51456 
51457   // Make sure it isn't a register that requires 64-bit mode.
51458   if (!Subtarget.is64Bit() &&
51459       (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
51460       TRI->getEncodingValue(Res.first) >= 8) {
51461     // Register requires REX prefix, but we're in 32-bit mode.
51462     return std::make_pair(0, nullptr);
51463   }
51464 
51465   // Make sure it isn't a register that requires AVX512.
51466   if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
51467       TRI->getEncodingValue(Res.first) & 0x10) {
51468     // Register requires EVEX prefix.
51469     return std::make_pair(0, nullptr);
51470   }
51471 
51472   // Otherwise, check to see if this is a register class of the wrong value
51473   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
51474   // turn into {ax},{dx}.
51475   // MVT::Other is used to specify clobber names.
51476   if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
51477     return Res;   // Correct type already, nothing to do.
51478 
51479   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
51480   // return "eax". This should even work for things like getting 64bit integer
51481   // registers when given an f64 type.
51482   const TargetRegisterClass *Class = Res.second;
51483   // The generic code will match the first register class that contains the
51484   // given register. Thus, based on the ordering of the tablegened file,
51485   // the "plain" GR classes might not come first.
51486   // Therefore, use a helper method.
51487   if (isGRClass(*Class)) {
51488     unsigned Size = VT.getSizeInBits();
51489     if (Size == 1) Size = 8;
51490     Register DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
51491     if (DestReg > 0) {
51492       bool is64Bit = Subtarget.is64Bit();
51493       const TargetRegisterClass *RC =
51494           Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
51495         : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
51496         : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
51497         : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
51498         : nullptr;
51499       if (Size == 64 && !is64Bit) {
51500         // Model GCC's behavior here and select a fixed pair of 32-bit
51501         // registers.
51502         switch (DestReg) {
51503         case X86::RAX:
51504           return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
51505         case X86::RDX:
51506           return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
51507         case X86::RCX:
51508           return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
51509         case X86::RBX:
51510           return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
51511         case X86::RSI:
51512           return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
51513         case X86::RDI:
51514           return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
51515         case X86::RBP:
51516           return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
51517         default:
51518           return std::make_pair(0, nullptr);
51519         }
51520       }
51521       if (RC && RC->contains(DestReg))
51522         return std::make_pair(DestReg, RC);
51523       return Res;
51524     }
51525     // No register found/type mismatch.
51526     return std::make_pair(0, nullptr);
51527   } else if (isFRClass(*Class)) {
51528     // Handle references to XMM physical registers that got mapped into the
51529     // wrong class.  This can happen with constraints like {xmm0} where the
51530     // target independent register mapper will just pick the first match it can
51531     // find, ignoring the required type.
51532 
51533     // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
51534     if (VT == MVT::f32 || VT == MVT::i32)
51535       Res.second = &X86::FR32XRegClass;
51536     else if (VT == MVT::f64 || VT == MVT::i64)
51537       Res.second = &X86::FR64XRegClass;
51538     else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
51539       Res.second = &X86::VR128XRegClass;
51540     else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
51541       Res.second = &X86::VR256XRegClass;
51542     else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
51543       Res.second = &X86::VR512RegClass;
51544     else {
51545       // Type mismatch and not a clobber: Return an error;
51546       Res.first = 0;
51547       Res.second = nullptr;
51548     }
51549   } else if (isVKClass(*Class)) {
51550     if (VT == MVT::i1)
51551       Res.second = &X86::VK1RegClass;
51552     else if (VT == MVT::i8)
51553       Res.second = &X86::VK8RegClass;
51554     else if (VT == MVT::i16)
51555       Res.second = &X86::VK16RegClass;
51556     else if (VT == MVT::i32)
51557       Res.second = &X86::VK32RegClass;
51558     else if (VT == MVT::i64)
51559       Res.second = &X86::VK64RegClass;
51560     else {
51561       // Type mismatch and not a clobber: Return an error;
51562       Res.first = 0;
51563       Res.second = nullptr;
51564     }
51565   }
51566 
51567   return Res;
51568 }
51569 
51570 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
51571                                             const AddrMode &AM, Type *Ty,
51572                                             unsigned AS) const {
51573   // Scaling factors are not free at all.
51574   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
51575   // will take 2 allocations in the out of order engine instead of 1
51576   // for plain addressing mode, i.e. inst (reg1).
51577   // E.g.,
51578   // vaddps (%rsi,%rdx), %ymm0, %ymm1
51579   // Requires two allocations (one for the load, one for the computation)
51580   // whereas:
51581   // vaddps (%rsi), %ymm0, %ymm1
51582   // Requires just 1 allocation, i.e., freeing allocations for other operations
51583   // and having less micro operations to execute.
51584   //
51585   // For some X86 architectures, this is even worse because for instance for
51586   // stores, the complex addressing mode forces the instruction to use the
51587   // "load" ports instead of the dedicated "store" port.
51588   // E.g., on Haswell:
51589   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
51590   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
51591   if (isLegalAddressingMode(DL, AM, Ty, AS))
51592     // Scale represents reg2 * scale, thus account for 1
51593     // as soon as we use a second register.
51594     return AM.Scale != 0;
51595   return -1;
51596 }
51597 
51598 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
51599   // Integer division on x86 is expensive. However, when aggressively optimizing
51600   // for code size, we prefer to use a div instruction, as it is usually smaller
51601   // than the alternative sequence.
51602   // The exception to this is vector division. Since x86 doesn't have vector
51603   // integer division, leaving the division as-is is a loss even in terms of
51604   // size, because it will have to be scalarized, while the alternative code
51605   // sequence can be performed in vector form.
51606   bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
51607   return OptSize && !VT.isVector();
51608 }
51609 
51610 void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
51611   if (!Subtarget.is64Bit())
51612     return;
51613 
51614   // Update IsSplitCSR in X86MachineFunctionInfo.
51615   X86MachineFunctionInfo *AFI =
51616       Entry->getParent()->getInfo<X86MachineFunctionInfo>();
51617   AFI->setIsSplitCSR(true);
51618 }
51619 
51620 void X86TargetLowering::insertCopiesSplitCSR(
51621     MachineBasicBlock *Entry,
51622     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
51623   const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
51624   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
51625   if (!IStart)
51626     return;
51627 
51628   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
51629   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
51630   MachineBasicBlock::iterator MBBI = Entry->begin();
51631   for (const MCPhysReg *I = IStart; *I; ++I) {
51632     const TargetRegisterClass *RC = nullptr;
51633     if (X86::GR64RegClass.contains(*I))
51634       RC = &X86::GR64RegClass;
51635     else
51636       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
51637 
51638     Register NewVR = MRI->createVirtualRegister(RC);
51639     // Create copy from CSR to a virtual register.
51640     // FIXME: this currently does not emit CFI pseudo-instructions, it works
51641     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
51642     // nounwind. If we want to generalize this later, we may need to emit
51643     // CFI pseudo-instructions.
51644     assert(
51645         Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&
51646         "Function should be nounwind in insertCopiesSplitCSR!");
51647     Entry->addLiveIn(*I);
51648     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
51649         .addReg(*I);
51650 
51651     // Insert the copy-back instructions right before the terminator.
51652     for (auto *Exit : Exits)
51653       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
51654               TII->get(TargetOpcode::COPY), *I)
51655           .addReg(NewVR);
51656   }
51657 }
51658 
51659 bool X86TargetLowering::supportSwiftError() const {
51660   return Subtarget.is64Bit();
51661 }
51662 
51663 /// Returns true if stack probing through a function call is requested.
51664 bool X86TargetLowering::hasStackProbeSymbol(MachineFunction &MF) const {
51665   return !getStackProbeSymbolName(MF).empty();
51666 }
51667 
51668 /// Returns true if stack probing through inline assembly is requested.
51669 bool X86TargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
51670 
51671   // No inline stack probe for Windows, they have their own mechanism.
51672   if (Subtarget.isOSWindows() ||
51673       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
51674     return false;
51675 
51676   // If the function specifically requests inline stack probes, emit them.
51677   if (MF.getFunction().hasFnAttribute("probe-stack"))
51678     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
51679            "inline-asm";
51680 
51681   return false;
51682 }
51683 
51684 /// Returns the name of the symbol used to emit stack probes or the empty
51685 /// string if not applicable.
51686 StringRef
51687 X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
51688   // Inline Stack probes disable stack probe call
51689   if (hasInlineStackProbe(MF))
51690     return "";
51691 
51692   // If the function specifically requests stack probes, emit them.
51693   if (MF.getFunction().hasFnAttribute("probe-stack"))
51694     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
51695 
51696   // Generally, if we aren't on Windows, the platform ABI does not include
51697   // support for stack probes, so don't emit them.
51698   if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
51699       MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
51700     return "";
51701 
51702   // We need a stack probe to conform to the Windows ABI. Choose the right
51703   // symbol.
51704   if (Subtarget.is64Bit())
51705     return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
51706   return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
51707 }
51708 
51709 unsigned
51710 X86TargetLowering::getStackProbeSize(MachineFunction &MF) const {
51711   // The default stack probe size is 4096 if the function has no stackprobesize
51712   // attribute.
51713   unsigned StackProbeSize = 4096;
51714   const Function &Fn = MF.getFunction();
51715   if (Fn.hasFnAttribute("stack-probe-size"))
51716     Fn.getFnAttribute("stack-probe-size")
51717         .getValueAsString()
51718         .getAsInteger(0, StackProbeSize);
51719   return StackProbeSize;
51720 }
51721 
51722 Align X86TargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
51723   if (ML->isInnermost() &&
51724       ExperimentalPrefInnermostLoopAlignment.getNumOccurrences())
51725     return Align(1ULL << ExperimentalPrefInnermostLoopAlignment);
51726   return TargetLowering::getPrefLoopAlignment();
51727 }
51728